在hibernate中,通常配置对象关系映射关系有两种,一种是基于xml的方式,另一种是基于annotation的注解方式,熟话说,萝卜青菜,可有所爱,每个人都有自己喜欢的配置方式,我在试了这两种方式以后,发现使用annotation的方式可以更简介,所以这里就简单记录下通过annotation来配置各种映射关系,在hibernate4以后已经将annotation的jar包集成进来了,如果使用hibernate3的版本就需要引入annotation的jar包。
配置持久化类常用的注解:
注:GeneratedValue指定了标识符的生成策略。jpa提供了4种标准用法。
01.AUTO:根据不同的数据库选择不同的策略
02.TABLE:使用表保存id值
03.INDENITY:使用数据库自动生成主键
04.SEQUENCE:使用序列创建主键(如Oracle)
配置关联关系常用的注解:
话不多说了,待大家来看看到底怎么用的才最重要
1.注解配置对象关联关系之 一对一(学生对学生证)
Student.java
package cn.zhang.entity; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; //学生实体类 @Entity @Table(name="Student2161") public class Student { @Id //主键 @GeneratedValue //主键生成策略 private Integer sid; private String name; //配置之间的一对一的关系 //cascade={CascadeType.ALL}设置了级联 //mappedBy="stu"设置维护关系的控制权交给StuCard类这一方,相当于Student.hbm.xml中配置的inverse="true" @OneToOne(mappedBy="stu",cascade={CascadeType.ALL}) private StuCard sCard; public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public StuCard getsCard() { return sCard; } public void setsCard(StuCard sCard) { this.sCard = sCard; } }
StuCard.java
package cn.zhang.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; //学生证实体类 @Entity @Table(name="StuCard2161") public class StuCard { @Id //主键 @Column(length=18) //可以指定最大长度 private String cid;//身份证 @OneToOne //配置一对一关联 @JoinColumn(name="sid")//指定了维护关系的外键字段是Student的sid private Student stu; public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public Student getStu() { return stu; } public void setStu(Student stu) { this.stu = stu; } }
最后只需要在hibernate.cfg.xml文件里面将该实体类加进去即可:
<!-- 注解配置 --> <mapping class="cn.zhang.entity.Student"/> <mapping class="cn.zhang.entity.StuCard"/>
测试:
package cn.zhang.test; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.After; import org.junit.Before; import org.junit.Test; import cn.zhang.entity.StuCard; import cn.zhang.entity.Student; import cn.zhang.util.HibernateUtil; public class MyTest { Session session; Transaction tx; //单元测试前走 @Before public void Before(){ session= HibernateUtil.currentSession(); tx= session.beginTransaction(); } //单元测试后走 @After public void After(){ tx.commit(); HibernateUtil.closeSession(); } @Test public void TestOne(){ Student student=new Student(); student.setName("good"); StuCard sCard=new StuCard(); sCard.setCid("11111111111111"); sCard.setStu(student); student.setsCard(sCard); session.save(student); } }
2.注解配置对象关联关系之 多对一(部门和员工)
Dept.java
package cn.zhang.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; //部门实体类 @Entity @Table(name="Dept2161") public class Dept { @Id //主键生成策略 @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_gen") @SequenceGenerator(name="seq_gen",sequenceName="SEQ_HouseNum",allocationSize=1,initialValue=1) private Integer deptid; private String deptname; @OneToMany(mappedBy="dept",cascade={CascadeType.ALL}) @LazyCollection(LazyCollectionOption.FALSE) //设置立即加载,默认为延迟加载 private Set<Emp> emps = new HashSet<Emp>();// 员工集合 public Set<Emp> getEmps() { return emps; } public void setEmps(Set<Emp> emps) { this.emps = emps; } public Integer getDeptid() { return deptid; } public void setDeptid(Integer deptid) { this.deptid = deptid; } public String getDeptname() { return deptname; } public void setDeptname(String deptname) { this.deptname = deptname; } }
Emp.java
package cn.zhang.entity; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; //员工实体类 @Entity @Table(name="Emp2161") public class Emp { @Id //主键生成策略 @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_gen") @SequenceGenerator(name="seq_gen",sequenceName="SEQ_HouseNum",allocationSize=1,initialValue=1) private Integer empno; private String empname; @ManyToOne(fetch=FetchType.LAZY) //fentch: 设置了延迟加载 ,默认为立即加载,不设置则会和dept表外连接查询 @JoinColumn(name="deptid") private Dept dept;//所属部门 public Dept getDept() { return dept; } public void setDept(Dept dept) { this.dept = dept; } public Integer getEmpno() { return empno; } public void setEmpno(Integer empno) { this.empno = empno; } public String getEmpname() { return empname; } public void setEmpname(String empname) { this.empname = empname; } }
最后只需要在hibernate.cfg.xml文件里面将该实体类加进去即可:
<!-- 注解配置 --> <mapping class="cn.zhang.entity.Dept"/> <mapping class="cn.zhang.entity.Emp"/>
测试:
package cn.zhang.test; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.After; import org.junit.Before; import org.junit.Test; import cn.zhang.entity.Dept; import cn.zhang.entity.Emp; import cn.zhang.util.HibernateUtil; public class MyTest { Session session; Transaction tx; //单元测试前走 @Before public void Before(){ session= HibernateUtil.currentSession(); tx= session.beginTransaction(); } //单元测试后走 @After public void After(){ tx.commit(); HibernateUtil.closeSession(); } @Test public void TestOne(){ Emp emp=new Emp(); emp.setEmpname("好人一个"); Dept dept=new Dept(); dept.setDeptname("人才部"); dept.getEmps().add(emp); emp.setDept(dept); session.save(dept); } @Test public void TestTwo(){ Emp emp = (Emp)session.load(Emp.class, 2); System.out.println(emp.getEmpname()); System.out.println("------------"); Dept dept = (Dept)session.load(Dept.class, 1); System.out.println(dept.getDeptname()); } }
3.注解配置对象关联关系之 多对多(项目和员工)
Emp.java
package cn.zhang.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name = "Emp2161") public class Emp { @Id @GeneratedValue private Integer eid; private String name; @ManyToMany(cascade=CascadeType.ALL)//设置多对多和级联 //利用第三张表实现多对多的关联 @JoinTable( name = "EmpPro2161", //指定第三张表名 joinColumns = @JoinColumn(name = "eid"), //Emp表在第三张表中的外键 inverseJoinColumns = @JoinColumn(name = "pid")//Project表在第三张表中的外键 ) private Set<Project> projects = new HashSet<Project>(); public Integer getEid() { return eid; } public void setEid(Integer eid) { this.eid = eid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Project> getProjects() { return projects; } public void setProjects(Set<Project> projects) { this.projects = projects; } }
Project.java
package cn.zhang.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="Project2161") public class Project { @Id @GeneratedValue private Integer pid; private String name; @ManyToMany(mappedBy="projects")//设置多对多并指定维护关系的控制权交给Emp类这一方 private Set<Emp> emps=new HashSet<Emp>(); public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Emp> getEmps() { return emps; } public void setEmps(Set<Emp> emps) { this.emps = emps; } }
最后只需要在hibernate.cfg.xml文件里面将该实体类加进去即可:
<!-- 注解配置 --> <mapping class="cn.zhang.entity.Project"/> <mapping class="cn.zhang.entity.Emp"/>
测试:
package cn.zhang.test; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.After; import org.junit.Before; import org.junit.Test; import cn.zhang.entity.Emp; import cn.zhang.entity.Project; import cn.zhang.util.HibernateUtil; public class MyTest { Session session; Transaction tx; //单元测试前走 @Before public void Before(){ session= HibernateUtil.currentSession(); tx= session.beginTransaction(); } //单元测试后走 @After public void After(){ tx.commit(); HibernateUtil.closeSession(); } @Test public void TestOne(){ Emp emp=new Emp(); emp.setName("好人一个"); Project project=new Project(); project.setName("好项目"); project.getEmps().add(emp); emp.getProjects().add(project); session.save(emp); } }
注意:在判断到底是谁维护关联关系时,可以通过查看外键,哪个实体类定义了外键,哪个类就负责维护关联关系。
来源:https://www.cnblogs.com/zhangzongle/p/5802938.html