Java进阶知识11 Hibernate一对多_多对一双向关联(Annotation+XML实现)

本文知识点(目录):

    1、Annotation 注解版(只是测试建表)
    2、XML版 的实现(只是测试建表)
    3、附录(Annotation 注解版CRUD操作)【注解版有个问题:插入值时,外键为null,用xml 版可以解决此问题】



1、Annotation 注解版  

1.1、在“一”的一方(Customer类)加@OneToMany;在“多”的一方(Order类)加@ManyToOne

1.2、创建Customer类和Order类

注意:必须在“一”的一方配mappedBy=”XXXX”;否则会多一个中间表,或者出现两个外键(加@JoinColumn的时候)。
          XXXX表示在“多”的一方中,定义的“一”的一方类的一个实例/对象

 1 package com.shore.model;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 import javax.persistence.Entity;
 7 import javax.persistence.GeneratedValue;
 8 import javax.persistence.GenerationType;
 9 import javax.persistence.Id;
10 import javax.persistence.OneToMany;
11 import javax.persistence.Table;
12 
13 /**
14  * @author DSHORE/2019-9-20
15  * 一对多,双向关联(注解版)
16  * 一对多双向关联:在“一”的一方加(@OneToMany),在“多”的一方加(@ManyToOne)
17  */
18 @Entity
19 @Table(name="anno_customer")
20 public class Customer {//顾客  (“一”的一方);一对多,在“一”的一方加Set;并且在该对象的get方法上加@OneToMany
21     private Integer id;
22     private String name;
23     private Integer age;
24     private Set<Order> orders = new HashSet<Order>();
25     /**
26      * List 有序,可重复,可以用index取值(get(index))
27      * Set  无序,不可重复
28      */
29     
30     @Id
31     @GeneratedValue(strategy=GenerationType.IDENTITY)
32     public Integer getId() {
33         return id;
34     }
35     public void setId(Integer id) {
36         this.id = id;
37     }
38     public String getName() {
39         return name;
40     }
41     public void setName(String name) {
42         this.name = name;
43     }
44     public Integer getAge() {
45         return age;
46     }
47     public void setAge(Integer age) {
48         this.age = age;
49     }
50     
51     @OneToMany(mappedBy="customer")   //告诉JVM在Order对象的customer中已经做了ManyToOne的映射
52     //@JoinColumn(name="customerId")
53     public Set<Order> getOrders() {
54         return orders;
55     }
56     public void setOrders(Set<Order> orders) {
57         this.orders = orders;
58     }
59 }

Order类

 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.ManyToOne;
 8 import javax.persistence.Table;
 9 
10 /**
11  * @author DSHORE/2019-9-20
12  *  一对多,单向关联(注解版)
13  */
14 @Entity
15 @Table(name="anno_order") //Order是MySQL数据库关键字。需重新定义表名
16 public class Order {//订单  (“多”的一方); 一对多,在“多”的一方加@ManyToOne
17     private Integer id;
18     private String number;
19     private Float sum;
20     private Customer customer;
21     
22     @Id
23     @GeneratedValue(strategy=GenerationType.IDENTITY)
24     public Integer getId() {
25         return id;
26     }
27     public void setId(Integer id) {
28         this.id = id;
29     }
30     public String getNumber() {
31         return number;
32     }
33     public void setNumber(String number) {
34         this.number = number;
35     }
36     public Float getSum() {
37         return sum;
38     }
39     public void setSum(Float sum) {
40         this.sum = sum;
41     }
42     
43     @ManyToOne
44     public Customer getCustomer() {
45         return customer;
46     }
47     public void setCustomer(Customer customer) {
48         this.customer = customer;
49     }
50 }

1.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.Customer" />
20         <mapping class="com.shore.model.Order" />
21     </session-factory>
22 </hibernate-configuration>

1.4、开始测试

 1 package com.shore.test;
 2 
 3 import org.hibernate.cfg.AnnotationConfiguration;
 4 import org.hibernate.tool.hbm2ddl.SchemaExport;
 5 import org.junit.Test;
 6 
 7 /**
 8  * @author DSHORE/2019-9-20
 9  *
10  */
11 public class AnnotationTest {
12     @Test
13     public void test() {//简单测试,只创建表,不插入数据
14                     //注解版,用AnnotationConfiguration()方法
15         new SchemaExport(new AnnotationConfiguration().configure()).create(
16                 false, true);
17     }
18 }

测试结果图:

     

 

 

2、XML版 的实现  

2.1、创建Customer类和Order类

 1 package com.shore.model;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 /**
 7  * @author DSHORE/2019-9-20
 8  * 一对多,双向关联(xml版)
 9  */
10 public class Customer {//顾客  (“一”的一方);一对多,在“一”的一方加Set
11     private Integer id;
12     private String name;
13     private Integer age;
14     private Set<Order> orders = new HashSet<Order>();
15     /**
16      * List 有序,可重复,可以用index取值(get(index))
17      * Set  无序,不可重复
18      */
19     
20     public Integer getId() {
21         return id;
22     }
23     public void setId(Integer id) {
24         this.id = id;
25     }
26     public String getName() {
27         return name;
28     }
29     public void setName(String name) {
30         this.name = name;
31     }
32     public Integer getAge() {
33         return age;
34     }
35     public void setAge(Integer age) {
36         this.age = age;
37     }
38     public Set<Order> getOrders() {
39         return orders;
40     }
41     public void setOrders(Set<Order> orders) {
42         this.orders = orders;
43     }
44 }

Order类

 1 package com.shore.model;
 2 
 3 /**
 4  * @author DSHORE/2019-9-20
 5  *  一对多,单向关联(xml版)
 6  */
 7 public class Order {//订单  (“多”的一方)
 8     private Integer id;
 9     private String number;
10     private Float sum;
11     private Customer customer;
12     
13     public Integer getId() {
14         return id;
15     }
16     public void setId(Integer id) {
17         this.id = id;
18     }
19     public String getNumber() {
20         return number;
21     }
22     public void setNumber(String number) {
23         this.number = number;
24     }
25     public Float getSum() {
26         return sum;
27     }
28     public void setSum(Float sum) {
29         this.sum = sum;
30     }
31     public Customer getCustomer() {
32         return customer;
33     }
34     public void setCustomer(Customer customer) {
35         this.customer = customer;
36     }
37 }

2.2、创建 Customer.hbm.xml 配置文件和 Order.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="Customer" table="customer_xml">  
 8         <id name="id"> 
 9             <generator class="native"/>
10         </id>
11         <property name="name" type="java.lang.String"/>
12         <property name="age" type="java.lang.Integer"/>
13         <set name="orders"> 
14             <key column="customerId"></key>
15             <one-to-many class="com.shore.model.Order"/>
16         </set>
17     </class>
18 </hibernate-mapping>

Order.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="Order" table="order_xml">  
 8         <id name="id"> 
 9             <generator class="native"/>
10         </id>
11         <property name="number" type="java.lang.String"/>
12         <property name="sum" type="java.lang.Float"/>
13         <many-to-one name="customer" column="customerId"/>
14     </class>
15 </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.Customer" />
20         <mapping class="com.shore.model.Order" /> -->
21         <mapping resource="com/shore/model/Customer.hbm.xml" />
22         <mapping resource="com/shore/model/Order.hbm.xml" />
23     </session-factory>
24 </hibernate-configuration>

2.4、开始测试

 1 package com.shore.test;
 2 
 3 import org.hibernate.cfg.Configuration;
 4 import org.hibernate.tool.hbm2ddl.SchemaExport;
 5 import org.junit.Test;
 6 
 7 /**
 8  * @author DSHORE/2019-9-20
 9  *
10  */
11 public class AnnotationTest {
12     @Test
13     public void test() {//简单测试,只创建表,不插入数据
14                     //注解版,用Configuration()方法
15         new SchemaExport(new Configuration().configure()).create(
16                 false, true);
17     }
18 }

测试结果图:

     

 

 

 

  附录  

1、一对多_多对一,双向关联注解版CRUD操作

1.1、创建Customer类和Order类

 1 package com.shore.model;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 import javax.persistence.CascadeType;
 7 import javax.persistence.Entity;
 8 import javax.persistence.GeneratedValue;
 9 import javax.persistence.GenerationType;
10 import javax.persistence.Id;
11 import javax.persistence.OneToMany;
12 import javax.persistence.Table;
13 
14 /**
15  * @author DSHORE/2019-9-20
16  * 一对多_多对一(注解版) CRUD操作
17  * 一对多双向关联:在“一”的一方加(@OneToMany),在“多”的一方加(@ManyToOne)【即:一对多_多对一】
18  */
19 @Entity
20 @Table(name="anno_customer")
21 public class Customer {//顾客  (“一”的一方);一对多,在“一”的一方加Set;并且在该对象的get方法上加@OneToMany
22     private Integer id;
23     private String name;
24     private Integer age;
25     private Set<Order> orders = new HashSet<Order>();
26     /**
27      * List 有序,可重复,可以用index取值(get(index))
28      * Set  无序,不可重复
29      */
30     
31     @Id
32     @GeneratedValue(strategy=GenerationType.IDENTITY)
33     public Integer getId() {
34         return id;
35     }
36     public void setId(Integer id) {
37         this.id = id;
38     }
39     public String getName() {
40         return name;
41     }
42     public void setName(String name) {
43         this.name = name;
44     }
45     public Integer getAge() {
46         return age;
47     }
48     public void setAge(Integer age) {
49         this.age = age;
50     }
51     
52     /**
53      * cascade:级联(进行CRUD操作时,需要加上cascade=CascadeType.ALL。all表示:包括增删改查这几个操作)。
54      * mappedBy:映射(告诉JVM在Order对象的customer中已经做了ManyToOne的映射)。
55      */
56     @OneToMany(mappedBy="customer",cascade=CascadeType.ALL) 
57     public Set<Order> getOrders() {
58         return orders;
59     }
60     public void setOrders(Set<Order> orders) {
61         this.orders = orders;
62     }
63 }

Order类

 1 package com.shore.model;
 2 
 3 import javax.persistence.CascadeType;
 4 import javax.persistence.Entity;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.GenerationType;
 7 import javax.persistence.Id;
 8 import javax.persistence.ManyToOne;
 9 import javax.persistence.Table;
10 
11 /**
12  * @author DSHORE/2019-9-20
13  *  一对多_多对一(注解版) CRUD操作
14  */
15 @Entity
16 @Table(name="anno_order") //Order是MySQL数据库关键字。需重新定义表名
17 public class Order {//订单  (“多”的一方); 一对多,在“多”的一方加@ManyToOne
18     private Integer id;
19     private String number;
20     private Float sum;
21     private Customer customer;
22     
23     @Id
24     @GeneratedValue(strategy=GenerationType.IDENTITY)
25     public Integer getId() {
26         return id;
27     }
28     public void setId(Integer id) {
29         this.id = id;
30     }
31     public String getNumber() {
32         return number;
33     }
34     public void setNumber(String number) {
35         this.number = number;
36     }
37     public Float getSum() {
38         return sum;
39     }
40     public void setSum(Float sum) {
41         this.sum = sum;
42     }
43     
44     @ManyToOne(cascade=CascadeType.ALL) //cascade:级联
45     public Customer getCustomer() {
46         return customer;
47     }
48     public void setCustomer(Customer customer) {
49         this.customer = customer;
50     }
51 }

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/hibernate2</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">update</property>
18 
19         <mapping class="com.shore.model.Customer" />
20         <mapping class="com.shore.model.Order" />
21     </session-factory>
22 </hibernate-configuration>

1.3、开始测试

  1 package com.shore.test;
  2 
  3 import java.util.HashSet;
  4 import java.util.Set;
  5 
  6 import org.hibernate.Session;
  7 import org.hibernate.SessionFactory;
  8 import org.hibernate.Transaction;
  9 import org.hibernate.cfg.AnnotationConfiguration;
 10 import org.junit.AfterClass;
 11 import org.junit.BeforeClass;
 12 import org.junit.Test;
 13 
 14 import com.shore.model.Customer;
 15 import com.shore.model.Order;
 16 
 17 /**
 18  * @author DSHORE/2019-9-20
 19  * 一对多_多对一(注解版) CRUD操作
 20  */
 21 public class MyTest {
 22     public static SessionFactory sessionFactory = null;
 23     public static Session session = null;
 24 
 25     @BeforeClass
 26     public static void buildSessionFactory() {
 27         sessionFactory = new AnnotationConfiguration().configure()
 28                 .buildSessionFactory();
 29     }
 30 
 31     @AfterClass
 32     public static void close() {
 33         session.close();
 34         sessionFactory.close();
 35     }
 36 
 37     /**
 38      * Create
 39      */
 40     //多对一
 41     @Test
 42     public void testSaveOrder() {//以“多”的一方为主,进行测试
 43         session = sessionFactory.openSession();
 44         Transaction transaction = session.beginTransaction();
 45         Customer customer = new Customer();
 46         customer.setName("张三");
 47         customer.setAge(18);
 48         
 49         Order order = new Order();
 50         order.setNumber("1008");
 51         order.setSum(8.90f);
 52         order.setCustomer(customer);
 53         // session.save(customer); //已经使用了级联,这句话不需要了
 54         session.save(order);
 55         transaction.commit();
 56     }
 57 
 58     //一对多        //【要么使用上面的testSaveOrder()方法,以“多”的一方为主,添加数据;要就用xml配置文件的方式来做】
 59     @Test //一对多双向关联,以“一”的一方为主,进行测试,多的一方Order表中的外键(customer_id)是空的(null);解决方法在最下面“补充”处
 60     public void testSaveCustomer() {//以“一”的一方为主,进行测试  
 61         session = sessionFactory.openSession();
 62         Transaction transaction = session.beginTransaction();
 63         Order order1 = new Order();
 64         order1.setNumber("2008");
 65         order1.setSum(9.90f);
 66         Order order2 = new Order();
 67         order2.setNumber("2010");
 68         order2.setSum(99.90f);
 69         
 70         Customer customer = new Customer();
 71         customer.setName("李四");
 72         customer.setAge(20);
 73         
 74         Set<Order> orders = new HashSet<Order>();
 75         orders.add(order1);
 76         orders.add(order2);
 77         customer.setOrders(orders);
 78         session.save(customer);
 79         transaction.commit();
 80     }
 81     
 82     /**
 83      * Read   
 84      * get:即时查询
 85      * load:懒加载
 86      */
 87     //多对一
 88     @Test
 89     public void testGetOrder() {
 90         session = sessionFactory.openSession();
 91         Transaction transaction = session.beginTransaction();
 92         Order order = (Order) session.get(Order.class, 1); //即时查询
 93         transaction.commit();
 94         
 95         System.out.println("id:"+order.getId());
 96         System.out.println("number:"+order.getNumber());
 97         System.out.println("customer:"+order.getCustomer());
 98     }
 99     
100     //一对多
101     @Test
102     public void testGetCustomer() {
103         session = sessionFactory.openSession();
104         Transaction transaction = session.beginTransaction();
105         Customer customer = (Customer) session.get(Customer.class, 1);
106         transaction.commit();
107         
108         System.out.println("id:"+customer.getId());
109         System.out.println("name:"+customer.getName());
110         System.out.println("orders:"+customer.getOrders());
111         System.out.println("orders-size:"+customer.getOrders().size());
112     }
113     
114     /**
115      * Update
116      */
117     //多对一
118     @Test
119     public void testUpdateOrderProperties(){
120         session = sessionFactory.openSession();
121         Transaction transaction = session.beginTransaction();
122         Order order = (Order) session.load(Order.class, 2); //懒加载
123         Customer customer = order.getCustomer();
124         customer.setAge(20);
125         customer.setName("赵六");
126         order.setCustomer(customer);
127         session.save(order);
128         transaction.commit();
129     }
130     
131     //多对一
132     @Test
133     public void testUpdateOrderPK(){
134         session = sessionFactory.openSession();
135         Transaction transaction = session.beginTransaction();
136         Order order = (Order) session.load(Order.class, 1);
137         Customer customer = (Customer) session.load(Customer.class, 2);
138         order.setCustomer(customer);
139         session.save(order);
140         transaction.commit();
141     }
142     
143     //一对多
144     @Test
145     public void testUpdateCustomer(){
146         session = sessionFactory.openSession();
147         Transaction transaction = session.beginTransaction();
148         Customer customer = (Customer) session.load(Customer.class, 1);
149         Object[] objects = customer.getOrders().toArray();
150         Order order = (Order) objects[0];
151         order.setSum(20.00f);
152         session.save(order);
153         transaction.commit();
154     }
155     
156     /**
157      * Delete
158      */
159     //多对一:多个order对应一个customer
160     @Test
161     public void testDeleteOrder(){//因为已经级联,所以删除id=3的订单时,对应的顾客也同时被删除
162         session = sessionFactory.openSession();
163         Transaction transaction = session.beginTransaction();
164             
165         Order order = (Order) session.load(Order.class, 3);
166         session.delete(order);
167         
168         transaction.commit();
169     }
170     
171     //一对多
172     @Test
173     public void testDeleteCustomer(){
174         session = sessionFactory.openSession();
175         Transaction transaction = session.beginTransaction();
176         
177         Customer customer = (Customer) session.get(Customer.class, 2);
178         session.delete(customer);
179         
180         transaction.commit();
181     }
182 }

 

补充:解决上面附录中第1.3小点测试类中的第二个测试方法testSaveCustomer()的问题。

该方法向数据库中插入数据时,Order表中的外键customer_id为null,一直插不进来有效的值。解决方法如下:首先我们得将注解的方式改为XML的方式,并在“一”的一方的xml配置文件加上inverse="false",且还需要在两方的xml配置文件中加上cascade="all"。即可解决外键一直插不进值得问题。

cascade关系有以下几种:
  all: 所有情况下均进行关联操作,即save-update和delete。
  none: 所有情况下均不进行关联操作。这是默认值。
  save-update: 在执行save/update/saveOrUpdate时进行关联操作。
  delete: 在执行delete 时进行关联操作。
  all-delete-orphan: 当一个节点在对象图中成为孤儿节点时,删除该节点

inverse 维护关系:
    inverse的值是boolean类型的,也就是只能设置为true或false。 如果一方的映射文件中设置为true,说明在映射关系(一对多,多对多等)中让对方来维护关系。如果为false,就自己来维护关系。默认值是false。 并且这属性只能在一端设置。比如一对多,这个一端。也就是在有set集合的这方设置。
  1、维护外键的关系:通俗点讲,就是由哪一方去设置这个被外键约束的字段的值。
  2、维护级联的关系:就是说如果让对方维护关系,则自己方的级联将会失效,对方设置的级联有用,如果自己维护关系,则自己方的级联会有用,但是对方设置的级联就会失效。

 

下面我们来看具体的代码实现:

Customer和Order实体类上面“附录”中有,就不在帖出来了。这个是xml版本的,把实体类中的所有注解去掉即可,其他的都不变。

1、创建 Customer.hbm.xml 配置文件和 Order.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="Customer" table="customer_xml">  
 8         <id name="id"> 
 9             <generator class="native"/>
10         </id>
11         <property name="name" type="java.lang.String"/>
12         <property name="age" type="java.lang.Integer"/>
13         
14         <!-- 如果inverse="true",让对方维护关系,此时这里的cascade(级联)设置没什么用,因为自身不维护关系,它也就失效了。 -->
15         <set name="orders" inverse="false" cascade="all"> <!-- 解决外键为null的问题,主要在此 inverse="false" -->
16             <key column="customerId"></key>
17             <one-to-many class="com.shore.model.Order"/>
18         </set>
19     </class>
20 </hibernate-mapping>

Order.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="Order" table="order_xml">  
 8         <id name="id"> 
 9             <generator class="native"/>
10         </id>
11         <property name="number" type="java.lang.String"/>
12         <property name="sum" type="java.lang.Float"/>
13         <many-to-one name="customer" column="customerId" cascade="all"/>  <!-- cascade:级联 -->
14     </class>
15 </hibernate-mapping>

hibernate.cfg.xml 和上面的一样,此处也不贴出来了。

2、测试类,开始测试

 1 package com.shore.test;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 import org.hibernate.Session;
 7 import org.hibernate.SessionFactory;
 8 import org.hibernate.Transaction;
 9 import org.hibernate.cfg.AnnotationConfiguration;
10 import org.junit.AfterClass;
11 import org.junit.BeforeClass;
12 import org.junit.Test;
13 
14 import com.shore.model.Customer;
15 import com.shore.model.Order;
16 
17 /**
18  * @author DSHORE/2019-9-20
19  *
20  */
21 public class CRUDTest {
22     public static SessionFactory sessionFactory = null;
23     public static Session session = null;
24 
25     @BeforeClass
26     public static void buildSessionFactory() {
27         sessionFactory = new AnnotationConfiguration().configure()
28                 .buildSessionFactory();
29     }
30 
31     @AfterClass
32     public static void close() {
33         session.close();
34         sessionFactory.close();
35     }
36     /**
37      * Create
38      */
39     //多对一
40     @Test
41     public void testSaveOrder() {//以“多”的一方为主,进行测试
42         session = sessionFactory.openSession();
43         Transaction transaction = session.beginTransaction();
44         Customer customer = new Customer();
45         customer.setName("张三");
46         customer.setAge(18);
47         
48         Order order = new Order();
49         order.setNumber("1008");
50         order.setSum(8.90f);
51         order.setCustomer(customer);
52         // session.save(customer); //已经使用了级联,这句话不需要了
53         session.save(order);
54         transaction.commit();
55     }
56 
57     //一对多
58     @Test   //一对多双向关联,以“一”的一方为主,进行测试,多的一方Order表中的外键(customer_id)是空的(null)
59     public void testSaveCustomer() {//以“一”的一方为主,进行测试
60         session = sessionFactory.openSession();
61         Transaction transaction = session.beginTransaction();
62         Order order1 = new Order();
63         order1.setNumber("2008");
64         order1.setSum(19.90f);
65         Order order2 = new Order();
66         order2.setNumber("2010");
67         order2.setSum(99.90f);
68         
69         Customer customer = new Customer();
70         customer.setName("李四");
71         customer.setAge(20);
72         
73         Set<Order> orders = new HashSet<Order>();
74         orders.add(order1);
75         orders.add(order2);
76         customer.setOrders(orders);
77         session.save(customer);
78         transaction.commit();
79     }
80 }

     

 

 

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/11560433.html

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

posted @ 2019-09-20 23:45  DSHORE  阅读(398)  评论(0编辑  收藏  举报