联合主键关联

 @JoinColumns()

Husband 和 Wife 是一对一的关系,并且 Wife 的 id和name字段是联合主键。

Annotation 配置:

  WifePK

 1 package com.bjsxt.hibernate;
 2 
 3 public class WifePK {
 4     
 5     private Integer id;
 6     
 7     private String name;
 8     
 9     public Integer getId() {
10         return id;
11     }
12 
13     public void setId(Integer id) {
14         this.id = id;
15     }
16 
17     public String getName() {
18         return name;
19     }
20 
21     public void setName(String name) {
22         this.name = name;
23     }
24 }
View Code

  Wife

 1 package com.bjsxt.hibernate;
 2 
 3 import javax.persistence.Entity;
 4 import javax.persistence.Id;
 5 import javax.persistence.IdClass;
 6 
 7 @Entity
 8 @IdClass(value=WifePK.class)//使用第三种联合主键配置方法
 9 public class Wife {
10     
11     private Integer id;
12     
13     private String name;
14     
15     private int age;
16 
17     @Id
18     public Integer getId() {
19         return id;
20     }
21 
22     public void setId(Integer id) {
23         this.id = id;
24     }
25 
26     @Id
27     public String getName() {
28         return name;
29     }
30 
31     public void setName(String name) {
32         this.name = name;
33     }
34 
35     public int getAge() {
36         return age;
37     }
38 
39     public void setAge(int age) {
40         this.age = age;
41     }
42 }
View Code

  Husband

 1 package com.bjsxt.hibernate;
 2 
 3 import javax.persistence.Entity;
 4 import javax.persistence.GeneratedValue;
 5 import javax.persistence.Id;
 6 import javax.persistence.JoinColumn;
 7 import javax.persistence.JoinColumns;
 8 import javax.persistence.OneToOne;
 9 
10 @Entity
11 public class Husband {
12     
13     private Integer id;
14     
15     private String name;
16 
17     private Wife wife;
18     
19     @Id
20     @GeneratedValue
21     public Integer getId() {
22         return id;
23     }
24 
25     public String getName() {
26         return name;
27     }
28 
29     @OneToOne//一对一的关系
30     //JoinColumns 配置也可以不加,hibernate 会自动帮我们加
31     @JoinColumns(
32             {
33                 @JoinColumn(name="wifeId",referencedColumnName="id"),
34                 @JoinColumn(name="wifeName",referencedColumnName="name")
35             }
36     )
37     public Wife getWife() {
38         return wife;
39     }
40 
41     public void setId(Integer id) {
42         this.id = id;
43     }
44 
45     public void setName(String name) {
46         this.name = name;
47     }
48 
49     public void setWife(Wife wife) {
50         this.wife = wife;
51     }
52 }
View Code

XML 配置:

  参考 ID 生成策略的最后一部分XML联合主键的生成。

jar包链接: https://pan.baidu.com/s/1nvHiUfv 密码: fjuy

代码链接: https://pan.baidu.com/s/1sl4j0Vr 密码: nnf6

posted @ 2017-04-19 15:12  流年如水烟雨随风  阅读(694)  评论(0编辑  收藏  举报