关联映射
多对一(Employee - Department)
一对多(Department-Employee)
一对一(Person - IDCard)
多对多(teacher - student)
组件映射(User-Name)
集合映射(set, list, map, bag)
inverse和cascade(Employee – Department)
 
多对一(Employee - Department)
映射文件<many-to-one name=”depart” column=”depart_id”/>
ER图
 
举例:
Department.java

package com.dzq.domain;

import java.io.Serializable;
import java.util.Set; public class Department implements Serializable{
private int id;
private String name;
private Set<Employee> empls;
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 Set<Employee> getEmpls() {
return empls;
} public void setEmpls(Set<Employee> empls) {
this.empls = empls;
} }

Employee.java

package com.dzq.domain;

import java.io.Serializable;

public class Employee implements Serializable{
private int id;
private String name;
private Department depart; 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 Department getDepart() {
return depart;
} public void setDepart(Department depart) {
this.depart = depart;
} }

Department.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 package="com.dzq.domain"> <class name="Department" table="department">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" />
</class> </hibernate-mapping>

  


Employee.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 package="com.dzq.domain"> <class name="Employee" table="employee">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" />
<many-to-one name="depart" column="depart_id" />
</class> </hibernate-mapping>

  测试代码:

public static void addEmAndDe(){
Employee em=new Employee();
Department depart=new Department();
depart.setName("FBI");
em.setDepart(depart);
em.setName("AK47");
HibernateUntils.add(depart);
HibernateUntils.add(em);
}

  

一对多(Department-Employee)
<set name=”employees”>
<key column=”depart_id”/>
<one-to-many class=”Employee”/>
</set>

  

一对一(Person - IdCard)
1)基于主键的one-to-one(person的映射文件)
<id name=”id”>
<generator class=”foreign”><param name=”property”>idCard</param></generator>
<id>
<one-to-one name=”idCard” constrained=”true”/>

例子:

Person.java  主对象

package com.dzq.domain;

import java.io.Serializable;

public class Person  implements Serializable{
private int id;
private String name;
private IDCard idcard; 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 IDCard getIdcard() {
return idcard;
} public void setIdcard(IDCard idcard) {
this.idcard = idcard;
} }

IDCard.java 从对象

package com.dzq.domain;

import java.io.Serializable;

public class IDCard  implements Serializable{
private int id;
private String name;
private Person person; 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 Person getPerson() {
return person;
} public void setPerson(Person person) {
this.person = person;
} }

IDCard.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 package="com.dzq.domain"> <class name="IDCard" table="id_card">
<id name="id" column="id">
<generator class="foreign">
<param name="property">person</param>
</generator>
</id>
<property name="name" column="name" />
<one-to-one name="person" constrained="true"/>
</class> </hibernate-mapping>

Person.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 package="com.dzq.domain"> <class name="Person" table="person">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" />
<one-to-one name="idcard"/>
</class> </hibernate-mapping>

测试代码:

OneToOne.java

package com.dzq.test;

import org.hibernate.Session;
import org.hibernate.Transaction; import com.dzq.domain.IDCard;
import com.dzq.domain.Person;
import com.dzq.utils.HibernateUntils; public class OneToOne {
public static void main(String[] args) {
add();
queryPerson(1);
queryIDcard(1);
} public static Person add(){
Session s=null;
Transaction ts=null;
try {
s=HibernateUntils.getSession();
Person p=new Person();
IDCard idcard=new IDCard();
idcard.setName("0606");
p.setName("ll");
p.setIdcard(idcard);
idcard.setPerson(p);
ts=s.beginTransaction();
s.save(p);
s.save(idcard);
ts.commit();
return p;
} catch (Exception e) {
if(ts!=null)
ts.rollback();
throw new RuntimeException(e);
}finally{
if(s!=null){
s.close();
}
}
} /**
* 查询主对象,用连接表查询
* @param id
* @return
*/
public static Person queryPerson(int id){
Session s=null;
try {
s=HibernateUntils.getSession();
Person p=(Person) s.get(Person.class, id);
System.out.println(p.getIdcard().getName());
return p;
} finally{
if(s!=null){
s.close();
}
}
}
/**
* 查询从对象,查询两次
* @param id
* @return
*/
public static IDCard queryIDcard(int id){
Session s=null;
try {
s=HibernateUntils.getSession();
IDCard idc= (IDCard) s.get(IDCard.class, id);
System.out.println(idc.getPerson().getName());
return idc;
} finally{
if(s!=null){
s.close();
}
}
}
}
2)基于外健的one-to-one,可以描述为多对一,加unique=“true”约束
<one-to-one name=”idCard” property-ref=“person”/>
<!-property-ref用于指定关联类的一个属性,这个属性将会和本外键相对应 -->
<many-to-one name=”person” column=”person_id” unique=”true” not-null=”true”/>
 <!-唯一的多对一,其实就便成了一对一了-->

<?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 package="com.dzq.domain"> <class name="IDCard" table="id_card">
<id name="id" column="id">
<!-- <generator class="foreign">
<param name="property">person</param>
</generator> -->
<generator class="native"/>
</id>
<property name="name" column="name" />
<!-- <one-to-one name="person" constrained="true"/> -->
<many-to-one name="person" column="person_id" unique="true"/>
</class> </hibernate-mapping>
<?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 package="com.dzq.domain"> <class name="Person" table="person">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" />
<!-- <one-to-one name="idcard"/> -->
<one-to-one name="idcard" property-ref="person"/>
</class> </hibernate-mapping>
多对多(teacher - student)
在操作和性能方面都不太理想,所以多对多的映射使用较少,实际使用中最好转换成一对多的对象模型;Hibernate会为我们创建中间关联表,转换成两个一对多。
<set name="teacher" table="teacher_student">
<key column="teacher_id"/>
<many-to-many class="Student" column="student_id"/>
</set>
l

<?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 package="com.dzq.domain"> <class name="Student" table="student">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" />
<set name="teachers" table="teacher_student">
<key column="student_id"/>
<many-to-many class="Teacher" column="teacher_id"/>
</set>
</class> </hibernate-mapping>
<?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 package="com.dzq.domain"> <class name="Teacher" table="teacher">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" />
<set name="students" table="teacher_student">
<key column="teacher_id"/>
<many-to-many class="Student" column="student_id"/>
</set>
</class> </hibernate-mapping>
package com.dzq.test;

import java.util.HashSet;
import java.util.Set; import org.hibernate.Session;
import org.hibernate.Transaction; import com.dzq.domain.Student;
import com.dzq.domain.Teacher;
import com.dzq.utils.HibernateUntils; public class ManyToMany { public static void main(String[] args) {
add();
query(1);
} public static void add(){
Session s=null;
Transaction ts=null;
try {
Set<Teacher> tes=new HashSet<Teacher>();
Set<Student> stus=new HashSet<Student>();
s=HibernateUntils.getSession();
Teacher t1=new Teacher();
t1.setName("gao");
Teacher t2=new Teacher();
t2.setName("gaoji");
tes.add(t1);
tes.add(t2);
Student s1=new Student();
s1.setName("hu");
Student s2=new Student();
s2.setName("xiaohu");
stus.add(s1);
stus.add(s2);
t1.setStudents(stus);
t2.setStudents(stus);
/*s1.setTeachers(tes);
s2.setTeachers(tes);*/ // 会报错,插入重复,要一个就行
ts=s.beginTransaction();
s.save(t1);
s.save(t2);
s.save(s1);
s.save(s2);
ts.commit();
} catch (Exception e) {
if(ts!=null)
ts.rollback();
throw new RuntimeException(e);
}finally{
if(s!=null){
s.close();
}
}
}
/**
* 多对多查询,效率很低,用的比较少,最好使用分页查询,数据量很小才会使用,数据大量是会存在很严重的性能问题
* @param id
*/ public static void query(int id){
Session s=null;
try {
s=HibernateUntils.getSession();
Teacher teacher=(Teacher) s.get(Teacher.class, id);
System.out.println(teacher.getStudents().size());
} finally{
if(s!=null){
s.close();
}
}
} }
组件映射(User-Name)
关联的属性是个复杂类型的持久化类,但不是实体即:数据库中没有表与该属性对应,但该类的属性要之久保存的。
<component name=”name” class=”com.test.hibernate.domain.Name”>
<property name=”initial”/>
<property name=”first”/>
<property name=”last”/>
</component>
当组件的属性不能和表中的字段简单对应的时候可以选择实现:
org.hibernate.usertype. UserType或
org.hibernate.usertype. CompositeUserType

package com.dzq.domain;

public class Name {
private String firstName;
private String lastName; public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} }

只会产生一张表

<?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 package="com.dzq.domain"> <class name="User" table="user">
<id name="id" column="id">
<generator class="native" />
</id>
<!-- <property name="username" column="username" /> -->
<component name="username">
<property name="firstName" column="first_name"/>
<property name="lastName" column="last_name"/>
</component>
<property name="password" column="password" />
<property name="mobile" column="mobile" />
<property name="regdate" column="regdate"/>
</class> </hibernate-mapping>

关联关系的级联操作

package com.dzq.test;

import java.util.HashSet;
import java.util.Set; import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction; import com.dzq.domain.Department;
import com.dzq.domain.Employee;
import com.dzq.utils.HibernateUntils; public class ManyToOne { public static void main(String[] args) {
add();
}
public static void addEmAndDe(){
Employee em=new Employee();
Department depart=new Department();
depart.setName("FBI");
em.setDepart(depart);
em.setName("AK47");
HibernateUntils.add(depart);
HibernateUntils.add(em);
} public static void add(){
Session s=null;
Transaction ts=null;
try { Department dep=new Department();
dep.setName("FBI");
Employee e1=new Employee();
Employee e2=new Employee();
e1.setName("hi");
e1.setDepart(dep);
e2.setName("hello");
e2.setDepart(dep);
Set<Employee> empls=new HashSet<Employee>();
empls.add(e1);
empls.add(e2);
dep.setEmpls(empls);
s=HibernateUntils.getSession();
ts=s.beginTransaction();
//s.save(e1);
//s.save(e2);
s.save(dep);
ts.commit();
} catch (Exception e) {
ts.rollback();
throw new RuntimeException(e);
}finally{
if(s!=null){
s.close();
}
}
} }
<?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 package="com.dzq.domain"> <class name="Department" table="department">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" />
<set name="empls" cascade="save-update">
<key column="depart_id"/>
<one-to-many class="Employee"/>
</set>
<!-- <list name="empls">
<key column="depart_id"/>
<list-index column="order_col"/>
<one-to-many class="Employee"/>
</list> --> <!-- <bag name="empls">
<key column="depart_id"/>
<one-to-many class="Employee"/>
</bag>
--> </class> </hibernate-mapping>
 

20160507-hibernate入门的更多相关文章

  1. 三大框架之hibernate入门

    hibernate入门   1.orm      hibernate是一个经典的开源的orm[数据访问中间件]框架           ORM( Object Relation Mapping)对象关 ...

  2. Hibernate入门案例及增删改查

    一.Hibernate入门案例剖析: ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private I ...

  3. Hibernate入门案例 增删改

    一.Hibernate入门案例剖析: ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private I ...

  4. Hibernate入门6.Hibernate检索方式

    Hibernate入门6.Hibernate检索方式 20131128 代码下载 链接: http://pan.baidu.com/s/1Ccuup 密码: vqlv Hibernate的整体框架已经 ...

  5. Hibernate入门5持久化对象关系和批量处理技术

    Hibernate入门5持久化对象关系和批量处理技术 20131128 代码下载 链接: http://pan.baidu.com/s/1Ccuup 密码: vqlv 前言: 前面学习了Hiberna ...

  6. Hibernate入门4.核心技能

    Hibernate入门4.核心技能 20131128 代码下载 链接: http://pan.baidu.com/s/1Ccuup 密码: vqlv 前言: 前面学习了Hibernate3的基本知识, ...

  7. Hibernate入门3.配置映射文件深入

    Hibernate入门3.配置映射文件深入 2013.11.27 前言: 之前的两节是在Java项目中如何使用hibernate,并且通过一个简单地项目实践,期间有很多的错误,一般都是因为配置包的问题 ...

  8. 简单的Hibernate入门简介

    其实Hibernate本身是个独立的框架,它不需要任何web server或application server的支持.然而,大多数的Hibernate入门介绍都加入了很多非Hibernate的东西, ...

  9. Hibernate入门(1)-第一个Hibernate程序

    Hibernate入门(1)-第一个Hibernate程序 Hibernate是最著名的ORM工具之一,本系列文章主要学习Hibernate的用法,不涉及Hibernate的原理.本文介绍第一个Hib ...

  10. hibernate入门之person表

    下面的hibernate入门person表指的是:根据mysql数据库中的test表和其中的元素-->建立映射表==>进而创建持久化类的顺序来操作了,下面为步骤 1.配置MySQL驱动程序 ...

随机推荐

  1. JDBC 创建连接对象的三种方式 、 properties文件的建立、编辑和信息获取

    创建连接对象的三种方式 //第一种方式 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ ...

  2. SSH权威指南(转载)

    本书是一本介绍通信安全的书籍,如果你想保障你的通信安全,本书能给你一个很好的解决方案.本书从ssh协议介绍起,到具体的开源实现和商业实现.但本书同时介绍开源实现和商业实现,给人感觉比较乱.注意:由于o ...

  3. 配置OpenStack以使用LDAP实现身份管理

    本文展示了如何配置 Keystone,以便使用轻量级目录http://www.aliyun.com/zixun/aggregation/34570.html">访问协议( LDAP)服 ...

  4. Spark生态之Spark BlinkDB

  5. [OC Foundation框架 - 1] 常用结构体

    底层封装是使用了typedef定义的结构体 typedef struct _NSString{ xxx xxx } NSString;   1. NSRange 结构体 #注意结构体不是对象 3种定义 ...

  6. [置顶] 解成电OJ1003真实的谎言的记录

    原题目 Description   N个人做一个游戏,游戏中每个人说了一句话(可能是真的也可能是假的) 第i个人说:“N个人中有至少有ai个,至多有bi个人说的是真话!”(i = 1, 2, 3….. ...

  7. jquery.validate.js 应用示例

    今天发现了jQuery一个很强大的验证表单插件(jquery.validate.js 下载地址:http://bassistance.de/jquery-plugins/jquery-plugin-v ...

  8. DOS/Windows下黑客攻防(一)——神秘黑客大曝光

    一.认识神秘的黑客 谈到网络安全,人们不自觉间就会联想到黑客,人们往往会将他们同破坏网络安全.盗取用户账号.偷窃个人私密信息联系起来.其实黑客也有好坏之分,他们并不全是网络上的捣乱分子,其中也有一部分 ...

  9. java基础理论知识的一些总结

    在学习Java初期,由于我们是刚开始接触Java,我们不仅需要牢牢掌握Java的基础理论知识,来为我们后面对Java更深层次的学习打好基础,而且我们需要养成编程人的思想习惯.来我们一起来探索Java基 ...

  10. MySQL索引使用方法和性能优化

    在自己的一个项目中,数据比较多,搜索也很频繁,这里找到一个建立索引很不错的文章,推荐下. 关于MySQL索引的好处,如果正确合理设计并且使用索引的MySQL是一辆兰博基尼的话,那么没有设计和使用索引的 ...