Hibernate注解(三)

关系映射级别注解

1.一对一单向外键

2.一对一双向外键关联

3.一对一双向外键联合主键

4.多对一单向外键关联

5.一对多单向外键关联

6.一对多双向外键关联

7.多对多单向外键关联

8.多对多双向外键关联

(一)一对一单向外键

@OneToOne(cascade=CascadeType.ALL)//cascade级联关系

@JoinColumn(name="pid",unique=true)//被控类的外键,写在主控类的表中,pid在主表中充当外键

注意:保存时因该先保存外键对象,再保存主表对象

主控方:含有外键的一方,被控方:被引用主键的一方。

例子:

被控方IdCard:

 1 package com.relationannotation.entity.oto_pk;
 2 
 3 import javax.persistence.Column;
 4 import javax.persistence.Entity;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.Id;
 7 
 8 import org.hibernate.annotations.GenericGenerator;
 9 
10 /** 
11  * 身份证类
12  *
13  * @author mrq
14  */
15 @Entity
16 public class IdCard {
17     
18     @Id
19     @GeneratedValue(generator="pid")
20     @GenericGenerator(name="pid", strategy = "assigned")
21     @Column(length=18)
22     private String pid;//身份证号码
23     
24     private String sname;//学生姓名
25 
26     public IdCard(){
27     }
28     
29     public IdCard(String pid, String sname) {
30         this.pid = pid;
31         this.sname = sname;
32     }
33 
34 
35     public String getPid() {
36         return pid;
37     }
38 
39     public void setPid(String pid) {
40         this.pid = pid;
41     }
42 
43     public String getSname() {
44         return sname;
45     }
46 
47     public void setSname(String sname) {
48         this.sname = sname;
49     }
50     
51     
52     
53     
54     
55 }
View Code

主控方Students:

 1 package com.relationannotation.entity.oto_pk;
 2 
 3 import java.util.Date;
 4 
 5 import javax.persistence.CascadeType;
 6 import javax.persistence.Entity;
 7 import javax.persistence.GeneratedValue;
 8 import javax.persistence.GenerationType;
 9 import javax.persistence.Id;
10 import javax.persistence.JoinColumn;
11 import javax.persistence.OneToOne;
12 
13 /** 
14  * 学生实体类
15  * 
16  */
17 @Entity//(name = "t_students")
18 public class Students{
19     
20     
21     private IdCard card;
22     
23     private int sid;//学号
24     //@Id/* 联合主键,需要实现Serializable接口*/
25     //@Column(length = 8)/* 列注解,length属性值字段的长度*/
26     private String gender;//出生日期
27     private Date birthday;//出生日期
28     private String major;//专业
29     
30     public Students() {
31     }
32 
33     public Students(IdCard card, String gender, Date birthday, String major) {
34         this.card = card;
35         this.gender = gender;
36         this.birthday = birthday;
37         this.major = major;
38     }
39 
40     @Id
41     @GeneratedValue(strategy=GenerationType.AUTO)//默认是自增长的
42     public int getSid() {
43         return sid;
44     }
45 
46     public void setSid(int sid) {
47         this.sid = sid;
48     }
49 
50 
51     public String getGender() {
52         return gender;
53     }
54 
55     public void setGender(String gender) {
56         this.gender = gender;
57     }
58 
59     public Date getBirthday() {
60         return birthday;
61     }
62 
63     public void setBirthday(Date birthday) {
64         this.birthday = birthday;
65     }
66 
67     public String getMajor() {
68         return major;
69     }
70 
71     public void setMajor(String major) {
72         this.major = major;
73     }
74 
75     @OneToOne(cascade = CascadeType.ALL)
76     @JoinColumn(name = "pid",unique=true)//被控方的主键
77     public IdCard getCard() {
78         return card;
79     }
80 
81     public void setCard(IdCard card) {
82         this.card = card;
83     }
84 
85     
86     
87     
88     
89     
90     
91     
92 }
View Code

配置文件hibernate.cfg.xml:

 1 <?xml version='1.0' encoding='utf-8'?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3 "-//Hibernate/Hibernate Configuration DTD//EN"
 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5  
 6 <hibernate-configuration>
 7     <session-factory>
 8        <property name="connection.username">root</property>
 9        <property name="connection.password">mysql</property>
10        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
11        <property name="connection.url">jdbc:mysql:///hibernate?useUnicode=true&amp;characterEncoding=UTF-8</property>
12        
13        <!-- 配置数据的库的前缀 -->
14        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
15            
16            <!-- 
17                是否把Hibernate运行时的SQL语句输出到控制台,编码阶段便于测试
18             -->
19            <property name="show_sql">true</property>
20            <!-- 
21                输出到控制台的SQL语句是否进行排版,便于阅读。建议设置true
22             -->
23            <property name="format_sql">true</property>
24            <!-- 
25                可以到帮助由java代码生成数据库脚本,进而生辰具体的表结构。
26                create|update|create-drop|validate
27             -->
28            <property name="hbm2ddl.auto">create</property>
29            
30            <mapping class="com.relationannotation.entity.oto_pk.Students"/>
31            <mapping class="com.relationannotation.entity.oto_pk.IdCard"/>
32        <!--     <mapping class="com.entity.StudentA"/> -->
33     </session-factory>
34  
35 </hibernate-configuration>
View Code

测试用例:

 1 package com.entity.oto_pk;
 2 
 3 import java.util.Date;
 4 
 5 import org.hibernate.Session;
 6 import org.hibernate.SessionFactory;
 7 import org.hibernate.Transaction;
 8 import org.hibernate.cfg.Configuration;
 9 import org.hibernate.service.ServiceRegistry;
10 import org.hibernate.service.ServiceRegistryBuilder;
11 import org.hibernate.tool.hbm2ddl.SchemaExport;
12 import org.junit.Test;
13 
14 import com.relationannotation.entity.oto_pk.IdCard;
15 import com.relationannotation.entity.oto_pk.Students;
16 
17 public class TestStudent {
18 
19     /** 
20     *  生成表格
21     *  
22     * @param     
23     * @return void    
24     * @throws 
25     */
26     @Test
27     public void testeSchemaExport() {
28 
29         // 创建hibernate配置对象
30         Configuration config = new Configuration().configure();
31         // 创建服务注册对象
32         ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
33                 .buildServiceRegistry();
34         // 生成sessionFactory
35         SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
36         SchemaExport export = new SchemaExport(config);
37         export.create(true, true);
38     }
39     
40     /** 
41     * 增加一个学生
42     *  
43     * @param     
44     * @return void    
45     * @throws 
46     */
47     @Test
48     public void testAddStudent() {
49 
50         // 创建hibernate配置对象
51         Configuration config = new Configuration().configure();
52         // 创建服务注册对象
53         ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
54                 .buildServiceRegistry();
55         // 生成sessionFactory
56         SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
57         
58         Session session = sessionFactory.openSession();
59         
60         Transaction tx = session.beginTransaction();
61         
62         IdCard card = new IdCard("323232323232323232","张三");
63         Students students = new Students(card, "男", new Date(), "数学");
64 
65         session.save(card);//先保存身份证
66         session.save(students);//后保存学生
67         
68         tx.commit();
69         session.close();
70         
71         
72     }
73     
74 
75 }
View Code

 (二)一对一双向外键

主控方的配置通一对一单向外键关联

@OneToOne(mappedBy="card")//被控方 mappedBy表示把控制权交给主控方

双向关联,被空方必须设置mappedBy属性。因为双向关联只能交给一方去控制,不肯能在双方都设置外键保存关联关系,否则双方都无法保存。

例子:

被控方IdCard:

 1 package com.relationannotation.entity.oto_bfk;
 2 
 3 import javax.persistence.Column;
 4 import javax.persistence.Entity;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.Id;
 7 import javax.persistence.OneToOne;
 8 
 9 import org.hibernate.annotations.GenericGenerator;
10 
11 /** 
12  * 身份证类
13  *
14  * @author mrq
15  */
16 @Entity
17 public class IdCard {
18     
19     @Id
20     @GeneratedValue(generator="pid")
21     @GenericGenerator(name="pid", strategy = "assigned")
22     @Column(length=18)
23     private String pid;//身份证号码
24     
25     private String sname;//学生姓名
26 
27     @OneToOne(mappedBy="card")//这里把控制权交给主控方
28     private Students stu;
29     
30     public IdCard(){
31     }
32     
33     public IdCard(String pid, String sname) {
34         this.pid = pid;
35         this.sname = sname;
36     }
37 
38 
39     public String getPid() {
40         return pid;
41     }
42 
43     public void setPid(String pid) {
44         this.pid = pid;
45     }
46 
47     public String getSname() {
48         return sname;
49     }
50 
51     public void setSname(String sname) {
52         this.sname = sname;
53     }
54 
55     public Students getStu() {
56         return stu;
57     }
58 
59     public void setStu(Students stu) {
60         this.stu = stu;
61     }
62     
63     
64     
65     
66     
67 }
View Code

主控方Students:

 1 package com.relationannotation.entity.oto_bfk;
 2 
 3 import java.util.Date;
 4 
 5 import javax.persistence.CascadeType;
 6 import javax.persistence.Entity;
 7 import javax.persistence.GeneratedValue;
 8 import javax.persistence.GenerationType;
 9 import javax.persistence.Id;
10 import javax.persistence.JoinColumn;
11 import javax.persistence.OneToOne;
12 
13 /** 
14  * 学生实体类
15  * 
16  */
17 @Entity//(name = "t_students")
18 public class Students{
19     
20     
21     private IdCard card;
22     
23     private int sid;//学号
24     //@Id/* 联合主键,需要实现Serializable接口*/
25     //@Column(length = 8)/* 列注解,length属性值字段的长度*/
26     private String gender;//出生日期
27     private Date birthday;//出生日期
28     private String major;//专业
29     
30     public Students() {
31     }
32 
33     public Students(IdCard card, String gender, Date birthday, String major) {
34         this.card = card;
35         this.gender = gender;
36         this.birthday = birthday;
37         this.major = major;
38     }
39 
40     @Id
41     @GeneratedValue(strategy=GenerationType.AUTO)//默认是自增长的
42     public int getSid() {
43         return sid;
44     }
45 
46     public void setSid(int sid) {
47         this.sid = sid;
48     }
49 
50 
51     public String getGender() {
52         return gender;
53     }
54 
55     public void setGender(String gender) {
56         this.gender = gender;
57     }
58 
59     public Date getBirthday() {
60         return birthday;
61     }
62 
63     public void setBirthday(Date birthday) {
64         this.birthday = birthday;
65     }
66 
67     public String getMajor() {
68         return major;
69     }
70 
71     public void setMajor(String major) {
72         this.major = major;
73     }
74 
75     @OneToOne(cascade = CascadeType.ALL)
76     @JoinColumn(name = "pid",unique=true)//被控方的主键
77     public IdCard getCard() {
78         return card;
79     }
80 
81     public void setCard(IdCard card) {
82         this.card = card;
83     }
84 
85     
86     
87     
88     
89     
90     
91     
92 }
View Code

配置文件hibernate.cfg.xml:

 1 <?xml version='1.0' encoding='utf-8'?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3 "-//Hibernate/Hibernate Configuration DTD//EN"
 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5  
 6 <hibernate-configuration>
 7     <session-factory>
 8        <property name="connection.username">root</property>
 9        <property name="connection.password">mysql</property>
10        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
11        <property name="connection.url">jdbc:mysql:///hibernate?useUnicode=true&amp;characterEncoding=UTF-8</property>
12        
13        <!-- 配置数据的库的前缀 -->
14        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
15            
16            <!-- 
17                是否把Hibernate运行时的SQL语句输出到控制台,编码阶段便于测试
18             -->
19            <property name="show_sql">true</property>
20            <!-- 
21                输出到控制台的SQL语句是否进行排版,便于阅读。建议设置true
22             -->
23            <property name="format_sql">true</property>
24            <!-- 
25                可以到帮助由java代码生成数据库脚本,进而生辰具体的表结构。
26                create|update|create-drop|validate
27             -->
28            <property name="hbm2ddl.auto">create</property>
29            
30            <mapping class="com.relationannotation.entity.oto_bfk.Students"/>
31            <mapping class="com.relationannotation.entity.oto_bfk.IdCard"/>
32        <!--     <mapping class="com.entity.StudentA"/> -->
33     </session-factory>
34  
35 </hibernate-configuration>
View Code

测试用例和上述一样的结果。

(三)一对一双向外键联合主键

创建主键类

主键类必须实现Serializable接口,重写hashCode()和equals()方法。

主键类

@Embeddable

实体类

@EmbeddedId

(四)多对一单向外键

多方持有一方的引用,比如:多个学生对应一个班级(多对一)

@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)

@JoinColumn(name="cid",referencedColumnName=""CID)//name一方的外键,referencedColumnName表示映射到数据库的列名,

例子:

一方ClassRoom:

 1 package com.relationannotation.entity.mto_fk;
 2 
 3 import javax.persistence.Column;
 4 import javax.persistence.Entity;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.Id;
 7 
 8 import org.hibernate.annotations.GenericGenerator;
 9 
10 /*班级实体类*/
11 @Entity
12 public class ClassRoom {
13     
14     @Id
15     @GeneratedValue(generator="cid")
16     @GenericGenerator(name="cid",strategy="assigned")
17     @Column(length=4)
18     private String cid;//班级的编号
19     
20     private String cname;//班级的名字
21     
22     public ClassRoom(){
23     }
24     
25     
26     
27     public ClassRoom(String cid, String cname) {
28         this.cid = cid;
29         this.cname = cname;
30     }
31 
32 
33 
34     public String getCid() {
35         return cid;
36     }
37 
38     public void setCid(String cid) {
39         this.cid = cid;
40     }
41 
42     public String getCname() {
43         return cname;
44     }
45 
46     public void setCname(String cname) {
47         this.cname = cname;
48     }
49     
50     
51 }
View Code

多方StudentM:

  1 package com.relationannotation.entity.mto_fk;
  2 
  3 import java.util.Date;
  4 
  5 import javax.persistence.CascadeType;
  6 import javax.persistence.Entity;
  7 import javax.persistence.FetchType;
  8 import javax.persistence.GeneratedValue;
  9 import javax.persistence.GenerationType;
 10 import javax.persistence.Id;
 11 import javax.persistence.JoinColumn;
 12 import javax.persistence.ManyToOne;
 13 
 14 /*学生实体类*/
 15 @Entity
 16 public class StudentM {
 17     
 18     @Id
 19     @GeneratedValue(strategy=GenerationType.AUTO)//默认是自增长的
 20     private int sid;//学号
 21     
 22     private String sname;
 23     
 24     private String gender;//性别
 25     
 26     private Date birthday;//出生日期
 27     
 28     private String major;//专业
 29     
 30     @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
 31     @JoinColumn(name="cidcid",referencedColumnName="cid")//name是外键的列名,referencedColumnName引用外键的表的主键
 32     private ClassRoom classRoom;//
 33     
 34     public StudentM() {
 35     }
 36 
 37 
 38     public StudentM(String sname, String gender, Date birthday, String major) {
 39         this.sname = sname;
 40         this.gender = gender;
 41         this.birthday = birthday;
 42         this.major = major;
 43     }
 44 
 45 
 46     public int getSid() {
 47         return sid;
 48     }
 49 
 50     public void setSid(int sid) {
 51         this.sid = sid;
 52     }
 53 
 54     public String getGender() {
 55         return gender;
 56     }
 57 
 58     public void setGender(String gender) {
 59         this.gender = gender;
 60     }
 61 
 62     public Date getBirthday() {
 63         return birthday;
 64     }
 65 
 66     public void setBirthday(Date birthday) {
 67         this.birthday = birthday;
 68     }
 69 
 70     public String getMajor() {
 71         return major;
 72     }
 73 
 74     public void setMajor(String major) {
 75         this.major = major;
 76     }
 77 
 78     public ClassRoom getClassRoom() {
 79         return classRoom;
 80     }
 81 
 82     public void setClassRoom(ClassRoom classRoom) {
 83         this.classRoom = classRoom;
 84     }
 85 
 86 
 87     public String getSname() {
 88         return sname;
 89     }
 90 
 91 
 92     public void setSname(String sname) {
 93         this.sname = sname;
 94     }
 95 
 96     
 97     
 98     
 99     
100 }
View Code

配置文件相应的mapping修改一下

测试用例:

 1 package com.entity.mto_fk;
 2 
 3 
 4 import java.util.Date;
 5 
 6 import org.hibernate.Session;
 7 import org.hibernate.SessionFactory;
 8 import org.hibernate.Transaction;
 9 import org.hibernate.cfg.Configuration;
10 import org.hibernate.service.ServiceRegistry;
11 import org.hibernate.service.ServiceRegistryBuilder;
12 import org.hibernate.tool.hbm2ddl.SchemaExport;
13 import org.junit.Test;
14 
15 import com.relationannotation.entity.mto_fk.ClassRoom;
16 import com.relationannotation.entity.mto_fk.StudentM;
17 
18 
19 public class TestStudent {
20 
21     /** 
22     *  生成表格
23     *  
24     * @param     
25     * @return void    
26     * @throws 
27     */
28     @Test
29     public void testeSchemaExport() {
30 
31         // 创建hibernate配置对象
32         Configuration config = new Configuration().configure();
33         // 创建服务注册对象
34         ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
35                 .buildServiceRegistry();
36         // 生成sessionFactory
37         SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
38         SchemaExport export = new SchemaExport(config);
39         export.create(true, true);
40     }
41     
42     @Test
43     public void addStudents(){
44         Configuration config = new Configuration().configure();
45         // 创建服务注册对象
46         ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
47                 .buildServiceRegistry();
48         // 生成sessionFactory
49         SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
50         Session session = sessionFactory.openSession();
51         Transaction tx = session.beginTransaction();
52         
53         //先创建班级对象
54         ClassRoom c1 = new ClassRoom("C001","软件工程");
55         ClassRoom c2 = new ClassRoom("C002","网络工程");
56         
57         //创建是个学生
58         StudentM s1 = new StudentM("张三","男", new Date(), "计算机");
59         StudentM s2 = new StudentM("李四","男", new Date(), "计算机");
60         StudentM s3 = new StudentM("王五","女", new Date(), "计算机");
61         StudentM s4 = new StudentM("赵六","女", new Date(), "计算机");
62         
63         s1.setClassRoom(c1);
64         s2.setClassRoom(c1);
65         
66         s3.setClassRoom(c2);
67         s4.setClassRoom(c2);
68         
69         //先保存班级
70         session.save(c1);
71         session.save(c2);
72         session.save(s1);
73         session.save(s2);
74         session.save(s3);
75         session.save(s4);
76         
77         
78         tx.commit();
79         session.close();
80     }
81     
82     
83 }
View Code

(五)一对多单向外键

一方持有多方的集合,一个班级有多个学生(一对多)。

@OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)

@JoinColumn(name="cid")例子:

一方ClassRoom:

 1 package com.relationannotation.entity.otm_fk;
 2 
 3 import java.util.Set;
 4 
 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.JoinColumn;
12 import javax.persistence.OneToMany;
13 
14 import org.hibernate.annotations.GenericGenerator;
15 
16 /*班级实体类*/
17 @Entity
18 public class ClassRoom {
19     
20     @Id
21     @GeneratedValue(generator="cid")
22     @GenericGenerator(name="cid",strategy="assigned")
23     @Column(length=4)
24     private String cid;//班级的编号
25     
26     private String cname;//班级的名字
27     
28     @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
29     @JoinColumn(name="cid")
30     private Set<StudentM> stus;
31     
32     public ClassRoom(){
33     }
34     
35     
36     
37     public ClassRoom(String cid, String cname) {
38         this.cid = cid;
39         this.cname = cname;
40     }
41 
42 
43 
44     public String getCid() {
45         return cid;
46     }
47 
48     public void setCid(String cid) {
49         this.cid = cid;
50     }
51 
52     public String getCname() {
53         return cname;
54     }
55 
56     public void setCname(String cname) {
57         this.cname = cname;
58     }
59 
60     public Set<StudentM> getStus() {
61         return stus;
62     }
63 
64     public void setStus(Set<StudentM> stus) {
65         this.stus = stus;
66     }
67     
68     
69     
70 }
View Code

多方StudentM:

 1 package com.relationannotation.entity.otm_fk;
 2 
 3 import java.util.Date;
 4 
 5 import javax.persistence.Entity;
 6 import javax.persistence.GeneratedValue;
 7 import javax.persistence.GenerationType;
 8 import javax.persistence.Id;
 9 
10 /*学生实体类*/
11 @Entity
12 public class StudentM {
13     
14     @Id
15     @GeneratedValue(strategy=GenerationType.AUTO)//默认是自增长的
16     private int sid;//学号
17     
18     private String sname;
19     
20     private String gender;//性别
21     
22     private Date birthday;//出生日期
23     
24     private String major;//专业
25     
26     public StudentM() {
27     }
28 
29 
30     public StudentM(String sname, String gender, Date birthday, String major) {
31         this.sname = sname;
32         this.gender = gender;
33         this.birthday = birthday;
34         this.major = major;
35     }
36 
37 
38     public int getSid() {
39         return sid;
40     }
41 
42     public void setSid(int sid) {
43         this.sid = sid;
44     }
45 
46     public String getGender() {
47         return gender;
48     }
49 
50     public void setGender(String gender) {
51         this.gender = gender;
52     }
53 
54     public Date getBirthday() {
55         return birthday;
56     }
57 
58     public void setBirthday(Date birthday) {
59         this.birthday = birthday;
60     }
61 
62     public String getMajor() {
63         return major;
64     }
65 
66     public void setMajor(String major) {
67         this.major = major;
68     }
69 
70 
71     public String getSname() {
72         return sname;
73     }
74 
75 
76     public void setSname(String sname) {
77         this.sname = sname;
78     }
79 
80     
81     
82     
83     
84 }
View Code

 晕倒!@注解,要么都写在属性上,要么都写到getter方法上,否则会出错org.hibernate.MappingException: Could not determine type for

(六)多对多单向外键

学生和教师构成多对多的关联关系

其中一个多方持有另一个多方的集合对象(学生持有教师的集合)

创建中间表

@ManyToMany

@JoinTable(name="teachers_students",joinColumns={@JoinColumn(name="sid")},inverseJoinColumns={@JoinColumn(name="tid")})

例子:

学生类StudentM:

 1 package com.relationannotation.entity.mtm_fk;
 2 
 3 import java.util.Date;
 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.JoinColumn;
11 import javax.persistence.JoinTable;
12 import javax.persistence.ManyToMany;
13 
14 /*学生实体类*/
15 @Entity
16 public class StudentM {
17 
18     
19     private int sid;// 学号
20 
21     private String sname;
22 
23     private String gender;// 性别
24 
25     private Date birthday;// 出生日期
26 
27     private String major;// 专业
28 
29     
30     private Set<Teachers> teachers;//
31 
32     public StudentM() {
33     }
34 
35     public StudentM(String sname, String gender, Date birthday, String major) {
36         this.sname = sname;
37         this.gender = gender;
38         this.birthday = birthday;
39         this.major = major;
40     }
41     @Id
42     @GeneratedValue(strategy = GenerationType.AUTO) // 默认是自增长的
43     public int getSid() {
44         return sid;
45     }
46 
47     public void setSid(int sid) {
48         this.sid = sid;
49     }
50 
51     public String getGender() {
52         return gender;
53     }
54 
55     public void setGender(String gender) {
56         this.gender = gender;
57     }
58 
59     public Date getBirthday() {
60         return birthday;
61     }
62 
63     public void setBirthday(Date birthday) {
64         this.birthday = birthday;
65     }
66 
67     public String getMajor() {
68         return major;
69     }
70 
71     public void setMajor(String major) {
72         this.major = major;
73     }
74 
75     public String getSname() {
76         return sname;
77     }
78 
79     public void setSname(String sname) {
80         this.sname = sname;
81     }
82     
83     @ManyToMany
84     @JoinTable(name = "teachers_students", joinColumns = { @JoinColumn(name = "sid") }, inverseJoinColumns = {
85             @JoinColumn(name = "tid") })
86     public Set<Teachers> getTeachers() {
87         return teachers;
88     }
89 
90     public void setTeachers(Set<Teachers> teachers) {
91         this.teachers = teachers;
92     }
93 
94 }
View Code

教师类Teachers:

 1 package com.relationannotation.entity.mtm_fk;
 2 
 3 import javax.persistence.Column;
 4 import javax.persistence.Entity;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.Id;
 7 
 8 import org.hibernate.annotations.GenericGenerator;
 9 
10 /*教师实体类*/
11 @Entity
12 public class Teachers {
13     
14     
15     private String tid;//教师的编号
16     
17     private String tname;//教师的姓名
18 
19     public Teachers() {
20     }
21 
22     public Teachers(String tid, String tname) {
23         this.tid = tid;
24         this.tname = tname;
25     }
26     
27     @Id
28     @GeneratedValue(generator="tid")
29     @GenericGenerator(name="tid",strategy="assigned")
30     @Column(length=4)
31     public String getTid() {
32         return tid;
33     }
34 
35     public void setTid(String tid) {
36         this.tid = tid;
37     }
38 
39     public String getTname() {
40         return tname;
41     }
42 
43     public void setTname(String tname) {
44         this.tname = tname;
45     }
46     
47     
48     
49     
50     
51     
52 }
View Code

配置文件中mapping映射上述两个类

测试文件

 1 package com.entity.mtm_fk;
 2 
 3 
 4 import org.hibernate.SessionFactory;
 5 import org.hibernate.cfg.Configuration;
 6 import org.hibernate.service.ServiceRegistry;
 7 import org.hibernate.service.ServiceRegistryBuilder;
 8 import org.hibernate.tool.hbm2ddl.SchemaExport;
 9 import org.junit.Test;
10 
11 
12 public class TestStudent {
13 
14     /** 
15     *  生成表格
16     *  
17     * @param     
18     * @return void    
19     * @throws 
20     */
21     @Test
22     public void testeSchemaExport() {
23 
24         // 创建hibernate配置对象
25         Configuration config = new Configuration().configure();
26         // 创建服务注册对象
27         ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
28                 .buildServiceRegistry();
29         // 生成sessionFactory
30         SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
31         SchemaExport export = new SchemaExport(config);
32         export.create(true, true);
33     }
34     
35     @Test
36     public void addStudents(){
37     }
38     
39     
40 }
View Code

(七)多对多单向外键

就是Teachers类中持有学生的引用,加上@ManyToMany(mappedBy="teachers")

 1 package com.relationannotation.entity.mtm_fk;
 2 
 3 import java.util.Set;
 4 
 5 import javax.persistence.Column;
 6 import javax.persistence.Entity;
 7 import javax.persistence.GeneratedValue;
 8 import javax.persistence.Id;
 9 import javax.persistence.ManyToMany;
10 
11 import org.hibernate.annotations.GenericGenerator;
12 
13 /*教师实体类*/
14 @Entity
15 public class Teachers {
16     
17     
18     private String tid;//教师的编号
19     
20     private String tname;//教师的姓名
21     
22     private Set<StudentM> studentM;//
23 
24     public Teachers() {
25     }
26 
27     public Teachers(String tid, String tname) {
28         this.tid = tid;
29         this.tname = tname;
30     }
31     
32     @Id
33     @GeneratedValue(generator="tid")
34     @GenericGenerator(name="tid",strategy="assigned")
35     @Column(length=4)
36     public String getTid() {
37         return tid;
38     }
39 
40     public void setTid(String tid) {
41         this.tid = tid;
42     }
43 
44     public String getTname() {
45         return tname;
46     }
47 
48     public void setTname(String tname) {
49         this.tname = tname;
50     }
51     @ManyToMany(mappedBy="teachers")
52     public Set<StudentM> getStudentM() {
53         return studentM;
54     }
55 
56     public void setStudentM(Set<StudentM> studentM) {
57         this.studentM = studentM;
58     }
59 
60     
61     
62     
63 }
View Code

 

posted @ 2018-04-17 21:38  花雪依蒿  阅读(200)  评论(0编辑  收藏  举报