表结构

实体类关系

实体类源代码

Student

  1. package com.demo.model;
  2.  
  3. import java.io.UnsupportedEncodingException;
  4. import java.util.Set;
  5.  
  6. /**学生信息
  7. * @author wobendiankun
  8. *2014-10-19 下午08:54:29
  9. */
  10. public class Student {
  11. private int studentId ;
  12. private String studentName ;
  13. private int age;
  14. private Set<Certificate> certificates ;
  15. public int getStudentId() {
  16. return studentId;
  17. }
  18. public void setStudentId(int studentId) {
  19. this.studentId = studentId;
  20. }
  21. public String getStudentName() {
  22. return studentName;
  23. }
  24. public void setStudentName(String studentName) {
  25. this.studentName = studentName;
  26. }
  27. public int getAge() {
  28. return age;
  29. }
  30. public void setAge(int age) {
  31. this.age = age;
  32. }
  33. @Override
  34. public String toString() {
  35. String str="";
  36. if(studentName!=null){
  37. try {
  38. str=new String(studentName.getBytes("UTF-8"));
  39. } catch (UnsupportedEncodingException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. return "Student [studentId=" + studentId + ", studentName="
  44. + str + ", age=" + age + "]";
  45. }
  46. public Set<Certificate> getCertificates() {
  47. return certificates;
  48. }
  49. public void setCertificates(Set<Certificate> certificates) {
  50. this.certificates = certificates;
  51. }
  52.  
  53. }

Certificate

  1. package com.demo.model;
  2.  
  3. /**从业资格证书
  4. * @author wobendiankun
  5. *2014-10-25 上午11:43:21
  6. */
  7. public class Certificate {
  8. /**
  9. * 证书id
  10. */
  11. private int certificateId ;
  12. /**
  13. * 证书名称
  14. */
  15. private String certificateName;
  16. /**
  17. *证书编号
  18. */
  19. private String certificateNo ;
  20.  
  21. private Student student ;
  22. public int getCertificateId() {
  23. return certificateId;
  24. }
  25. public void setCertificateId(int certificateId) {
  26. this.certificateId = certificateId;
  27. }
  28. public String getCertificateName() {
  29. return certificateName;
  30. }
  31. public void setCertificateName(String certificateName) {
  32. this.certificateName = certificateName;
  33. }
  34. public String getCertificateNo() {
  35. return certificateNo;
  36. }
  37. public void setCertificateNo(String certificateNo) {
  38. this.certificateNo = certificateNo;
  39. }
  40. public Student getStudent() {
  41. return student;
  42. }
  43. public void setStudent(Student student) {
  44. this.student = student;
  45. }
  46.  
  47. }

xml配置:

Student.hbm.xml

  1. <?xml version="1.0"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5.  
  6. <hibernate-mapping >
  7.  
  8. <class name="com.demo.model.Student" table="t_student">
  9. <id name="studentId" column="student_id">
  10. <generator class="sequence">
  11. <param name="sequence">SEQ_T_STUDENT</param>
  12. </generator>
  13. </id>
  14. <property name="studentName" column="student_name" />
  15. <property name="age" />
  16.  
  17. <set name="certificates" lazy="extra"><!-- lazy="extra" -->
  18. <key column="student_id"></key>
  19. <one-to-many class="com.demo.model.Certificate"/>
  20. </set>
  21. </class>
  22. </hibernate-mapping>

Certificate.hbm.xml

  1. <?xml version="1.0"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5.  
  6. <hibernate-mapping >
  7.  
  8. <class name="com.demo.model.Certificate" table="t_certificate">
  9. <id name="certificateId" column="certificate_id">
  10. <generator class="sequence"><param name="sequence">SEQ_T_CERTIFICATE</param></generator>
  11. </id>
  12. <property name="certificateName" column="certificate_name"/>
  13. <property name="certificateNo" column="certificate_no"/>
  14. <many-to-one name="student" column="student_id"></many-to-one>
  15. </class>
  16. </hibernate-mapping>

CRUD:

add:

  1. @Test
  2. public void addTest(){
  3. Set<Certificate> certificates=new HashSet<Certificate>();
  4. Student student = new Student();
  5. student.setStudentName("王五");
  6. student.setAge(35);
  7.  
  8. Certificate certificate1 = new Certificate();
  9. certificate1.setCertificateName("aa");
  10. certificate1.setCertificateNo("3a10001");
  11. certificate1.setStudent(student);
  12. Certificate certificate2 = new Certificate();
  13. certificate2.setCertificateName("bb");
  14. certificate2.setCertificateNo("3a10002");
  15. certificate2.setStudent(student);
  16.  
  17. Session session = null;
  18.  
  19. try {
  20. session = HibernateUtil.openSession();
  21. session.beginTransaction();
  22. // 先保存one,再保存many
  23. session.save(student);
  24. session.save(certificate1);
  25. session.save(certificate2);
  26. session.getTransaction().commit();
  27. } catch (Exception e) {
  28. session.getTransaction().rollback();
  29. e.printStackTrace();
  30. } finally {
  31. HibernateUtil.closeSession(session);
  32. }
  33. }

发出的SQL:

  1. Hibernate: insert into t_student (student_name, age, student_id) values (?, ?, ?)
  2. Hibernate: insert into t_certificate (certificate_name, certificate_no, student_id, certificate_id) values (?, ?
  3.  
  4. , ?
  5.  
  6. , ?)
  7. Hibernate: insert into t_certificate (certificate_name, certificate_no, student_id, certificate_id) values (?
  8.  
  9. , ?
  10.  
  11. , ?, ?)

update:

  1. @Test
  2. public void updateStudentTest(){
  3. Student student=new Student();
  4. student.setStudentId(63);
  5. student.setStudentName("李九");
  6. Session session = null;
  7. try {
  8. session = HibernateUtil.openSession();
  9. session.beginTransaction();
  10. session.update(student);
  11. session.getTransaction().commit();
  12. } catch (Exception e) {
  13. session.getTransaction().rollback();
  14. e.printStackTrace();
  15. } finally {
  16. HibernateUtil.closeSession(session);
  17. }
  18. }

发出的SQL:

  1. Hibernate: update t_student set student_name=?, age=? where student_id=?
  2. Hibernate: update t_certificate set student_id=null where student_id=?

因为Student为one的一方,默认发维护关联字段。会多发送一条更新语句,解决方案为加入配置 inverse="true" (Student.hbm.xml的set元素中,加入属性),

inverse="true" 代表由:many的一方来维护关联字段

Student.hbm.xml:

  1. <?
  2.  
  3. xml version="1.0"?
  4.  
  5. >
  6. <!DOCTYPE hibernate-mapping PUBLIC
  7. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  8. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  9.  
  10. <hibernate-mapping >
  11.  
  12. <class name="com.demo.model.Student" table="t_student">
  13. <id name="studentId" column="student_id">
  14. <generator class="sequence">
  15. <param name="sequence">SEQ_T_STUDENT</param>
  16. </generator>
  17. </id>
  18. <property name="studentName" column="student_name" />
  19. <property name="age" />
  20.  
  21. <set name="certificates" lazy="extra" inverse="true">
  22. <key column="student_id"></key>
  23. <one-to-many class="com.demo.model.Certificate"/>
  24. </set>
  25. </class>
  26. </hibernate-mapping>

updateInverse

  1. @Test
  2. public void updateStudentWithInverseTest(){
  3. Student student=new Student();
  4. student.setStudentId(63);
  5. student.setStudentName("李九");
  6. Session session = null;
  7. try {
  8. session = HibernateUtil.openSession();
  9. session.beginTransaction();
  10. session.update(student);
  11. session.getTransaction().commit();
  12. } catch (Exception e) {
  13. session.getTransaction().rollback();
  14. e.printStackTrace();
  15. } finally {
  16. HibernateUtil.closeSession(session);
  17. }
  18. }

发出的SQL:

  1. Hibernate: update t_student set student_name=?, age=? where student_id=?

维护关联字段的update语句不出现了

loadCertificate:

  1. @Test
  2. public void loadCertificateTest(){
  3. Session session = null;
  4. try {
  5. session = HibernateUtil.openSession();
  6. session.beginTransaction();
  7. Certificate certificate=(Certificate)session.load(Certificate.class, 65);
  8. Certificate certificate2=(Certificate)session.load(Certificate.class, 66);
  9. System.out.println("编号:"+certificate.getCertificateNo());
  10. System.out.println("姓名:"+certificate.getStudent().getStudentName());
  11. System.out.println("---------------------------");
  12. System.out.println("编号:"+certificate2.getCertificateNo());
  13. System.out.println("姓名:"+certificate2.getStudent().getStudentName());
  14. session.getTransaction().commit();
  15. } catch (Exception e) {
  16. session.getTransaction().rollback();
  17. e.printStackTrace();
  18. } finally {
  19. HibernateUtil.closeSession(session);
  20. }
  21. }

发出的SQL:

  1. Hibernate: select certificat0_.certificate_id as certific1_1_0_, certificat0_.certificate_name as certific2_1_0_, certificat0_.certificate_no as certific3_1_0_, certificat0_.student_id as student4_1_0_ from t_certificate certificat0_ where certificat0_.certificate_id=?
  2. 编号:3a10001
  3. Hibernate: select student0_.student_id as student1_0_0_, student0_.student_name as student2_0_0_, student0_.age as age0_0_ from t_student student0_ where student0_.student_id=?
  4. 姓名:李九
  5. ---------------------------
  6. Hibernate: select certificat0_.certificate_id as certific1_1_0_, certificat0_.certificate_name as certific2_1_0_, certificat0_.certificate_no as certific3_1_0_, certificat0_.student_id as student4_1_0_ from t_certificate certificat0_ where certificat0_.certificate_id=?
  7. 编号:3a10002
  8. 姓名:李九

共三条查询语句,查询id为66的记录时,因为id为63的Student对象已经变化在session中,所以不会再发出查询id为63的语句

loadStudent:

  1. @Test
  2. public void loadStudentTest(){
  3. Session session = null;
  4. try {
  5. session = HibernateUtil.openSession();
  6. session.beginTransaction();
  7. Student student=(Student)session.load(Student.class, 63);
  8. System.out.println("姓名:"+student.getStudentName());
  9. for(Certificate c:student.getCertificates()){
  10. System.out.println("\t编号:"+c.getCertificateNo());
  11. }
  12. System.out.println("-------------------");
  13. Certificate c1=(Certificate)session.get(Certificate.class, 65);
  14. System.out.println("编号:"+c1.getCertificateNo());
  15. session.getTransaction().commit();
  16. } catch (Exception e) {
  17. session.getTransaction().rollback();
  18. e.printStackTrace();
  19. } finally {
  20. HibernateUtil.closeSession(session);
  21. }
  22. }

发出的SQL

  1. Hibernate: select student0_.student_id as student1_0_0_, student0_.student_name as student2_0_0_, student0_.age as age0_0_ from t_student student0_ where student0_.student_id=?
  2. 姓名:李九
  3. Hibernate: select certificat0_.student_id as student4_0_1_, certificat0_.certificate_id as certific1_1_, certificat0_.certificate_id as certific1_1_0_, certificat0_.certificate_name as certific2_1_0_, certificat0_.certificate_no as certific3_1_0_, certificat0_.student_id as student4_1_0_ from t_certificate certificat0_ where certificat0_.student_id=?
  4.  
  5. 编号:3a10001
  6. 编号:3a10002
  7. -------------------
  8. 编号:3a10001

id为65的Certificate对象,已经存在session中,所以session.get(Certificate.class, 65);不会发送查询语句

hibernate之7.one2many双向的更多相关文章

  1. hibernate一对一外键双向关联

    关联是类(类的实例)之间的关系,表示有意义和值得关注的连接. 本系列将介绍Hibernate中主要的几种关联映射 Hibernate一对一主键单向关联Hibernate一对一主键双向关联Hiberna ...

  2. hibernate一对一主键双向关联

    关联是类(类的实例)之间的关系,表示有意义和值得关注的连接. 本系列将介绍Hibernate中主要的几种关联映射 Hibernate一对一主键单向关联Hibernate一对一主键双向关联Hiberna ...

  3. Hibernate的关联映射——双向1-N关联

    Hibernate的关联映射--双向1-N关联 对于1-N的关联,Hibernate推荐使用双向关联,而且不要让1的一端控制关联关系,而是用N的一端控制关联关系.双线的1-N关联和N-1关联是两种相同 ...

  4. hibernate(十)双向关联关系的CRUD

    本文链接:http://www.orlion.ml/28/ 一.保存 1. 假设一个group有多个user,一个user只属于一个group,当保存user对象到数据库中时可以 User u = n ...

  5. Hibernate映射多对多双向关联关系(小案例)

    多对多双向关联关系(Project(工程)/Emp(员工)为案例): 步骤如下: 1.创建Project类,并需要定义集合类型的Emp属性 public class Project { //编号 pr ...

  6. [原创]java WEB学习笔记83:Hibernate学习之路---双向 1-n介绍,关键点解释,代码实现,set属性介绍(inverse,cascade ,order-by )

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  7. Hibernate 一对多自身双向关联关系 用于类别表的实现

    分类:一对多自身双向关联关系 Java持久化类: package com.hyy.hibernate.one_to_many.domain; import java.util.HashSet; imp ...

  8. hibernate它 11.many2many双向

    表结构: 类图: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd29iZW5kaWFua3Vu/font/5a6L5L2T/fontsize/400/fi ...

  9. Hibernate 建立一对多双向关联关系

    下面内容整理自<精通Hibernate>第二版 注:既然是双向关联."一对多双向关联"和"多对一双向关联"是同一回事. 对象位于内存中,在内存中从一 ...

随机推荐

  1. 当Shell遇上了Node.js(转载)

    转载:http://developer.51cto.com/art/201202/315066.htm 好吧,我承认,这个标题有点暧昧的基情,但是希望下文的内部能给不熟悉或不喜欢Shell或WIN平台 ...

  2. layui日期输入框

    <div class="layui-form-item">                <label class="layui-form-label& ...

  3. Spark2.2,IDEA,Maven开发环境搭建附测试

    前言: 停滞了一段时间,现在要沉下心来学习点东西,出点货了. 本文没有JavaJDK ScalaSDK和 IDEA的安装过程,网络上会有很多文章介绍这个内容,因此这里就不再赘述. 一.在IDEA上安装 ...

  4. ACM_螺旋填数

    螺旋填数 Time Limit: 2000/1000ms (Java/Others) Problem Description: 一天,小明在研究蜗牛的壳时,对其螺旋状的花纹感到十分有趣.于是他回到了家 ...

  5. xml之基本操作

    XML:Extensible Markup Language(可扩展标记语言)的缩写,是用来定义其它语言的一种元语言,其前身是SGML(Standard Generalized Markup Lang ...

  6. wcf 错误:无法加载或初始化请求的服务提供程序

    解决办法:cmd netsh winsock reset 恢复网络编程接口

  7. Spring + Redis ( 简单使用)

    1.Redis 的 Java API Java 中 使用 Redis 工具,要先去 maven 仓库中,下载 jedis jar包 jedis 依赖 <dependency> <gr ...

  8. windows phone控件

    常用控件: 包括: Button控件.CheckBox控件.HyperlinkButton控件.Iamege控件.ListBox控件.PasswordBox控件.ProgressBar控件.Radio ...

  9. 【SQL】含有NULL值的排序

    查询结果中有NULL值,当进行升序排序时,NULL值默认为“最大值”,排在最后面.要想改变NULL值的显示顺序,只需要在SQL语句后面加上NULLS FIRST(排在前面),NULLS LAST(排在 ...

  10. php知识点(基本上文档都有,只为方便记忆)

    类型转换 (unset)转换为NULL (binary) 转换和 b 前缀转换支持为 PHP 5.2.1 新增   转换二进制 隐藏php后缀名 AddType application/x-httpd ...