映射关系级别注解
Posted 黄小鱼ZZZ
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了映射关系级别注解相关的知识,希望对你有一定的参考价值。
映射关系级别注解
一对一单向外键
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="pid",unique=true)
注意:保存时应该先保存外键对象,在保存主表对象
@JoinColumn(name="pid",unique=true)
注意:保存时应该先保存外键对象,在保存主表对象
实例:将环境配置好,所需要的包前边已经提到过,
学生实体类:
package com.oto; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity;//JPA注解 import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; /* * 学生实体类 */ @Entity public class Students { private int sid; //学号 private IdCard card;//身份证 private String gender;//性别 private Date birthday;//出生日期 private String major;//专业 public Students(){ } public Students(IdCard card, String gender, Date date, String major) { // super(); this.card = card; this.gender = gender; this.birthday = date; this.major = major; } @Id @GeneratedValue public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="pid",unique=true) public IdCard getCard() { return card; } public void setCard(IdCard card) { this.card = card; } }
身份证实体类:
package com.oto; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; @Entity public class IdCard { @Id @GeneratedValue(generator="pid") @GenericGenerator(name="pid",strategy="assigned") @Column(length=18) private String pid; //身份证号 private String sname;//姓名 public IdCard(){ } public IdCard(String pid, String sname) { this.pid = pid; this.sname = sname; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } }测试类:
package com.oto; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Test; public class TestStudents { @Test public void testShemaExport(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); SchemaExport export = new SchemaExport(config); export.create(true,true); } //往数据库中添加学生数据 @Test public void addStudents(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); //创建会话 Session session = sessionFactory.getCurrentSession(); //创建事务 Transaction tx = session.beginTransaction(); IdCard card = new IdCard("123456789012345678","猪八戒"); Students stu = new Students(card,"男",new Date(),"计算机"); session.save(card); session.save(stu); tx.commit(); } }
hibernate.cfg.xml中的配置:下面的使用的是同一个配置,下边的代码中不再列举,
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.mysqlDialect</property> <!-- <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql:///hibernate_struts_stumanager</property> --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mypage</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.show_sql">false</property> <property name="hibernate.hbm2ddl.auto">create</property> <property name="current_session_context_class">thread</property> <!-- <mapping class="com.oto.Students"/> <mapping class="com.oto.IdCard"/> --><!-- 一对一单向外键关联 --> <!-- <mapping class="com.oto_11.Students"/> <mapping class="com.oto_11.IdCard"/> --> <!--一对一双向外键关联 --> <!-- <mapping class="com.mto.Students"/> <mapping class="com.mto.ClassRoom"/> --><!-- 多对一单向外键关联--> <!-- <mapping class="com.otm.Students"/> <mapping class="com.otm.ClassRoom"/> --><!-- 一对多单向外键关联 --> <!-- <mapping class="com.otm_11.Students"/> <mapping class="com.otm_11.ClassRoom"/> --><!-- 一对多双向外键 --> <!-- <mapping class="com.mtm.Students"/> <mapping class="com.mtm.Teachers"/> --> <!-- 多对多单向外键关联 --> <mapping class="com.mtm_11.Students"/> <mapping class="com.mtm_11.Teachers"/> <!-- 多对多双向外键关联 --> </session-factory> </hibernate-configuration>
一对一双向外键关联
主控方的配置同一对一单向外键关联
@OneToOne(mappedBy="card")//被控方
双向关联,必须设置mappedBy属性。因为双向关联只能交给一方去控制,不可能在双方
都设置外键保存关联关系,否则双方都无法保存
@OneToOne(mappedBy="card")//被控方
双向关联,必须设置mappedBy属性。因为双向关联只能交给一方去控制,不可能在双方
都设置外键保存关联关系,否则双方都无法保存
实例:
学生实体类
package com.oto_11; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity;//JPA注解 import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; /* * 学生实体类 */ @Entity public class Students { private int sid; //学号 private IdCard card;//身份证 private String gender;//性别 private Date birthday;//出生日期 private String major;//专业 public Students(){ } public Students(IdCard card, String gender, Date date, String major) { // super(); this.card = card; this.gender = gender; this.birthday = date; this.major = major; } @Id @GeneratedValue public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="pid",unique=true) public IdCard getCard() { return card; } public void setCard(IdCard card) { this.card = card; } }
package com.oto_11; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import org.hibernate.annotations.GenericGenerator; @Entity public class IdCard { @Id @GeneratedValue(generator="pid") @GenericGenerator(name="pid",strategy="assigned") @Column(length=18) private String pid; //身份证号 private String sname;//姓名 @OneToOne(mappedBy="card") private Students stu; public IdCard(){ } public IdCard(String pid, String sname) { this.pid = pid; this.sname = sname; } public Students getStu() { return stu; } public void setStu(Students stu) { this.stu = stu; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } }测试类:
package com.oto_11; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Test; public class TestStudents { @Test public void testShemaExport(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); SchemaExport export = new SchemaExport(config); export.create(true,true); } @Test public void addStudents(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); //创建会话 Session session = sessionFactory.getCurrentSession(); //创建事务 Transaction tx = session.beginTransaction(); IdCard card = new IdCard("123456789012345678","猪八戒"); Students stu = new Students(card,"男",new Date(),"计算机"); session.save(card); session.save(stu); tx.commit(); } }
一对一单向外键联合主键
一对一双向外键联合主键
创建主键类
主键类必须实现serializable接口,重写hashCode()和equals()方法。
主键类
@Embeddable
实体类
@EmbeddedId
主键类必须实现serializable接口,重写hashCode()和equals()方法。
主键类
@Embeddable
实体类
@EmbeddedId
多对一单向外键关联
多方持有一方的引用
@ManyToOne(cascade={CascadeType.ALL},
fetch=FetchType.EAGER)
@JoinColumn(name="cid",referencedColumnName="CID")
@ManyToOne(cascade={CascadeType.ALL},
fetch=FetchType.EAGER)
@JoinColumn(name="cid",referencedColumnName="CID")
学生实体类:
package com.mto; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity;//JPA注解 import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; /* * 学生实体类 */ @Entity public class Students { private int sid; //学号 private String gender;//性别 private Date birthday;//出生日期 private String major;//专业 private ClassRoom classroom; private String sname; public Students(){ } public Students(String sname, String gender, Date date, String major) { // super(); this.sname = sname; this.gender = gender; this.birthday = date; this.major = major; } @Id @GeneratedValue public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER) @JoinColumn(name="cid",referencedColumnName="CID") public ClassRoom getClassroom() { return classroom; } public void setClassroom(ClassRoom classroom) { this.classroom = classroom; } }
班级实体类:
package com.mto; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; //班级实体类 @Entity public class ClassRoom { @Id @GeneratedValue(generator="cid") @GenericGenerator(name="cid",strategy="assigned") @Column(length=4) private String cid;//班级的编号 private String cname;//班级的名字 public ClassRoom(){ } public ClassRoom(String cid, String cname) { this.cid = cid; this.cname = cname; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } }测试类:
package com.mto; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Test; public class TestStudents { @Test public void testShemaExport(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); SchemaExport export = new SchemaExport(config); export.create(true,true); } //往数据库中添加学生数据 @Test public void addStudents(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); //创建会话 Session session = sessionFactory.getCurrentSession(); //创建事务 Transaction tx = session.beginTransaction(); //创建班级对象 ClassRoom c1 = new ClassRoom("0001","软件工程"); ClassRoom c2 = new ClassRoom("0002","通信工程"); //创建学生对象 Students s1 = new Students("小王","男",new Date(),"计算机"); Students s2 = new Students("小黄","男",new Date(),"计算机"); Students s3 = new Students("小花","女",new Date(),"计算机"); Students s4 = new Students("小红","女",new Date(),"计算机"); s1.setClassroom(c1); s2.setClassroom(c1); s3.setClassroom(c2); s4.setClassroom(c2); session.save(c1); session.save(c2); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); } }
一对多单向外键关联
一方持有多方的集合
@OneToMany(cascade={cascadeType.ALL},fetch=FetchType.LAZY)
@JoinColumn(name="cid")
@OneToMany(cascade={cascadeType.ALL},fetch=FetchType.LAZY)
@JoinColumn(name="cid")
实例:
学生实体类:
package com.otm; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity;//JPA注解 import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; /* * 学生实体类 */ @Entity public class Students { private int sid; //学号 private String gender;//性别 private Date birthday;//出生日期 private String major;//专业 private String sname; public Students(){ } public Students(String sname, String gender, Date date, String major) { // super(); this.sname = sname; this.gender = gender; this.birthday = date; this.major = major; } @Id @GeneratedValue public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }班级实体类:
package com.otm; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import org.hibernate.annotations.GenericGenerator; //班级实体类 @Entity public class ClassRoom { @Id @GeneratedValue(generator="cid") @GenericGenerator(name="cid",strategy="assigned") @Column(length=4) private String cid;//班级的编号 private String cname;//班级的名字 @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY) @JoinColumn(name="cid") private Set<Students> stus;//一方持有多方的集合 public ClassRoom(){ } public ClassRoom(String cid, String cname) { this.cid = cid; this.cname = cname; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public Set<Students> getStus() { return stus; } public void setStus(Set<Students> stus) { this.stus = stus; } }
测试类:
package com.otm; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Test; public class TestStudents { @Test public void testShemaExport(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); SchemaExport export = new SchemaExport(config); export.create(true,true); } @Test public void addStudents(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); //创建会话 Session session = sessionFactory.getCurrentSession(); //创建事务 Transaction tx = session.beginTransaction(); //创建班级对象 ClassRoom c1 = new ClassRoom("0001","软件工程"); ClassRoom c2 = new ClassRoom("0002","通信工程"); //创建学生对象 Students s1 = new Students("小王","男",new Date(),"计算机"); Students s2 = new Students("小黄","男",new Date(),"计算机"); Students s3 = new Students("小花","女",new Date(),"计算机"); Students s4 = new Students("小红","女",new Date(),"计算机"); Set<Students> set1 = new HashSet<Students>(); set1.add(s1); set1.add(s2); Set<Students> set2 = new HashSet<Students>(); set2.add(s3); set2.add(s4); session.save(s1); session.save(s2); session.save(s3); session.save(s4); session.save(c1); session.save(c2); tx.commit(); } }
一对多双向外键关联
多方:多方持有一方的引用
@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
@JoinColumn(name="cid")
一方:一方持有多方的集合
@OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
@JoinColumn(name="cid")
@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
@JoinColumn(name="cid")
一方:一方持有多方的集合
@OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
@JoinColumn(name="cid")
实例:
package com.otm_11; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity;//JPA注解 import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; /* * 学生实体类 */ @Entity public class Students { private int sid; //学号 private String gender;//性别 private Date birthday;//出生日期 private String major;//专业 private String sname;//姓名 private ClassRoom classroom; public Students(){ } public Students(String sname, String gender, Date date, String major) { // super(); this.sname = sname; this.gender = gender; this.birthday = date; this.major = major; } @Id @GeneratedValue public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER) @JoinColumn(name="cid") public ClassRoom getClassroom() { return classroom; } public void setClassroom(ClassRoom classroom) { this.classroom = classroom; } }
班级实体类:
package com.otm_11; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import org.hibernate.annotations.GenericGenerator; //班级实体类 @Entity public class ClassRoom { @Id @GeneratedValue(generator="cid") @GenericGenerator(name="cid",strategy="assigned") @Column(length=4) private String cid;//班级的编号 private String cname;//班级的名字 @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY) @JoinColumn(name="cid") private Set<Students> stus;//一方持有多方的集合 public ClassRoom(){ } public ClassRoom(String cid, String cname) { this.cid = cid; this.cname = cname; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public Set<Students> getStus() { return stus; } public void setStus(Set<Students> stus) { this.stus = stus; } }测试类:
package com.mto_11; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Test; import com.otm_11.ClassRoom; import com.otm_11.Students; public class TestStudents { @Test public void testShemaExport(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); SchemaExport export = new SchemaExport(config); export.create(true,true); } @Test public void addStudents(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); //创建会话 Session session = sessionFactory.getCurrentSession(); //创建事务 Transaction tx = session.beginTransaction(); //创建班级对象 ClassRoom c1 = new ClassRoom("0001","软件工程"); ClassRoom c2 = new ClassRoom("0002","通信工程"); //创建学生对象 Students s1 = new Students("小王","男",new Date(),"计算机"); Students s2 = new Students("小黄","男",new Date(),"计算机"); Students s3 = new Students("小花","女",new Date(),"计算机"); Students s4 = new Students("小红","女",new Date(),"计算机"); s1.setClassroom(c1); s2.setClassroom(c1); s3.setClassroom(c2); s4.setClassroom(c2); session.save(c1); session.save(c2); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); } }
多对多单向外键关联
其中一个多方持有另一个多方的集合对象
创建中间表
@MantToMany
@JoinTable(
name="teachers_students",
joinColumns={@JoinColumn(name="sid")},inverseJoinColumns={@JoinColumn(name="tid")}
)
创建中间表
@MantToMany
@JoinTable(
name="teachers_students",
joinColumns={@JoinColumn(name="sid")},inverseJoinColumns={@JoinColumn(name="tid")}
)
实例:
学生实体类:
package com.mtm; import java.util.Date; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity;//JPA注解 import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; /* * 学生实体类 */ @Entity public class Students { private int sid; //学号 private String gender;//性别 private Date birthday;//出生日期 private String major;//专业 private String sname;//学生姓名 private Set<Teachers> teachers; //学生持有教师的集合 public Students(){ } public Students(String sname, String gender, Date date, String major) { // super(); this.sname = sname; this.gender = gender; this.birthday = date; this.major = major; } @Id @GeneratedValue public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } @ManyToMany @JoinTable( name="teachers_students", joinColumns={@JoinColumn(name="sid")}, inverseJoinColumns={@JoinColumn(name="tid")} ) public Set<Teachers> getTeachers() { return teachers; } public void setTeachers(Set<Teachers> teachers) { this.teachers = teachers; } }
老师实体类:
package com.mtm; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; //教师实体类 @Entity public class Teachers { @Id @GeneratedValue(generator="tid") @GenericGenerator(name="tid",strategy="assigned") @Column(length=4) private String tid;//教师id private String tname;//教师名字 public Teachers(){ } public Teachers(String tid, String tname) { // super(); this.tid = tid; this.tname = tname; } public String getTid() { return tid; } public void setTid(String tid) { this.tid = tid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } }
测试类:
package com.mtm; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Test; public class TestStudents { @Test public void testShemaExport(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); SchemaExport export = new SchemaExport(config); export.create(true,true); } @Test public void addStudents(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); //创建教师对象 Teachers t1 = new Teachers("0001","张老师"); Teachers t2 = new Teachers("0002","黄老师"); Teachers t3 = new Teachers("0003","李老师"); Teachers t4 = new Teachers("0004","王老师"); Students s1 = new Students("张三","男",new Date(),"计算机"); Students s2 = new Students("李四","男",new Date(),"计算机"); Students s3 = new Students("王五","女",new Date(),"通信"); Students s4 = new Students("赵六","女",new Date(),"通信"); Set<Teachers> set1 = new HashSet<Teachers>(); set1.add(t1); set1.add(t2); Set<Teachers> set2 = new HashSet<Teachers>(); set2.add(t3); set2.add(t4); Set<Teachers> set3 = new HashSet<Teachers>(); set3.add(t1); set3.add(t3); set3.add(t4); Set<Teachers> set4 = new HashSet<Teachers>(); set4.add(t2); set4.add(t3); set4.add(t4); s1.setTeachers(set1); s2.setTeachers(set2); s3.setTeachers(set3); s4.setTeachers(set4); session.save(t1); session.save(t2); session.save(t3); session.save(t4); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); } }
多对多双向外键关联
双方持有对方的集合对象,其中一方设置
//教师类
@ManyToMany(mappedBy="teachers")
另一方
//学生类
@ManyToMany
@JoinTable(
name="teachers_students",
joinColumns={@JoinColumn(name="sid")},
inverseJoinColumns={@JoinColumn(name="tid")}
)
//教师类
@ManyToMany(mappedBy="teachers")
另一方
//学生类
@ManyToMany
@JoinTable(
name="teachers_students",
joinColumns={@JoinColumn(name="sid")},
inverseJoinColumns={@JoinColumn(name="tid")}
)
实例:
学生实体类:
package com.mtm_11; import java.util.Date; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity;//JPA注解 import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; /* * 学生实体类 */ @Entity public class Students { private int sid; //学号 private String gender;//性别 private Date birthday;//出生日期 private String major;//专业 private String sname;//学生姓名 private Set<Teachers> teachers; //学生持有教师的集合 public Students(){ } public Students(String sname, String gender, Date date, String major) { // super(); this.sname = sname; this.gender = gender; this.birthday = date; this.major = major; } @Id @GeneratedValue public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } @ManyToMany @JoinTable( name="teachers_students", joinColumns={@JoinColumn(name="sid")}, inverseJoinColumns={@JoinColumn(name="tid")} ) public Set<Teachers> getTeachers() { return teachers; } public void setTeachers(Set<Teachers> teachers) { this.teachers = teachers; } }老师实体类:
package com.mtm_11; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import org.hibernate.annotations.GenericGenerator; //教师实体类 @Entity public class Teachers { @Id @GeneratedValue(generator="tid") @GenericGenerator(name="tid",strategy="assigned") @Column(length=4) private String tid;//教师id private String tname;//教师名字 @ManyToMany(mappedBy="teachers") private Set<Students> stus;//教师持有学生的集合 public Teachers(){ } public Teachers(String tid, String tname) { // super(); this.tid = tid; this.tname = tname; } public String getTid() { return tid; } public void setTid(String tid) { this.tid = tid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } }测试类:
package com.mtm_11; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Test; public class TestStudents { @Test public void testShemaExport(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); SchemaExport export = new SchemaExport(config); export.create(true,true); } @Test public void addStudents(){ //创建hibernate配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //生成SessionFactory SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); //创建教师对象 Teachers t1 = new Teachers("0001","张老师"); Teachers t2 = new Teachers("0002","黄老师"); Teachers t3 = new Teachers("0003","李老师"); Teachers t4 = new Teachers("0004","王老师"); Students s1 = new Students("张三","男",new Date(),"计算机"); Students s2 = new Students("李四","男",new Date(),"计算机"); Students s3 = new Students("王五","女",new Date(),"通信"); Students s4 = new Students("赵六","女",new Date(),"通信"); Set<Teachers> set1 = new HashSet<Teachers>(); set1.add(t1); set1.add(t2); Set<Teachers> set2 = new HashSet<Teachers>(); set2.add(t3); set2.add(t4); Set<Teachers> set3 = new HashSet<Teachers>(); set3.add(t1); set3.add(t3); set3.add(t4); Set<Teachers> set4 = new HashSet<Teachers>(); set4.add(t2); set4.add(t3); set4.add(t4); s1.setTeachers(set1); s2.setTeachers(set2); s3.setTeachers(set3); s4.setTeachers(set4); session.save(t1); session.save(t2); session.save(t3); session.save(t4); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); } }这里列举了几个简单的例子,大神直接略过啊~~~~
以上是关于映射关系级别注解的主要内容,如果未能解决你的问题,请参考以下文章
Hibernate基于注解的双向one-to-many映射关系的实现