码迷,mamicode.com
首页 > Web开发 > 详细

hibernate关系映射

时间:2016-09-27 19:20:04      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

一、一对多映射(one-to-many)

XML配置文件:

 1 <!DOCTYPE hibernate-configuration PUBLIC
 2     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 3     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 4 
 5 <hibernate-configuration>
 6 <session-factory>
 7     <!-- 配置连接目标数据库的属性 -->
 8     <property name="connection.driver_class">
 9         oracle.jdbc.OracleDriver
10     </property>
11     <property name="connection.url">
12         jdbc:oracle:thin:@127.0.0.1:1521:xe
13     </property>
14     <property name="connection.username">etc1616</property>
15     <property name="connection.password">123</property>
16 
17     <!-- 配置方言 -->
18     <property name="dialect">
19         org.hibernate.dialect.Oracle10gDialect
20     </property>
21 
22     <!-- 是否要显示Hibernate生成的sql语句 -->
23     <property name="show_sql">true</property>
24     <!-- 是否要格式化显示出的SQL -->
25     <property name="format_sql">true</property>
26 
27     <!-- 打开自动创建DDL -->
28      <property name="hbm2ddl.auto">update</property> 
29 
30     <!-- 配置C3P0连接池组件 
31     <property name="c3p0.max_size">5</property>
32     <property name="c3p0.min_size">2</property>
33     <property name="c3p0.timeout">5000</property>
34     <property name="c3p0.idle_test_period">3000</property>
35     <property name="c3p0.acquire_increment">1</property>
36     <property name="c3p0.max_statements">150</property>
37     -->
38     <!-- 开启二级缓存 
39     <property name="cache.use_second_level_cache">true</property>-->
40     <!-- 指定二级缓存供应商 
41     <property name="cache.region.factory_class">
42         org.hibernate.cache.ehcache.EhCacheRegionFactory
43     </property>
44     -->
45     
46 
47     <!-- 开启查询缓存 
48     <property name="cache.use_query_cache">true</property>-->
49     <!-- 读取映射文件 -->
50     <!--<mapping resource="com/hbm/entity/Account.hbm.xml" />-->
51     <!-- <mapping resource="com/hbm/entity/Student.hbm.xml" />
52     <mapping resource="com/hbm/entity/Class.hbm.xml" /> -->
53     <!-- 读取实体 -->
54     <!-- <mapping class="com.hbm.entity.Book" />
55     <mapping class="com.hbm.entity.BookInfo" />
56     <mapping class="com.hbm.entity.Customer" />
57     <mapping class="com.hbm.entity.Order" /> 
58     <mapping class="com.hbm.entity.Role" />
59     <mapping class="com.hbm.entity.User" />-->
60     <mapping class="com.hbm.entity.Category" /> 
61     <mapping class="com.hbm.entity.Product" />
62     <!-- <mapping class="com.hbm.entity.User" />
63     <mapping class="com.hbm.entity.Role" /> -->
64     
65 </session-factory>
66 </hibernate-configuration>

Product类:

 1 package com.hbm.entity;
 2 
 3 import javax.persistence.Column;
 4 import javax.persistence.Entity;
 5 import javax.persistence.FetchType;
 6 import javax.persistence.GeneratedValue;
 7 import javax.persistence.Id;
 8 import javax.persistence.JoinColumn;
 9 import javax.persistence.ManyToOne;
10 import javax.persistence.Table;
11 import org.hibernate.annotations.GenericGenerator;
12 
13 
14 @Entity
15 @Table(name = "product")
16 public class Product {
17 
18       private Integer id;
19       private Category category;
20       private String name;
21       private String price;
22       private String descripton;
23         
24      
25      public Product() {
26          // TODO Auto-generated constructor stub
27      }
28     
29      public Product(Category category, String name, String price,String descripton) {
30           this.category = category;
31           this.name = name;
32           this.price = price;
33           this.descripton = descripton;
34           
35      }
36      
37      @Id
38      @GenericGenerator(name = "generator", strategy = "increment")
39      @GeneratedValue(generator = "generator")
40      @Column(name = "id", unique = true, nullable = false)
41      public Integer getId() {
42          return this.id;
43      }
44     
45      public void setId(Integer id) {
46          this.id = id;
47       
48      }
49     
50      //延迟加载:多对一方式
51      //关联信息:外键name = "category_id"
52      @ManyToOne(fetch = FetchType.LAZY)
53      @JoinColumn(name = "category_id")
54      public Category getCategory() {
55          return this.category;
56      }
57     
58      public void setCategory(Category category) {
59          this.category = category;
60      }
61     
62      @Column(name = "name", length = 500)
63      public String getName() {
64          return this.name;
65      }
66     
67      public void setName(String name) {
68          this.name = name;
69      }
70     
71      @Column(name = "price", length = 10)
72      public String getPrice() {
73          return this.price;
74      }
75     
76      public void setPrice(String price) {
77          this.price = price;
78      }
79     
80      @Column(name = "descripton", length = 500)
81      public String getDescripton() {
82          return this.descripton;
83      }
84     
85      public void setDescripton(String descripton) {
86          this.descripton = descripton;
87       
88      }
89 
90     @Override
91     public String toString() {
92         return "Product [id=" + id + ", category=" + category + ", name="
93                 + name + ", price=" + price + ", descripton=" + descripton
94                 + "]";
95     }
96      
97 
98 }

Category类:

 1 package com.hbm.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 import javax.persistence.CascadeType;
 6 import javax.persistence.Column;
 7 import javax.persistence.Entity;
 8 import javax.persistence.FetchType;
 9 import javax.persistence.GeneratedValue;
10 import javax.persistence.Id;
11 import javax.persistence.OneToMany;
12 import javax.persistence.Table;
13 import org.hibernate.annotations.GenericGenerator;
14 
15     
16 @Entity
17 @Table(name = "category")
18 public class Category{
19 
20     private Integer id;
21     private String name;
22     private String description;
23     private Set<Product> products = new HashSet<Product>();
24 
25      public Category() {
26          
27      }
28 
29      public Category(String name, String description, Set<Product> products) {
30          this.name = name;
31          this.description = description;
32          this.products = products;
33          
34      }
35 
36      //主键 :@Id 主键生成方式:strategy = "increment"
37      //映射表中id这个字段,不能为空,并且是唯一的
38      @Id
39      @GenericGenerator(name = "generator", strategy = "increment")
40      @GeneratedValue(generator = "generator")
41      @Column(name = "id", unique = true, nullable = false)
42      public Integer getId() {
43          return this.id;
44      }
45 
46      public void setId(Integer id) {
47          this.id = id;
48      }
49 
50      //映射表中name这个字段 ,长度是500
51      @Column(name = "name", length = 500)
52      public String getName() {
53          return this.name;
54      }
55 
56      public void setName(String name) {
57          this.name = name;
58      }
59      
60      //映射表中description这个字段 ,长度是500
61      @Column(name = "description", length = 500)
62      public String getDescription() {
63          return this.description;
64      }
65 
66      public void setDescription(String description) {
67          this.description = description;
68      }
69 
70      //级联操作:cascade = CascadeType.ALL
71      //延迟加载:fetch = FetchType.LAZY
72      //映射:mappedBy = "category"
73      //一对多方式
74      @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")
75      public Set<Product> getProducts() {
76          return this.products;
77      }
78 
79      public void setProducts(Set<Product> products) {
80          this.products = products;
81      }
82 
83     @Override
84     public String toString() {
85         return "Category [id=" + id + ", name=" + name + ", description="
86                 + description + "]";
87     }
88      
89 
90 }

 测试类:

 1 package com.hbm.test;
 2 
 3 import java.util.Set;
 4 
 5 import org.hibernate.Session;
 6 import org.hibernate.SessionFactory;
 7 import org.hibernate.Transaction;
 8 import org.junit.Test;
 9 import com.hbm.Util.HibernateUtil;
10 import com.hbm.entity.Category;
11 import com.hbm.entity.Product;
12 
13 public class Category_Test {
14     
15     
16     SessionFactory sf=HibernateUtil.getSessionFactory();
17     Session session=sf.openSession();
18     Transaction ts=session.beginTransaction();
19     
20     @Test
21     public void test1(){
22         
23         Product p=new Product();
24         p.setName("大语文");
25         p.setPrice("123");
26         p.setDescripton("编程语言");
27         
28         
29         Category c=new Category();
30         c.setId(1);
31         c.setName("李四");
32         c.setDescription("ok");
33         
34         //建立双向关联
35     
36         c.getProducts().add(p);
37         p.setCategory(c);
38         
39         session.save(c);
40         
41         ts.commit();
42         session.close();
43         
44         
45     }
46     
47     
48     @Test
49     public void test2(){
50         
51         Category c=(Category)session.get(Category.class, 1);
52         Set<Product> p=c.getProducts();
53         for(Product product:p){
54             System.out.println(product);
55         }
56         System.out.println(c);
57         ts.commit();
58         
59     }
60 
61              
62 }

 

三、多对多映射(many-to-many)

XML配置文件:

 1 <!DOCTYPE hibernate-configuration PUBLIC
 2     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 3     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 4 
 5 <hibernate-configuration>
 6 <session-factory>
 7     <!-- 配置连接目标数据库的属性 -->
 8     <property name="connection.driver_class">
 9         oracle.jdbc.OracleDriver
10     </property>
11     <property name="connection.url">
12         jdbc:oracle:thin:@127.0.0.1:1521:xe
13     </property>
14     <property name="connection.username">etc1616</property>
15     <property name="connection.password">123</property>
16 
17     <!-- 配置方言 -->
18     <property name="dialect">
19         org.hibernate.dialect.Oracle10gDialect
20     </property>
21 
22     <!-- 是否要显示Hibernate生成的sql语句 -->
23     <property name="show_sql">true</property>
24     <!-- 是否要格式化显示出的SQL -->
25     <property name="format_sql">true</property>
26 
27     <!-- 打开自动创建DDL -->
28      <property name="hbm2ddl.auto">update</property> 
29 
30     <!-- 配置C3P0连接池组件 
31     <property name="c3p0.max_size">5</property>
32     <property name="c3p0.min_size">2</property>
33     <property name="c3p0.timeout">5000</property>
34     <property name="c3p0.idle_test_period">3000</property>
35     <property name="c3p0.acquire_increment">1</property>
36     <property name="c3p0.max_statements">150</property>
37     -->
38     <!-- 开启二级缓存 
39     <property name="cache.use_second_level_cache">true</property>-->
40     <!-- 指定二级缓存供应商 
41     <property name="cache.region.factory_class">
42         org.hibernate.cache.ehcache.EhCacheRegionFactory
43     </property>
44     -->
45     
46 
47     <!-- 开启查询缓存 
48     <property name="cache.use_query_cache">true</property>-->
49     <!-- 读取映射文件 -->
50     <!--<mapping resource="com/hbm/entity/Account.hbm.xml" />-->
51     <!-- <mapping resource="com/hbm/entity/Student.hbm.xml" />
52     <mapping resource="com/hbm/entity/Class.hbm.xml" /> -->
53     <!-- 读取实体 -->
54     <!-- <mapping class="com.hbm.entity.Book" />
55     <mapping class="com.hbm.entity.BookInfo" />
56     <mapping class="com.hbm.entity.Customer" />
57     <mapping class="com.hbm.entity.Order" /> 
58     <mapping class="com.hbm.entity.Role" />
59     <mapping class="com.hbm.entity.User" />-->
60     <mapping class="com.hbm.entity.User" />
61     <mapping class="com.hbm.entity.Role" />
62     
63 </session-factory>
64 </hibernate-configuration>

User类:

 1 package com.hbm.entity;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 import javax.persistence.Entity;
 6 import javax.persistence.GeneratedValue;
 7 import javax.persistence.Id;
 8 import javax.persistence.JoinColumn;
 9 import javax.persistence.JoinTable;
10 import javax.persistence.ManyToMany;
11 
12 @Entity(name="hbl_user")
13 public class User {
14     
15     private int user_id;
16     private String user_name;
17     private List<Role> rs_id=new ArrayList<Role>();
18     
19     
20     public User() {
21         // TODO Auto-generated constructor stub
22     }
23 
24 
25     public User(int user_id, String user_name, List<Role> rs_id) {
26         super();
27         this.user_id = user_id;
28         this.user_name = user_name;
29         this.rs_id = rs_id;
30     }
31 
32     @Id
33     @GeneratedValue
34     public int getUser_id() {
35         return user_id;
36     }
37 
38 
39     public void setUser_id(int user_id) {
40         this.user_id = user_id;
41     }
42 
43     @JoinColumn
44     public String getUser_name() {
45         return user_name;
46     }
47 
48 
49     public void setUser_name(String user_name) {
50         this.user_name = user_name;
51     }
52 
53     @ManyToMany()
54     @JoinTable(
55         //中间表的自定义列名,与之相对应的关联表的主键名
56         joinColumns=@JoinColumn(name="user_id",referencedColumnName="user_id"),
57         //中间表的自定义列名,与之相对应的关联表的主键名
58         inverseJoinColumns=@JoinColumn(name="role_id",referencedColumnName="role_id")
59     )
60     public List<Role> getRs_id() {
61         return rs_id;
62     }
63 
64 
65     public void setRs_id(List<Role> rs_id) {
66         this.rs_id = rs_id;
67     }
68     
69     
70 }

Role类:

 1 package com.hbm.entity;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import javax.persistence.Column;
 7 import javax.persistence.Entity;
 8 import javax.persistence.GeneratedValue;
 9 import javax.persistence.Id;
10 import javax.persistence.ManyToMany;
11 
12 
13 @Entity(name="hbl_role")
14 public class Role {
15     
16     private  int role_id;
17     private String role_name;
18     private  double price;
19     private List<User> us_id=new ArrayList<User>();
20     
21     public Role() {
22         // TODO Auto-generated constructor stub
23     }
24 
25     public Role(int role_id, String role_name, double price, List<User> us_id) {
26         super();
27         this.role_id = role_id;
28         this.role_name = role_name;
29         this.price = price;
30         this.us_id = us_id;
31     }
32     
33     @Id
34     @GeneratedValue
35     public int getRole_id() {
36         return role_id;
37     }
38 
39     public void setRole_id(int role_id) {
40         this.role_id = role_id;
41     }
42     
43     @Column
44     public String getRole_name() {
45         return role_name;
46     }
47 
48     public void setRole_name(String role_name) {
49         this.role_name = role_name;
50     }
51 
52     @Column
53     public double getPrice() {
54         return price;
55     }
56 
57     public void setPrice(double price) {
58         this.price = price;
59     }
60 
61     @ManyToMany
62     public List<User> getUs_id() {
63         return us_id;
64     }
65 
66     public void setUs_id(List<User> us_id) {
67         this.us_id = us_id;
68     }
69     
70     
71     
72     
73     
74 }

测试类:

  1 package com.hbm.test;
  2 
  3 import java.util.Iterator;
  4 import org.hibernate.Session;
  5 import org.hibernate.SessionFactory;
  6 import org.hibernate.Transaction;
  7 import org.junit.Test;
  8 import com.hbm.Util.HibernateUtil;
  9 import com.hbm.entity.Role;
 10 import com.hbm.entity.User;
 11 
 12 public class User_Test {
 13 
 14     SessionFactory sf=HibernateUtil.getSessionFactory();
 15     Session session=sf.openSession();
 16     Transaction ts=session.beginTransaction();
 17     
 18     
 19     //插入数据
 20     @Test
 21     public void test1(){
 22         
 23         User u1=new User();
 24         u1.setUser_name("乔峰");
 25 
 26         User u2=new User();
 27         u2.setUser_name("段誉");
 28         
 29         
 30         Role c1=new Role();
 31         c1.setRole_name("丐帮帮主");
 32         c1.setPrice(100.0);
 33     
 34         Role c2=new Role();
 35         c2.setRole_name("大理王子");
 36         c2.setPrice(200.0);
 37 
 38         Role c3=new Role();
 39         c3.setRole_name("武林高手");
 40         c3.setPrice(300.0);
 41     
 42         u1.getRs_id().add(c1);
 43         u1.getRs_id().add(c3);
 44         
 45         u2.getRs_id().add(c1);
 46         u2.getRs_id().add(c2);
 47         u2.getRs_id().add(c3);
 48         
 49         c1.getUs_id().add(u1);
 50         c3.getUs_id().add(u2);
 51         
 52     
 53         session.save(u1);
 54         session.save(u2);
 55         
 56         session.save(c1);
 57         session.save(c2);
 58         session.save(c3);
 59         
 60         ts.commit();
 61         session.close();
 62         
 63         
 64     }
 65     
 66     //查询
 67     @Test
 68     public void test2(){
 69         
 70         User us =(User) session.get(User.class, 2);
 71         System.out.println("我的名字是:"+us.getUser_name());
 72         System.out.println("我的角色是:");
 73         Iterator<Role> it = us.getRs_id().iterator();
 74         while(it.hasNext()){
 75             System.out.println(it.next().getRole_name());    
 76         }
 77         
 78         ts.commit();
 79         session.close();
 80         
 81     }
 82     //删除
 83     @Test
 84     public void test3(){
 85         
 86         User us =(User) session.get(User.class, 1);
 87         Role rs =(Role) session.get(Role.class, 3);
 88         
 89         us.getRs_id().remove(rs);
 90         rs.getUs_id().remove(us);
 91         
 92         ts.commit();
 93         session.close();
 94         
 95         
 96     }
 97     //更新
 98     @Test
 99     public void test4(){
100         
101         User us =(User) session.get(User.class, 2);
102         Role rs1 =(Role) session.get(Role.class, 3);
103         Role rs2 =(Role) session.get(Role.class, 4);
104         
105         
106         us.getRs_id().remove(rs1);
107         rs1.getUs_id().remove(us);
108         
109         
110         us.getRs_id().add(rs2);
111         rs2.getUs_id().add(us);
112         
113         
114         ts.commit();    
115         session.close();
116         
117         
118     }
119     
120     
121 }

 

 

hibernate关系映射

标签:

原文地址:http://www.cnblogs.com/0lxp/p/5913785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!