- 浏览: 13262 次
文章分类
最新评论
电子书下载地址:
http://xiaochenggushi.iteye.com/admin/pdf_jobs/12250
hibernate注解总结一
hibernate注解总结二
hibernate注解 一对一主键关联
hibernate 注解一对一关系 关联表关联
hibernate 注解一对一关系 外键关联
hibernate注解 一对多 外键关联
hibernate 注解一对多 关联表映射
hibernate注解多对多映射
本文内容参考http://gyfbao.blog.sohu.com//entry/8176950/
http://xiaochenggushi.iteye.com/admin/pdf_jobs/12250
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/
相关推荐
本文主要总结了Hibernate中常见的注解用法,涵盖了类级别和属性级别的注解,以及与主键和非主键相关的注解。 1. 类级别注解: - `@Entity`: 这个注解是必不可少的,它告诉Hibernate一个Java类是一个实体,可以映射...
每个实体类都需要一个对应的 Hibernate 映射文件(.hbm.xml),或者使用注解进行配置,定义类与表的映射关系。映射文件或注解包含字段类型、主键策略、关联关系等信息。 **SessionFactory 和 Session** ...
1. Hibernate配置: Hibernate的配置主要通过一个名为`hibernate.cfg.xml`的文件进行。该文件定义了与数据库的连接参数、方言、缓存策略等关键设置。例如: - `connection.driver_class`: 指定数据库驱动,如`...
总结来说,Hibernate注解极大地简化了Java应用的数据库操作,通过注解我们可以定义实体、关联、缓存策略等,使得代码更简洁,同时也提高了开发效率。理解和熟练运用这些注解是成为高效Hibernate开发者的关键。在实践...
通过上述分析,我们可以看出Hibernate注解编程是一种高效且灵活的方式来实现持久化层的功能。它简化了配置过程,使开发者能够更加专注于业务逻辑的编写。此外,Hibernate还提供了强大的映射机制,支持复杂的关联关系...
在 Hibernate 中,注解是一种简洁且强大的工具,用于替代传统的 XML 配置文件来描述对象模型和数据库之间的映射关系。这篇文档将深入探讨 Hibernate 注解的使用。 ### 第 1 章 创建一个注解项目 在开始使用 ...
总结来说,Hibernate的注解使得我们可以方便地在Java实体类中描述数据库中的关系,极大地简化了ORM的过程。`@OneToMany`、`@ManyToMany`和`@OneToOne`注解分别对应了一对多、多对多和一对一的关系映射,通过合理的...
Hibernate是一款强大的Java对象关系映射(ORM)框架,它极大地简化了数据库操作,使得开发者可以使用面向对象的方式处理数据库事务。在本文中,我们将深入探讨Hibernate的关键概念、配置、实体管理、查询语言以及...
总结,Hibernate注解提供了一种高效、简洁的ORM解决方案,是现代Java开发中不可或缺的一部分。理解和熟练掌握这些注解,将有助于提升开发效率,降低项目维护成本。在实际开发中,应根据项目需求和团队习惯,合理选择...
**Hibernate学习笔记与总结** Hibernate 是一款开源的对象关系映射(ORM)框架,它为Java开发者提供了一种在关系数据库上操作对象数据的便捷方式。本文将深入探讨Hibernate的核心概念、配置、实体类、映射文件、...
方便 Hibernate 注解的查询使用,包含了常用的注解及其属性值和说明!
### Hibernate注解详解 #### 一、概述 Hibernate是一个开源的对象关系映射(ORM)框架,用于Java应用程序中实现数据库操作。它通过提供强大的映射工具和服务,简化了基于Java的应用程序开发人员对数据库的访问过程...
本文将详细讲解Hibernate注解的使用,包括持久化类的声明、属性映射以及对象关联关系的配置。 一、什么是注解? 注解是一种元数据,它为编译器和JVM提供关于代码的附加信息。在Hibernate中,注解用于标记Java类和...
【标签】:Hibernate, Annotation, 笔记, 总结, 注解 【正文】: Hibernate Annotation是Hibernate框架的一个重要特性,它允许开发者直接在Java类上使用注解来定义对象的数据库映射,从而避免了传统的XML配置文件...
《注释驱动的Hibernate实战详解》 在Java的持久化框架中,Hibernate以其强大的功能和易用性,深受开发者喜爱。...通过实践和学习,我们可以更好地利用Hibernate注解,提升开发效率,降低维护成本。
### Hibernate关联映射总结 #### 一、基础知识 在探讨Hibernate中的关联映射之前,我们需要先理解几个基本概念,这将有助于我们更好地理解和应用这些关联映射。 - **主键**(Primary Key):主键是用来唯一标识一...
**一、Hibernate注解基础** 在Hibernate 3.2之后,引入了注解支持,使得开发者不再需要XML配置文件来定义实体类和映射关系。主要的注解包括: 1. `@Entity`:标记一个Java类为Hibernate实体类,对应数据库中的表。...
1. **Configuration** 类是Hibernate框架的核心配置类,负责读取配置文件并初始化配置信息。构造方法会默认读取 `hibernate.properties` 文件,如果需要使用其他的配置文件,可以通过 `configure(String ...