表结构

实体类关系

实体类源代码

Student

package com.demo.model;

import java.io.UnsupportedEncodingException;
import java.util.Set; /**学生信息
* @author wobendiankun
*2014-10-19 下午08:54:29
*/
public class Student {
private int studentId ;
private String studentName ;
private int age;
private Set<Certificate> certificates ;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
String str="";
if(studentName!=null){
try {
str=new String(studentName.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return "Student [studentId=" + studentId + ", studentName="
+ str + ", age=" + age + "]";
}
public Set<Certificate> getCertificates() {
return certificates;
}
public void setCertificates(Set<Certificate> certificates) {
this.certificates = certificates;
} }

Certificate

package com.demo.model;

/**从业资格证书
* @author wobendiankun
*2014-10-25 上午11:43:21
*/
public class Certificate {
/**
* 证书id
*/
private int certificateId ;
/**
* 证书名称
*/
private String certificateName;
/**
*证书编号
*/
private String certificateNo ; private Student student ;
public int getCertificateId() {
return certificateId;
}
public void setCertificateId(int certificateId) {
this.certificateId = certificateId;
}
public String getCertificateName() {
return certificateName;
}
public void setCertificateName(String certificateName) {
this.certificateName = certificateName;
}
public String getCertificateNo() {
return certificateNo;
}
public void setCertificateNo(String certificateNo) {
this.certificateNo = certificateNo;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
} }

xml配置:

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping > <class name="com.demo.model.Student" table="t_student">
<id name="studentId" column="student_id">
<generator class="sequence">
<param name="sequence">SEQ_T_STUDENT</param>
</generator>
</id>
<property name="studentName" column="student_name" />
<property name="age" /> <set name="certificates" lazy="extra"><!-- lazy="extra" -->
<key column="student_id"></key>
<one-to-many class="com.demo.model.Certificate"/>
</set>
</class>
</hibernate-mapping>

Certificate.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping > <class name="com.demo.model.Certificate" table="t_certificate">
<id name="certificateId" column="certificate_id">
<generator class="sequence"><param name="sequence">SEQ_T_CERTIFICATE</param></generator>
</id>
<property name="certificateName" column="certificate_name"/>
<property name="certificateNo" column="certificate_no"/>
<many-to-one name="student" column="student_id"></many-to-one>
</class>
</hibernate-mapping>

CRUD:

add:

@Test
public void addTest(){
Set<Certificate> certificates=new HashSet<Certificate>();
Student student = new Student();
student.setStudentName("王五");
student.setAge(35); Certificate certificate1 = new Certificate();
certificate1.setCertificateName("aa");
certificate1.setCertificateNo("3a10001");
certificate1.setStudent(student);
Certificate certificate2 = new Certificate();
certificate2.setCertificateName("bb");
certificate2.setCertificateNo("3a10002");
certificate2.setStudent(student); Session session = null; try {
session = HibernateUtil.openSession();
session.beginTransaction();
// 先保存one,再保存many
session.save(student);
session.save(certificate1);
session.save(certificate2);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
HibernateUtil.closeSession(session);
}
}

发出的SQL:

Hibernate: insert into t_student (student_name, age, student_id) values (?, ?, ?)
Hibernate: insert into t_certificate (certificate_name, certificate_no, student_id, certificate_id) values (?, ? , ? , ?)
Hibernate: insert into t_certificate (certificate_name, certificate_no, student_id, certificate_id) values (? , ? , ?, ?)

update:

@Test
public void updateStudentTest(){
Student student=new Student();
student.setStudentId(63);
student.setStudentName("李九");
Session session = null;
try {
session = HibernateUtil.openSession();
session.beginTransaction();
session.update(student);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
HibernateUtil.closeSession(session);
}
}

发出的SQL:

Hibernate: update t_student set student_name=?, age=? where student_id=?
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:

<?

xml version="1.0"?

>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping > <class name="com.demo.model.Student" table="t_student">
<id name="studentId" column="student_id">
<generator class="sequence">
<param name="sequence">SEQ_T_STUDENT</param>
</generator>
</id>
<property name="studentName" column="student_name" />
<property name="age" /> <set name="certificates" lazy="extra" inverse="true">
<key column="student_id"></key>
<one-to-many class="com.demo.model.Certificate"/>
</set>
</class>
</hibernate-mapping>

updateInverse

@Test
public void updateStudentWithInverseTest(){
Student student=new Student();
student.setStudentId(63);
student.setStudentName("李九");
Session session = null;
try {
session = HibernateUtil.openSession();
session.beginTransaction();
session.update(student);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
HibernateUtil.closeSession(session);
}
}

发出的SQL:

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

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

loadCertificate:

@Test
public void loadCertificateTest(){
Session session = null;
try {
session = HibernateUtil.openSession();
session.beginTransaction();
Certificate certificate=(Certificate)session.load(Certificate.class, 65);
Certificate certificate2=(Certificate)session.load(Certificate.class, 66);
System.out.println("编号:"+certificate.getCertificateNo());
System.out.println("姓名:"+certificate.getStudent().getStudentName());
System.out.println("---------------------------");
System.out.println("编号:"+certificate2.getCertificateNo());
System.out.println("姓名:"+certificate2.getStudent().getStudentName());
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
HibernateUtil.closeSession(session);
}
}

发出的SQL:

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=?
编号:3a10001
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=?
姓名:李九
---------------------------
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=?
编号:3a10002
姓名:李九

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

loadStudent:

@Test
public void loadStudentTest(){
Session session = null;
try {
session = HibernateUtil.openSession();
session.beginTransaction();
Student student=(Student)session.load(Student.class, 63);
System.out.println("姓名:"+student.getStudentName());
for(Certificate c:student.getCertificates()){
System.out.println("\t编号:"+c.getCertificateNo());
}
System.out.println("-------------------");
Certificate c1=(Certificate)session.get(Certificate.class, 65);
System.out.println("编号:"+c1.getCertificateNo());
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
HibernateUtil.closeSession(session);
}
}

发出的SQL

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=?
姓名:李九
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=? 编号:3a10001
编号:3a10002
-------------------
编号: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. java web支持jsonp跨域

    jsonp跨域请求处理 Jsonp(JSON with Padding) 是 json的一种"使用模式",可以让网页从别的域名(网站)那获取资料,绕过同源策略(若地址里面的协议.域 ...

  2. 《疯狂Python讲义》重要笔记--变量

    一个Python解释器 接下来的旅程——你需要下载好Python,Python解释器通常放在 /usr/local/bin/python3.7 ; 在Unix系统的bash中输入 where pyth ...

  3. Java 位运算符 &、|、^、~、<<、>>、>>>

      撸了N久的代码,但是突然冒出来个位运算,我就蒙蔽了,这是什么?我是谁?我在干什么?我在哪? 1)闲扯 关于位运算符无非也就 与(&).或(|).异或(^).取反(~).左移(<< ...

  4. 树形$dp$学习笔记

    今天学习了树形\(dp\),一开始浏览各大\(blog\),发现都\(TM\)是题,连个入门的\(blog\)都没有,体验极差.所以我立志要写一篇可以让初学树形\(dp\)的童鞋快速入门. 树形\(d ...

  5. B - Sleuth

    Problem description Vasya plays the sleuth with his friends. The rules of the game are as follows: t ...

  6. Java 判断字符串的存储长度

    判断前台输入项的长度应该都会碰到String.length()  判断出来没有超出最大长度,存到数据库就超出长度的问题,oracle字符集是gbk的不太清楚,如果是UTF-8,中文是占三个字符的,所以 ...

  7. 易企CMS主要模板文件介绍

    article.tpl 文章内容页模板 catalog.tpl 文章,产品目录页模板 category.tpl 分类页模板 comment.tpl 留言页模板 footer.tpl 页尾模板 head ...

  8. 使用 gradle 在编译时动态设置 Android resValue / BuildConfig / Manifes中<meta-data>变量的值

    转载请说明来源: http://www.cnblogs.com/lizhilin2016/p/7390079.html 最近lz 在开始做一个新的Demo, 在项目中集成了bugly用于收集项目中的崩 ...

  9. CDC之Metastability

    1 CDC  A clock domain crossing occurs whenever data is transferred from a flop driven by one clock t ...

  10. hadoop单机环境配置

    1.配置一台linux服务器(当前使用CentOS7)及一些基本设置 1.1在wmware下制作一台centos服务器(桥接模式)         并设置静态ip (编辑/etc/sysmconfig ...