电子书下载地址:
[url]http://xiaochenggushi.iteye.com/admin/pdf_jobs/12250[/url]
hibernate注解总结一
hibernate注解总结二
hibernate注解 一对一主键关联
hibernate 注解一对一关系 关联表关联
hibernate 注解一对一关系 外键关联
hibernate注解 一对多 外键关联
hibernate 注解一对多 关联表映射
hibernate注解多对多映射
本文内容参考http://gyfbao.blog.sohu.com//entry/8176950/
[url]http://xiaochenggushi.iteye.com/admin/pdf_jobs/12250[/url]
hibernate注解总结一
1. Hibernate Annotation关系映射有下面几种类型:
1)一对一外键关联映射(单向)
2)一对一外键关联映射(双向)
3)一对一关联表映射(单向)
4)一对一关联表映射(双向)
5)一对一主键关联映射
使用注解@PrimaryKeyJoinColumn
6)多对一关联映射
7)一对多外键关联映射(单向)
8)一对多外键关联映射(双向)
9)一对多关联表映射(单向)
10)一对多关联表映射(双向)
11)多对多关联映射(单向)
12)多对多关联映射(双向)
2.介绍各种映射用法
1)一对一外键关联映射(单向)
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="userid",unique=true)
//一对一外键关联,使用@OneToOne,并设置了级联操作
//@JoinColum设置了外键的名称为userid(数据库字段名),如果不设置,则默认为另一类的属性名+ _id
//外键的值是唯一的(unique),不可重复,与另一类的主键一致
2)一对一外键关联映射(双向)
Class1里与上面一样,
Class2:
@OneToOne(mappedBy="class2",cascade=CascadeType.ALL)
//一对一双向关联关系,使用@OneToOne
//注意:需要加上mappedBy="class2",如果不加上的话,
//Class2也会生成一个外键(class1_id)
//mappedby="class2"需要指向与他关联对象的一个属性
//说明双向关联关系中,有且仅有一端是作为主体(owner)端存在的
//主体端负责维护联接列
//对于不需要维护这种关系的从表则通过mappedBy属性进行声明
//mappedBy的值指向主体的关联属性
//规律:只有是双向关联关系,都加上mappedby
//cascade=CascadeType.ALL级联
3)一对一关联表映射(单向)
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name ="basicdetail",
joinColumns =@JoinColumn(name="class1id"),
inverseJoinColumns =@JoinColumn(name="class2id")
//通过basicdetail这个表关联class1和class2。该关联表拥有名为class2id的外键列,该外键指向class2表,该信息定义为inverseJoinColoumns的属性值,而class1id外键列指向class1表,该信息定义为joinColumns的属性值。
4)一对一关联表映射(双向)
Class1里与上面一样,
Class2:
@OneToOne(mappedBy="class2",cascade=CascadeType.ALL)
5)一对一主键关联映射(单向)
在从表类的一端如下设置
@Id
@GeneratedValue(generator="pkGenerator")
@GenericGenerator(name ="pkGenerator",
strategy="foreign" ,
parameters={@Parameter(name="property",value="class1")})
//从表类的ID是根据主表类的ID来赋值的,这里需要设置ID生成器的策略为foreign,参数中指定从表类的ID是使用主表类对象中的ID
@OneToOne(cascade=CascadeType.ALL)
@PrimaryKeyJoinColumn
通过@PrimaryKeyJoinColumn批注定义了一对一关联
6)一对一主键关联映射(双向)
主表类的一端如下:
@OneToOne(cascade=CascadeType.ALL, mappedBy="class1")
mappedBy="class1"这个是必须的.否则会在主表类生成从表类的一个外键。
hibernate注解总结二
7)一对多关联映射外键关联(单向)
@OneToMany
@JoinColumn(name="orgid")
/**
* 一对多注解@OneToMany(单向)
* 如果只写@OneToMany的话,hibernate会建一张中间表来
* 维护他们之间的关系,
* 加上@JoinColumn(name="orgid"),则不会建中间表,他会在
* 多的一端加上外键orgid,来维护他们之间的关系
*/
8)一对多关联映射外键关联(双向)
一端:
@OneToMany
@JoinColumn(name="orgid")
多端:
@ManyToOne
@JoinColumn(name="orgid")
/**
* 一对多双向
* 需要指定外键与一的一端给的外键名称一致,@JoinColumn(name="orgid")
* 也可以不指定,如果在多的一端不指定,则一的一端也不能指定
* 否则为生成两个外键
* 一的一端可以有(mappedBy="class1"),但不可与@JoinColumn同时使用。使用mappedBy会在多的一端自动生成外键
*/
9)一对多关联表映射(单向)
@ManyToOne
@JoinTable(name ="people_study",
joinColumns =@JoinColumn(name="sid"),
inverseJoinColumns =@JoinColumn(name="pid")
)
/*只能在多的一端控制
*/
10)一对多关联表映射(双向)
一端:
@OneToMany(mappedBy="class2")
多端:
@ManyToOne
@JoinTable(name ="people_study",
joinColumns =@JoinColumn(name="sid"),
inverseJoinColumns =@JoinColumn(name="pid")
)
/*
*通过关联表关联,多端的主键做为关联表的主键,拥有joinColumns属性,一端的主键做为关联表的外键,拥有inverseJoinColumns属性。
*
*/
11)多对多关联映射(单向)
@ManyToMany
/**
* 多对多映射:注解@ManyToMany(单向)
* 默认情况下,hibernate会自动的创建一张中间表,
* 来维护多对多关系
* 默认中间表的名称 :user_role中间表,字段的名称user_id role_id
* 如果想更换表名和字段名称,注解如下:
*/
@JoinTable(name="t_u_r",
joinColumns={@JoinColumn(name="u_id")},
inverseJoinColumns={@JoinColumn(name="r_id")}
)
12)多对多关联映射(双向) User端
@ManyToMany
/**
* 多对多映射:注解@ManyToMany(单向)
* 默认情况下,hibernate会自动的创建一张中间表,
* 来维护多对多关系
* 默认中间表的名称 :user_role中间表,字段的名称user_id role_id
* 如果想更换表名和字段名称,注解如下:
*/
@JoinTable(name="t_u_r",
joinColumns={@JoinColumn(name="u_id")},
inverseJoinColumns={@JoinColumn(name="r_id")}
)
/**
* @JoinTable(name="t_u_r",
* 指定中间表的表名
* joinColumns={@JoinColumn(name="u_id")},
* 指定当前对象的外键
* inverseJoinColumns={@JoinColumn(name="r_id")}
* 指定关联对象的外键
*/
Role端
@ManyToMany(mappedBy="role")
/**
* 多对多,双向关联映射
*/
hibernate注解 一对一主键关联
表结构:
CREATE TABLE `studentbasick` (
`studentId` int(11) NOT NULL auto_increment,
`sex` varchar(10) default NULL,
`studentName` varchar(10) default NULL,
PRIMARY KEY (`studentId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `studentdetailk` (
`studentId` int(11) NOT NULL,
`homeAddress` varchar(50) default NULL,
`homePhoneNumber` varchar(100) default NULL,
PRIMARY KEY (`studentId`),
KEY `FK20021F7FB22DAC9` (`studentId`),
CONSTRAINT `FK20021F7FB22DAC9` FOREIGN KEY (`studentId`) REFERENCES `studentbasick` (`studentId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
类:
package com.gyfbao.model.student.one2one.key;
/**
* @author 郭永福 E-mail:gyfbao@sohu.com
* @version 创建时间:2011-1-22 下午03:08:40
* 类说明
*/
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity(name="StudentBasic")
@Table(name="studentBasick")
public class StudentBasic implements Serializable{
private static final long serialVersionUID = 691350277643811847L;
@Id
@GeneratedValue
@Column(name="studentId")
private Integer studentId;
@Column(length=10)
private String studentName;
@Column(length=10)
private String sex;
@OneToOne(cascade=CascadeType.ALL, mappedBy="basic")
private StudentDetail studentDetail;
public StudentBasic() {
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public StudentDetail getStudentDetail() {
return studentDetail;
}
public void setStudentDetail(StudentDetail studentDetail) {
this.studentDetail = studentDetail;
}
}
package com.gyfbao.model.student.one2one.key;
/**
* @author 郭永福 E-mail:gyfbao@sohu.com
* @version 创建时间:2011-1-22 下午03:09:02
* 类说明
*/
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Entity(name="StudentDetail")
@Table(name="studentDetailk")
public class StudentDetail implements Serializable{
private static final long serialVersionUID = 2038888147029653370L;
@Id
@GeneratedValue(generator="pkGenerator")
@GenericGenerator(name ="pkGenerator",
strategy="foreign" ,
parameters={@Parameter(name="property",value="basic")})
int studentId;
@Column(length=50)
private String homeAddress;
@Column(length=100)
private String homePhoneNumber;
@OneToOne(cascade=CascadeType.ALL)
@PrimaryKeyJoinColumn
private StudentBasic basic;
public StudentDetail() {
}
public String getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public String getHomePhoneNumber() {
return homePhoneNumber;
}
public void setHomePhoneNumber(String homePhomeNumber) {
this.homePhoneNumber = homePhomeNumber;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public StudentBasic getBasic() {
return basic;
}
public void setBasic(StudentBasic basic) {
this.basic = basic;
}
}
测试类:
public class test {
public void save(){
Session session=HibernateSessionFactory.getSession();
Transaction tx =session.beginTransaction();
try{
StudentBasic basic=new StudentBasic();
basic.setStudentName("gyf");
basic.setSex("1");
StudentDetail detail=new StudentDetail();
detail.setHomeAddress("2222");
detail.setHomePhoneNumber("11111");
//basic.setStudentDetail(detail);
detail.setBasic(basic);
session.save(detail);
tx.commit();
}catch(Exception e){
e.printStackTrace();
tx.rollback();
}
session.close();
}
public void list(){
Session session=HibernateSessionFactory.getSession();
StudentDetail detail=(StudentDetail)session.createQuery("select b from StudentDetail b").iterate().next();
// List list=session.createQuery("select b from StudentBasic b").list();
// System.out.println(list.size());
// session.close();
}
public static void main(String[] args){
test t=new test();
t.save();
}
}
hibernate 注解一对一关系 关联表关联
表结构:
CREATE TABLE `studentbasict` (
`studentId` int(11) NOT NULL auto_increment,
`sex` varchar(10) default NULL,
`studentName` varchar(10) default NULL,
PRIMARY KEY (`studentId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `studentdetailt` (
`detailId` int(11) NOT NULL auto_increment,
`homeAddress` varchar(50) default NULL,
`homePhoneNumber` varchar(100) default NULL,
PRIMARY KEY (`detailId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `basicdetail` (
`detailId` int(11) default NULL,
`studentId` int(11) NOT NULL,
PRIMARY KEY (`studentId`),
UNIQUE KEY `detailId` (`detailId`),
KEY `FKEAEC91FF9E05C387` (`detailId`),
KEY `FKEAEC91FF7CDB817A` (`studentId`),
CONSTRAINT `FKEAEC91FF7CDB817A` FOREIGN KEY (`studentId`) REFERENCES `studentbasict` (`studentId`),
CONSTRAINT `FKEAEC91FF9E05C387` FOREIGN KEY (`detailId`) REFERENCES `studentdetailt` (`detailId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
类:
package com.gyfbao.model.student.one2one.table;
/**
* @author 郭永福 E-mail:gyfbao@sohu.com
* @version 创建时间:2011-1-22 上午10:21:57
* 类说明
*/
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity(name="StudentBasic")
@Table(name="studentBasict")
public class StudentBasic implements Serializable{
private static final long serialVersionUID = 691350277643811847L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="studentId")
private Integer studentId;
@Column(length=10)
private String studentName;
@Column(length=10)
private String sex;
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name ="basicdetail",
joinColumns =@JoinColumn(name="studentId"),
inverseJoinColumns =@JoinColumn(name="detailId",unique=true)
)
private StudentDetail studentDetail;
public StudentBasic() {
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public StudentDetail getStudentDetail() {
return studentDetail;
}
public void setStudentDetail(StudentDetail studentDetail) {
this.studentDetail = studentDetail;
}
}
package com.gyfbao.model.student.one2one.table;
/**
* @author 郭永福 E-mail:gyfbao@sohu.com
* @version 创建时间:2011-1-22 上午10:22:27
* 类说明
*/
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity(name="StudentDetail")
@Table(name="studentDetailt")
public class StudentDetail implements Serializable{
private static final long serialVersionUID = 2038888147029653370L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer detailId;
@Column(length=50)
private String homeAddress;
@Column(length=100)
private String homePhoneNumber;
@OneToOne(mappedBy="studentDetail",cascade=CascadeType.ALL)
private StudentBasic basic;
public StudentDetail() {
}
public String getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public String getHomePhoneNumber() {
return homePhoneNumber;
}
public void setHomePhoneNumber(String homePhomeNumber) {
this.homePhoneNumber = homePhomeNumber;
}
public Integer getDetailId() {
return detailId;
}
public void setDetailId(Integer detailId) {
this.detailId = detailId;
}
public StudentBasic getBasic() {
return basic;
}
public void setBasic(StudentBasic basic) {
this.basic = basic;
}
}
测试:
public class test {
public void save(){
Session session=HibernateSessionFactory.getSession();
Transaction tx =session.beginTransaction();
try{
StudentBasic basic=new StudentBasic();
basic.setStudentName("gyf");
basic.setSex("1");
session.persist(basic);
StudentDetail detail=new StudentDetail();
detail.setHomeAddress("2222");
detail.setHomePhoneNumber("11111");
detail.setBasic(basic);
//session.persist(detail);
basic.setStudentDetail(detail);
session.save(basic);
tx.commit();
}catch(Exception e){
e.printStackTrace();
tx.rollback();
}
session.close();
}
public void list(){
Session session=HibernateSessionFactory.getSession();
StudentDetail detail=(StudentDetail)session.createQuery("select b from StudentDetail b").iterate().next();
//List list=session.createQuery("select b from StudentBasic b").list();
//System.out.println(list.size());
session.close();
}
public static void main(String[] args){
test t=new test();
t.list();
}
}
测试持久化过程中与外键关联不同的是,首先要把主键类持久化session.persist(basic),否则会报出非空属性(StudentBasic basic)指向了一个空属性或是瞬态的实例。
hibernate 注解一对一关系 外键关联
表结构:
CREATE TABLE `studentbasic` (
`studentId` int(11) NOT NULL auto_increment,
`studentName` varchar(20) character set utf8 default NULL,
`sex` varchar(10) character set utf8 default NULL,
PRIMARY KEY (`studentId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `studentdetail` (
`studentId` int(11) default NULL,
`homeAddress` varchar(100) character set utf8 default NULL,
`homePhoneNumber` varchar(13) default NULL,
`detailId` int(11) NOT NULL auto_increment,
PRIMARY KEY (`detailId`),
KEY `studentId` (`studentId`),
CONSTRAINT `studentdetail_ibfk_1` FOREIGN KEY (`studentId`) REFERENCES `studentbasic` (`studentId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
类:
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity(name="StudentBasic")
@Table(name="studentBasic")
public class StudentBasic implements Serializable{
private static final long serialVersionUID = 691350277643811847L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="studentId")
private Integer studentId;
@Column(length=10)
private String studentName;
@Column(length=10)
private String sex;
@OneToOne(mappedBy = "basic", cascade = CascadeType.ALL, optional = false)
private StudentDetail studentDetail;
public StudentBasic() {
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public StudentDetail getStudentDetail() {
return studentDetail;
}
public void setStudentDetail(StudentDetail studentDetail) {
this.studentDetail = studentDetail;
}
}
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity(name="StudentDetail")
@Table(name="studentDetail")
public class StudentDetail implements Serializable{
private static final long serialVersionUID = 2038888147029653370L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer detailId;
@OneToOne
@JoinColumn(name="studentId",unique=true)
private StudentBasic basic;
@Column(length=50)
private String homeAddress;
@Column(length=100)
private String homePhoneNumber;
public StudentDetail() {
}
public String getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public String getHomePhoneNumber() {
return homePhoneNumber;
}
public void setHomePhoneNumber(String homePhomeNumber) {
this.homePhoneNumber = homePhomeNumber;
}
public Integer getDetailId() {
return detailId;
}
public void setDetailId(Integer detailId) {
this.detailId = detailId;
}
public StudentBasic getBasic() {
return basic;
}
public void setBasic(StudentBasic basic) {
this.basic = basic;
}
}
测试
public class test {
public void save(){
Session session=HibernateSessionFactory.getSession();
Transaction tx =session.beginTransaction();
StudentBasic basic=new StudentBasic();
basic.setStudentName("gyf");
basic.setSex("男");
StudentDetail detail=new StudentDetail();
detail.setHomeAddress("和平南路");
detail.setHomePhoneNumber("11111");
basic.setStudentDetail(detail);
detail.setBasic(basic);
try{
session.save(basic);
tx.commit();
}catch(Exception e){
e.printStackTrace();
tx.rollback();
}
session.close();
}
public void list(){
Session session=HibernateSessionFactory.getSession();
StudentBasic basic=(StudentBasic)session.createQuery("select b from StudentBasic b").iterate().next();
System.out.println(basic.toString());
session.close();
}
public static void main(String[] args){
test t=new test();
t.list();
}
}
hibernate注解 一对多 外键关联
类:
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* @author 郭永福 E-mail:gyfbao@sohu.com
* @version 创建时间:2011-1-23 下午03:38:09
* 类说明
*/
@Entity
@Table(name="people")
public class People {
private int id;
private String name;
private String address;
private Set<Study> stydy;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@OneToMany//(mappedBy="people")不可与@JoinColumn同时使用,使用mappedBy会在多的一端自动生成外键.
@JoinColumn(name="pid")//指定多的一端的外键,在多的一端也必须这样设置,否则会生成多个外键.
public Set<Study> getStydy() {
return stydy;
}
public void setStydy(Set<Study> stydy) {
this.stydy = stydy;
}
}
import java.util.Date;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* @author 郭永福 E-mail:gyfbao@sohu.com
* @version 创建时间:2011-1-23 下午03:40:33
* 类说明
*/
@Entity
@Table(name="study")
public class Study {
private int id;
private String schoolname;
private Date start;
private Date end;
private People people;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSchoolname() {
return schoolname;
}
public void setSchoolname(String schoolname) {
this.schoolname = schoolname;
}
@Temporal(TemporalType.DATE)
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
@Temporal(TemporalType.DATE)
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
@ManyToOne
@JoinColumn(name="pid")//同一的一端一样
public People getPeople() {
return people;
}
public void setPeople(People people) {
this.people = people;
}
}
测试类:
public class test {
public void save(){
Session session=HibernateSessionFactory.getSession();
Transaction tx =session.beginTransaction();
try{
People people=new People();
people.setAddress("aaaddd");
people.setName("gyfbao");
Study study1=new Study();
study1.setSchoolname("tyyz");
study1.setStart(new Date());
study1.setEnd(new Date());
session.persist(study1);
Study study2=new Study();
study2.setSchoolname("tywz");
session.persist(study2);
Set<Study> stu=new HashSet();
stu.add(study1);
stu.add(study2);
study1.setPeople(people);
study2.setPeople(people);
people.setStydy(stu);
session.save(people);
tx.commit();
}catch(Exception e){
e.printStackTrace();
tx.rollback();
}
session.close();
}
public void list(){
Session session=HibernateSessionFactory.getSession();
// List<People> list=session.createQuery("select p from People p").list();
// for(People p:list){
// Set<Study> study=p.getStydy();
// for(Study s:study){
// System.out.println(s.getSchoolname());
// }
// }
List<Study> list=session.createQuery("select s from Study s").list();
for(Study s:list){
People p=s.getPeople();
System.out.println(p.getName());
}
session.close();
}
public static void main(String[] args){
test t=new test();
t.list();
}
}
hibernate 注解一对多 关联表映射
类:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* @author 郭永福 E-mail:gyfbao@sohu.com
* @version 创建时间:2011-1-23 下午03:38:09
* 类说明
*/
@Entity
@Table(name="people")
public class People {
private int id;
private String name;
private String address;
private Set<Study> stydy;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@OneToMany(mappedBy="people")
public Set<Study> getStydy() {
return stydy;
}
public void setStydy(Set<Study> stydy) {
this.stydy = stydy;
}
}
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* @author 郭永福 E-mail:gyfbao@sohu.com
* @version 创建时间:2011-1-23 下午03:40:33
* 类说明
*/
@Entity
@Table(name="study")
public class Study {
private int id;
private String schoolname;
private Date start;
private Date end;
private People people;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSchoolname() {
return schoolname;
}
public void setSchoolname(String schoolname) {
this.schoolname = schoolname;
}
@Temporal(TemporalType.DATE)
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
@Temporal(TemporalType.DATE)
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
@ManyToOne
@JoinTable(name ="people_study",
joinColumns =@JoinColumn(name="sid"),
inverseJoinColumns =@JoinColumn(name="pid")
)
public People getPeople() {
return people;
}
public void setPeople(People people) {
this.people = people;
}
}
测试类:与前边一对多相同
hibernate注解多对多映射
类:
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
/**
* @author 郭永福 E-mail:gyfbao@sohu.com
* @version 创建时间:2011-1-25 上午09:54:35
* 类说明
*/
@Entity
@Table(name="users")
public class user {
private int id;
private String name;
private String passwd;
private Set<role> roles;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
@ManyToMany
public Set<role> getRoles() {
return roles;
}
public void setRoles(Set<role> roles) {
this.roles = roles;
}
}
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
/**
* @author 郭永福 E-mail:gyfbao@sohu.com
* @version 创建时间:2011-1-25 上午09:55:19
* 类说明
*/
@Entity
@Table(name="roles")
public class role {
private int id;
private String name;
private String cont;
private Set<user> users;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCont() {
return cont;
}
public void setCont(String cont) {
this.cont = cont;
}
@ManyToMany(mappedBy="roles")
public Set<user> getUsers() {
return users;
}
public void setUsers(Set<user> users) {
this.users = users;
}
}
测试类:
public class test {
public void save(){
Session session=HibernateSessionFactory.getSession();
Transaction tx =session.beginTransaction();
try{
user user1=new user();
user user2=new user();
role role1=new role();
role role2=new role();
role1.setName("gyf");
role2.setName("bao");
session.persist(role1);
session.persist(role2);
user1.setName("hhhh");
user2.setName("bbbb");
Set<user> users=new HashSet();
users.add(user1);
users.add(user2);
Set<role> roles=new HashSet();
roles.add(role1);
roles.add(role2);
user1.setRoles(roles);
user2.setRoles(roles);
role1.setUsers(users);
role2.setUsers(users);
session.save(user1);
session.save(user2);
tx.commit();
}catch(Exception e){
e.printStackTrace();
tx.rollback();
}
session.close();
}
public void list(){
Session session=HibernateSessionFactory.getSession();
// List <user> list=session.createQuery("select u from user u").list();
// for(user u:list){
// List<role> roles=new ArrayList(u.getRoles());
// for(role r:roles){
// System.out.println(r.getName());
// }
// }
List<role> list=session.createQuery("select r from role r").list();
for(role r:list){
List<user> users=new ArrayList(r.getUsers());
for(user u:users){
System.out.println(u.getName());
}
}
session.close();
}
public static void main(String[] args){
test t=new test();
t.list();
}
}
本文内容参考http://gyfbao.blog.sohu.com//entry/8176950/