1 . 集合映射
需求:购物商城,用户有多个地址。
// javabean设计
// javabean设计
public class User {
private int userId;
private String userName;
// 一个用户,对应的多个地址
private Set<String> address;
private List<String> addressList = new ArrayList<String>();
//private String[] addressArray; // 映射方式和list一样 <array name=""></array>
private Map<String,String> addressMap = new HashMap<String, String>(); }
分别用Set 、List 、Map 集合对地址进行保存。
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="User类所在包名">
<class name="User" table="t_user">
<id name="userId" column="id">
<generator class="native"></generator>
</id>
<property name="userName"></property>
<!--
set集合属性的映射
name 指定要映射的set集合的属性
table 集合属性要映射到的表
key 指定集合表(t_address)的外键字段
element 指定集合表的其他字段
type 元素类型,一定要指定
-->
<set name="address" table="t_address">
<key column="uid"></key>
<element column="address" type="string"></element>
</set>
<!--
list集合映射
list-index 指定的是排序列的名称 (因为要保证list集合的有序)
-->
<list name="addressList" table="t_addressList">
<key column="uid"></key>
<list-index column="idx"></list-index>
<element column="address" type="string"></element>
</list>
<!--
map集合的映射
key 指定外键字段
map-key 指定map的key
element 指定map的value
-->
<map name="addressMap" table="t_addressMap">
<key column="uid"></key>
<map-key column="shortName" type="string" ></map-key>
<element column="address" type="string" ></element>
</map>
</class>
</hibernate-mapping>
测试类:
private static SessionFactory sf;
static {
sf = new Configuration()
.configure()
.addClass(User.class) //(测试) 会自动加载映射文件:User.hbm.xml
.buildSessionFactory();
}
// 保存set
@Test
public void testSaveSet() throws Exception {
Session session = sf.openSession();
session.beginTransaction();
//-- 保存
Set<String> addressSet = new HashSet<String>();
addressSet.add("上海");
addressSet.add("成都");
// 用户对象
User user = new User();
user.setUserName("Jack");
user.setAddress(addressSet);
// 保存
session.save(user);
session.getTransaction().commit();
session.close();
}
// 保存list/map
@Test
public void testSaveList() throws Exception {
Session session = sf.openSession();
session.beginTransaction();
User user = new User();
user.setUserName("Tom");
// // 用户对象 -- list
// user.getAddressList().add("上海");
// user.getAddressList().add("成都");
// // 保存
// session.save(user);
// 用户对象 -- Map
user.getAddressMap().put("A0001", "上海");
user.getAddressMap().put("A0002", "成都");
// 保存
session.save(user);
session.getTransaction().commit();
session.close();
}
集合数据的获取
2 . 一对多 多对一映射
需求:
Normal
0
7.8 磅
0
2
false
false
false
EN-US
ZH-CN
X-NONE
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-font-kerning:1.0pt;}
部门与员工
一个部门有多个员工; 【一对多】
多个员工,属于一个部门 【多对一】
数据库设计:
- 数据库:
- t_dept 部门表
- deptId deptName
- 1 开发部
- 2 财务部
- t_employee 员工表
- empId empName salary dept_id 外键引用
- 1 小王 10000 1
- 2 小李 5000 1
- 3 小郑 7000 2
- 4 小高 6000 2
javabean
public class Dept {
private int deptId;
private String deptName;
// 【一对多】 部门对应的多个员工
private Set<Employee> emps = new HashSet<Employee>();
}
public class Employee {
private int empId;
private String empName;
private double salary;
// 【多对一】员工与部门
private Dept dept;
}
映射
Normal
0
7.8 磅
0
2
false
false
false
EN-US
ZH-CN
X-NONE
Dept.hbm.xml
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-font-kerning:1.0pt;}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="类所在包名">
<class name="Dept" table="t_dept">
<id name="deptId">
<generator class="native"></generator>
</id>
<property name="deptName" length="20"></property> <set name="emps"> <!-- table="t_employee" -->
<key column="dept_id"></key>
<one-to-many class="Employee"/>
</set>
</class>
</hibernate-mapping>
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-font-kerning:1.0pt;}
Employee.hbm.xml
员工(Employee )映射关键点:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.itcast.b_one2Many"> <class name="Employee" table="t_employee">
<id name="empId">
<generator class="native"></generator>
</id>
<property name="empName" length="20"></property>
<property name="salary" type="double"></property> <many-to-one name="dept" column="dept_id" class="Dept"></many-to-one> </class>
</hibernate-mapping>
测试:
public class App {
private static SessionFactory sf;
static {
sf = new Configuration()
.configure()
.addClass(Dept.class)
.addClass(Employee.class) // 测试时候使用
.buildSessionFactory();
}
// 保存, 部门方 【一的一方法操作】
@Test
public void save() {
Session session = sf.openSession();
session.beginTransaction();
// 部门对象
Dept dept = new Dept();
dept.setDeptName("应用开发部");
// 员工对象
Employee emp_zs = new Employee();
emp_zs.setEmpName("小王");
Employee emp_ls = new Employee();
emp_ls.setEmpName("小李");
// 关系
dept.getEmps().add(emp_zs);
dept.getEmps().add(emp_ls);
// 保存
session.save(emp_zs);
session.save(emp_ls);
session.save(dept); // 保存部门,部门下所有的员工
session.getTransaction().commit();
session.close();
/*
* 结果
* Hibernate: insert into t_employee (empName, salary, dept_id) values (?, ?, ?)
Hibernate: insert into t_employee (empName, salary, dept_id) values (?, ?, ?)
Hibernate: insert into t_dept (deptName) values (?)
Hibernate: update t_employee set deptId=? where empId=? 维护员工引用的部门的id
Hibernate: update t_employee set deptId=? where empId=?
*/
}
// 【推荐】 保存, 部员方 【多的一方法操作】
@Test
public void save2() {
Session session = sf.openSession();
session.beginTransaction();
// 部门对象
Dept dept = new Dept();
dept.setDeptName("综合部");
// 员工对象
Employee emp_zs = new Employee();
emp_zs.setEmpName("小王");
Employee emp_ls = new Employee();
emp_ls.setEmpName("小李");
// 关系
emp_zs.setDept(dept);
emp_ls.setDept(dept);
// 保存
session.save(dept); // 先保存一的方法
session.save(emp_zs);
session.save(emp_ls);// 再保存多的一方,关系回自动维护(映射配置完)
session.getTransaction().commit();
session.close();
/*
* 结果
* Hibernate: insert into t_dept (deptName) values (?)
Hibernate: insert into t_employee (empName, salary, dept_id) values (?, ?, ?)
Hibernate: insert into t_employee (empName, salary, dept_id) values (?, ?, ?)
少生成2条update sql
*/
} }
总结:
最好 让多的一方来维护 【员工 多的一方 】 可以提高 效率
配置一对多与多对一,这种叫“双向关联”
只配置一对多, 叫“单项一对多”
只配置多对一, 叫“单项多对一”
3 . inverse属性 + cascade级联属性
Inverse属性
,是在维护关联关系的时候起作用的。
表示控制权是否转移。(在一的一方起作用)
cascade 表示级联操作 【可以设置到一的一方或多的一方】
none 不级联操作, 默认值
save-update 级联保存或更新
delete 级联删除
save-update,delete 级联保存、更新、删除
all 同上。级联保存、更新、删除
4 . 多对多映射
需求:
JavaBean
Develper
public class Developer {
private int d_id;
private String d_name;
// 开发人员,参数的多个项目
private Set<Project> projects = new HashSet<Project>();
}
Project
public class Project {
private int prj_id;
private String prj_name;
// 项目下的多个员工
private Set<Developer> developers = new HashSet<Developer>();
}
Project.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="类所在包名">
<class name="Project" table="t_project">
<id name="prj_id">
<generator class="native"></generator>
</id>
<property name="prj_name" length="20"></property>
<!--
多对多映射:
1. 映射的集合属性: “developers”
2. 集合属性,对应的中间表: “t_relation”
3. 外键字段: prjId
4. 外键字段,对应的中间表字段: did
5. 集合属性元素的类型
-->
<set name="developers" table="t_relation" cascade="save-update">
<key column="prjId"></key>
<many-to-many column="did" class="Developer"></many-to-many>
</set>
</class>
</hibernate-mapping>
Developer.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="类所在包名">
<class name="Developer" table="t_developer">
<id name="d_id">
<generator class="native"></generator>
</id>
<property name="d_name" length="20"></property>
<!--
多对多映射配置: 员工方
name 指定映射的集合属性
table 集合属性对应的中间表
key 指定中间表的外键字段(引用当前表t_developer主键的外键字段)
many-to-many
column 指定外键字段对应的项目字段
class 集合元素的类型
-->
<set name="projects" table="t_relation">
<key column="did"></key>
<many-to-many column="prjId" class="Project"></many-to-many>
</set> </class> </hibernate-mapping>
测试:
@Test
public void testSaveSet() throws Exception {
Session session = sf.openSession();
session.beginTransaction();
// 创建项目
Project prj_ds = new Project();
prj_ds.setPrj_name("电商系统");
Project prj_oa = new Project();
prj_oa.setPrj_name("OA系统");
// 创建员工
Developer dev_1 = new Developer();
dev_1.setD_name("小王");
Developer dev_2 = new Developer();
dev_2.setD_name("小郑");
Developer dev_3 = new Developer();
dev_3.setD_name("小高");
// //设置关系
// prj_ds.getDevelopers().add(dev_1);
// prj_ds.getDevelopers().add(dev_2);
// prj_oa.getDevelopers().add(dev_2);
// prj_oa.getDevelopers().add(dev_3);
// // 保存
// session.save(prj_ds);
// session.save(prj_oa);//需要在 Project.hbm.xml 设置级联 cascade="save-update"
//
dev_1.getProjects().add(prj_ds);
dev_2.getProjects().add(prj_ds);
dev_2.getProjects().add(prj_oa);
dev_3.getProjects().add(prj_oa); session.save(dev_1);
session.save(dev_2);
session.save(dev_3);//需要在 Developer.hbm.xml 设置级联 cascade="save-update" session.getTransaction().commit();
session.close();
} }
老师与学员,
一个老师,对应多个学员
一个学员,有多个老师教
父亲/孩子
学生与考试成绩
….
Normal
0
7.8 磅
0
2
false
false
false
EN-US
ZH-CN
X-NONE
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-font-kerning:1.0pt;}
一对多:
<set name="映射的集合属性" table="(可选)集合属性对应的外键表">
<key column="外键表的,外键字段" />
<one-to-many class="集合元素的类型" />
</set>
多对一:
<many-to-one name="对象属性" class="对象类型" column="外键字段字段" />
多对多
<set name="" table="">
<key column="" />
<many-to-many column="" class="">
</set>
5 . 一对一映射
数据库设计:
Normal
0
7.8 磅
0
2
false
false
false
EN-US
ZH-CN
X-NONE
基于外键的映射
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-font-kerning:1.0pt;}
JavaBean
// 身份证
public class IdCard {
// 身份证号(主键)
private String cardNum;// 对象唯一表示(Object Identified, OID)
private String place; // 身份证地址
// 身份证与用户,一对一的关系
private User user;
}
// 用户
public class User {
private int userId;
private String userName;
// 用户与身份证信息, 一对一关系
private IdCard idCard;
}
映射:User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="类所在包名>
<class name="User" table="t_user">
<id name="userId">
<generator class="native"></generator>
</id>
<property name="userName" length="20"></property>
<!--
一对一映射: 没有外键方
-->
<one-to-one name="idCard" class="IdCard"></one-to-one>
</class>
</hibernate-mapping>
IdCard.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="类所在包名">
<class name="IdCard" table="t_IdCard">
<id name="cardNum">
<generator class="assigned"></generator>
</id>
<property name="place" length="20"></property>
<!--
一对一映射,有外键方
unique="true" 给外键字段添加唯一约束
-->
<many-to-one name="user" unique="true" column="user_id" class="User" cascade="save-update"></many-to-one>
</class>
</hibernate-mapping>
测试:
public class app {
private static SessionFactory sf;
static {
sf = new Configuration().configure().addClass(User.class)
.addClass(IdCard.class) // 测试时候使用
.buildSessionFactory();
}
@Test
public void testSaveSet() throws Exception {
Session session = sf.openSession();
session.beginTransaction();
// 用户
User user = new User();
user.setUserName("yif");
// 身份证
IdCard idCard = new IdCard();
idCard.setCardNum("1212xasxsxx");
idCard.setPlace("成都");
// 关系
idCard.setUser(user);
// 保存
session.save(idCard);
session.getTransaction().commit();
session.close();
} }
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri",sans-serif;
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-font-kerning:1.0pt;}
基于主键的映射
修改JavaBean
public class Idcard{
private int user_id;
//身份证号 主键
private String cardNum; //对象唯一表示 (Object Identified,OID)
private String palce; //身份证地址 、
//身份证与用户 ,一对一的关系
private User user;
}
IdCard.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="类所在包名">
<class name="IdCard" table="t_IdCard">
<id name="user_id">
<!--
id 节点指定的是主键映射, 即user_id是主键
主键生成方式: foreign 即把别的表的主键作为当前表的主键;
property (关键字不能修改)指定引用的对象 对象的全名 cn..User、 对象映射 cn.User.hbm.xml、 table(id)
-->
<generator class="foreign">
<param name="property">user</param>
</generator>
</id>
<property name="cardNum" length="20"></property>
<property name="place" length="20"></property>
<!--
一对一映射,有外键方
(基于主键的映射)
constrained="true" 指定在主键上添加外键约束
-->
<one-to-one name="user" class="User" constrained="true" cascade="save-update"></one-to-one>
</class>
</hibernate-mapping>
测试:
@Test
public void testSaveSet1() throws Exception {
Session session = sf.openSession();
session.beginTransaction(); //用户
User user = new User();
user.setUserName("yif");
//身份证
IdCard idCard = new IdCard();
idCard.setCardNum("12312dasxx");
idCard.setPlace("成都");
//关系
idCard.setUser(user);
//保存
session.save(idCard); session.getTransaction().commit();
session.close();
}