zoukankan      html  css  js  c++  java
  • Java进阶知识08 Hibernate一对一双向外键关联(Annotation+XML实现)

    1、Annotation 注解版  

    1.1、创建Husband类和Wife类

     1 package com.shore.model;
     2 
     3 import javax.persistence.Entity;
     4 import javax.persistence.GeneratedValue;
     5 import javax.persistence.GenerationType;
     6 import javax.persistence.Id;
     7 import javax.persistence.OneToOne;
     8 
     9 import org.hibernate.annotations.Type;
    10 
    11 /**
    12  * @author DSHORE/2019-9-18
    13  * 一对一,双向关联(注解版14  */
    15 @Entity
    16 public class Husband {//主表 类
    17     private Integer id;
    18     private String name;
    19     private Boolean sex;
    20     private Wife wife;
    21 
    22     @Id
    23     @GeneratedValue(strategy = GenerationType.AUTO) //主键生成策略(使用test()测试时,必须加上这个,否会报错:id生成错误)
    24     public Integer getId() {
    25         return id;
    26     }
    27     public void setId(Integer id) {
    28         this.id = id;
    29     }
    30     public String getName() {
    31         return name;
    32     }
    33     public void setName(String name) {
    34         this.name = name;
    35     }
    36     
    37     @Type(type = "yes_no") //数据库中,会以Y/N的形式插入到sex字段中
    38     public Boolean getSex() {
    39         return sex;
    40     }
    41     public void setSex(Boolean sex) {
    42         this.sex = sex;
    43     }
    44     
    45     @OneToOne(mappedBy="husband")//映射:从表wife映射主表husband。如果不要(mappedBy="husband"),主表husband将会多一个没必要的字段wife_id(外键)
    46     public Wife getWife() {
    47         return wife;
    48     }
    49     public void setWife(Wife wife) {
    50         this.wife = wife;
    51     }
    52 }

    Wife类

     1 package com.shore.model;
     2 
     3 import javax.persistence.Entity;
     4 import javax.persistence.GeneratedValue;
     5 import javax.persistence.GenerationType;
     6 import javax.persistence.Id;
     7 import javax.persistence.JoinColumn;
     8 import javax.persistence.OneToOne;
     9 
    10 import org.hibernate.annotations.Type;
    11 
    12 /**
    13  * @author DSHORE/2019-9-18
    14  * 一对一,双向关联(注解版)
    15  */
    16 @Entity
    17 public class Wife {//从表
    18     private Integer id;
    19     private String name;
    20     private Boolean sex;
    21     private Husband husband;
    22 
    23     @Id
    24     @GeneratedValue(strategy = GenerationType.AUTO) //主键生成策略(使用test1测试时,必须加上这个,否会报错:id生成错误)
    25     public Integer getId() {
    26         return id;
    27     }
    28     public void setId(Integer id) {
    29         this.id = id;
    30     }
    31     public String getName() {
    32         return name;
    33     }
    34     public void setName(String name) {
    35         this.name = name;
    36     }
    37     
    38     @Type(type = "yes_no") //数据库中,会以Y/N的形式插入到sex字段中
    39     public Boolean getSex() {
    40         return sex;
    41     }
    42     public void setSex(Boolean sex) {
    43         this.sex = sex;
    44     }
    45     
    46     @OneToOne  //默认创建的外键名称:husband_id
    47     @JoinColumn(name="husbandId") //创建表时,指定该外键名:husbandId
    48     public Husband getHusband() {
    49         return husband;
    50     }
    51     public void setHusband(Husband husband) {
    52         this.husband = husband;
    53     }
    54 }

    1.2、创建hibernate.cfg.xml核心配置文件

     1 <?xml version='1.0' encoding='utf-8'?>
     2 <!DOCTYPE hibernate-configuration PUBLIC
     3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
     5 
     6 <hibernate-configuration>
     7     <session-factory>
     8         <!-- Database connection settings -->
     9         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    10         <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    11         <property name="connection.username">root</property>
    12         <property name="connection.password">123456</property>
    13 
    14         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    15         <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    16         <property name="show_sql">true</property>
    17         <property name="hbm2ddl.auto">create</property>
    18 
    19         <mapping class="com.shore.model.Husband" />
    20         <mapping class="com.shore.model.Wife" />
    21     </session-factory>
    22 </hibernate-configuration>

    1.3、开始测试

     1 package com.shore.test;
     2 
     3 import org.hibernate.Session;
     4 import org.hibernate.SessionFactory;
     5 import org.hibernate.Transaction;
     6 import org.hibernate.cfg.AnnotationConfiguration;
     7 import org.junit.AfterClass;
     8 import org.junit.BeforeClass;
     9 import org.junit.Test;
    10 
    11 import com.shore.model.Husband;
    12 import com.shore.model.Wife;
    13 
    14 /**
    15  * @author DSHORE/2019-9-18
    16  *
    17  */
    18 public class AnnotationTest {
    19     public static SessionFactory sessionFactory = null;
    20     public static Session session = null;
    21     
    22     @BeforeClass
    23     public static void buildSessionFactory() {
    24         sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
    25     }
    26     
    27     @AfterClass
    28     public static void close() {
    29         session.close();
    30         sessionFactory.close();
    31     }
    32     
    33     @Test
    34     public void test(){//数据库表创建完后,插入数据
    35         session = sessionFactory.openSession(); //打开一个session
    36         Transaction transaction = session.beginTransaction(); //开启一个事务
    37         Husband husband = new Husband();
    38         husband.setName("黄晓明");
    39         husband.setSex(true);//
    40         session.save(husband);
    41         
    42         Wife wife = new Wife();
    43         wife.setName("AnglaBaby");
    44         wife.setSex(false);//
    45         wife.setHusband(husband);
    46         session.save(wife);
    47         transaction.commit(); //事务提交
    48     }
    49 }

    测试结果图:

        

    2、XML实现 版  

    2.1、创建husband类和wife类

     1 package com.shore.model;
     2 
     3 /**
     4  * @author DSHORE/2019-9-18
     5  * 一对一,双向关联(xml版)
     6  */
     7 public class Husband {//主表 类
     8     private Integer id;
     9     private String name;
    10     private Boolean sex;
    11     private Wife wife;
    12 
    13     public Integer getId() {
    14         return id;
    15     }
    16     public void setId(Integer id) {
    17         this.id = id;
    18     }
    19     public String getName() {
    20         return name;
    21     }
    22     public void setName(String name) {
    23         this.name = name;
    24     }
    25     public Boolean getSex() {
    26         return sex;
    27     }
    28     public void setSex(Boolean sex) {
    29         this.sex = sex;
    30     }
    31     public Wife getWife() {
    32         return wife;
    33     }
    34     public void setWife(Wife wife) {
    35         this.wife = wife;
    36     }
    37 }

    wife类

     1 package com.shore.model;
     2 
     3 /**
     4  * @author DSHORE/2019-9-18
     5  * 一对一,双向关联(xml版)
     6  */
     7 public class Wife {//从表 类
     8     private Integer id;
     9     private String name;
    10     private Boolean sex;
    11     private Husband husband;
    12 
    13     public Integer getId() {
    14         return id;
    15     }
    16     public void setId(Integer id) {
    17         this.id = id;
    18     }
    19     public String getName() {
    20         return name;
    21     }
    22     public void setName(String name) {
    23         this.name = name;
    24     }
    25     public Boolean getSex() {
    26         return sex;
    27     }
    28     public void setSex(Boolean sex) {
    29         this.sex = sex;
    30     }
    31     public Husband getHusband() {
    32         return husband;
    33     }
    34     public void setHusband(Husband husband) {
    35         this.husband = husband;
    36     }
    37 }

    2.2、创建 Husband.hbm.xml 配置文件和 Wife.hbm.xml 配置文件

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC
     3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5         
     6 <hibernate-mapping package="com.shore.model">
     7     <class name="Husband" table="husband_xml">  
     8         <id name="id"> 
     9             <generator class="native"/>
    10         </id>
    11         <property name="name" type="java.lang.String"/>
    12         <property name="sex" type="yes_no"/>
    13         
    14        <!-- 这里不能这么配置,否则主表husband里面会多一个没必要的外键wife_id
    15         <many-to-one name="wife" column="wife_id" unique="true"/> -->
    16         
    17         <!-- 应该这样配置 -->
    18         <one-to-one name="wife" property-ref="husband"/>
    19     </class>
    20 </hibernate-mapping>

    Wife.hbm.xml 配置文件

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC
     3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5         
     6 <hibernate-mapping package="com.shore.model">
     7     <class name="Wife" table="wife_xml">  
     8         <id name="id"> 
     9             <generator class="native"/>
    10         </id>
    11         <property name="name" type="java.lang.String"/>
    12         <property name="sex" type="yes_no" />
    13         
    14         <!-- many-to-one:多对一,但加了个unique="true",就变成了一对一 -->
    15         <many-to-one name="husband" column="husband_id" unique="true"/>
    16     </class>
    17 </hibernate-mapping>

    2.3、创建hibernate.cfg.xml 核心配置文件

     1 <?xml version='1.0' encoding='utf-8'?>
     2 <!DOCTYPE hibernate-configuration PUBLIC
     3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
     5 
     6 <hibernate-configuration>
     7     <session-factory>
     8         <!-- Database connection settings -->
     9         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    10         <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
    11         <property name="connection.username">root</property>
    12         <property name="connection.password">123456</property>
    13 
    14         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    15         <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    16         <property name="show_sql">true</property>
    17         <property name="hbm2ddl.auto">create</property>
    18 
    19         <!-- <mapping class="com.shore.model.Husband" />
    20         <mapping class="com.shore.model.Wife" /> -->
    21         <mapping resource="com/shore/model/Husband.hbm.xml" />
    22         <mapping resource="com/shore/model/Wife.hbm.xml" />
    23     </session-factory>
    24 </hibernate-configuration>

    2.4、开始测试

     1 package com.shore.test;
     2 
     3 import org.hibernate.Session;
     4 import org.hibernate.SessionFactory;
     5 import org.hibernate.Transaction;
     6 import org.hibernate.cfg.Configuration;
     7 import org.junit.AfterClass;
     8 import org.junit.BeforeClass;
     9 import org.junit.Test;
    10 
    11 import com.shore.model.Husband;
    12 import com.shore.model.Wife;
    13 
    14 /**
    15  * @author DSHORE/2019-9-19
    16  *
    17  */
    18 public class XMLTest {
    19     public static SessionFactory sessionFactory = null;
    20     public static Session session = null;
    21     
    22     @BeforeClass
    23     public static void buildSessionFactory() {
    24                 //用注解版的话,Configuration()方法,得改用AnnotationConfiguration()方法
    25         sessionFactory = new Configuration().configure().buildSessionFactory();
    26     }
    27     
    28     @AfterClass
    29     public static void close() {
    30         session.close();
    31         sessionFactory.close();
    32     }
    33     
    34     @Test
    35     public void test(){//数据库表创建完后,插入数据
    36         session = sessionFactory.openSession();
    37         Transaction transaction = session.beginTransaction();
    38         Husband husband = new Husband();
    39         husband.setName("黄晓明");
    40         husband.setSex(true);//
    41         session.save(husband);
    42         
    43         Wife wife = new Wife();
    44         wife.setName("AnglaBaby");
    45         wife.setSex(false);//
    46         wife.setHusband(husband);
    47         session.save(wife);
    48         transaction.commit();//事务提交
    49     }
    50 }

    测试结果图:

        

    Hibernate一对一单向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11545058.html
    Hibernate一对一双向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11545077.html

    Hibernate多对一单向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11553213.html
    Hibernate一对多单向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11553215.html
    Hibernate一对多多对一双向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11560433.html

    Hibernate多对多单向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11568536.html
    Hibernate多对多双向关联映射(Annotation+XML实现):https://www.cnblogs.com/dshore123/p/11568963.html

    原创作者:DSHORE

    作者主页:http://www.cnblogs.com/dshore123/

    原文出自:https://www.cnblogs.com/dshore123/p/11545077.html

    版权声明:欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

  • 相关阅读:
    数据结构 队列
    数据结构 堆栈
    UNP学习 广播
    UNP学习 路由套接口
    QTcpSocket发送结构体
    线性表及实现
    [转]理解WSRF之一 使用WS-ResourceProperties (整理自IBM网站)
    详解x86、IA-32、IA-64等CPU系列
    gsoap框架下的onvif程序流程分析
    【LeetCode】从contest-21开始。(一般是10个contest写一篇文章)
  • 原文地址:https://www.cnblogs.com/dshore123/p/11545077.html
Copyright © 2011-2022 走看看