当数据库表结构是多对多关系时,对应的实体类和相应的配置文件也需要是多对多的,多对多关系分为单向和多向,
一、单向
新建java项目,结构为:
需要的jar包及如何从hibernate官网获取jar包,请参见《Hibernate环境搭建和配置》
实体类Function代码:
package com.robert.pojo;
public class Function {
private int id ;
private String name ;
private String code ;
private String url ;
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 getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Function.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="com.robert.pojo">
<class name="Function">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="code"></property>
<property name="url"></property>
</class>
</hibernate-mapping>
实体类Role代码:
package com.robert.pojo;
import java.util.HashSet;
import java.util.Set;
public class Role {
private int id ;
private String name ;
private Set<Function> functions = new HashSet<Function>() ;
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<Function> getFunctions() {
return functions;
}
public void setFunctions(Set<Function> functions) {
this.functions = functions;
}
}
Role.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="com.robert.pojo">
<class name="Role">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<!-- table:连接表表名;
key中的column:在Role角度出发,连接表的主键key;
many-to-many中的column:因为是多对多关系,所以用many-to-many,column是连接表中多对多列的列名,这个列名数据来自Function类
cascade:设置为all,是为了保存数据时,能够将相关联的数据都存入数据库表中
-->
<set name="functions" table="Role_Function" cascade="all">
<key column="role_id" />
<many-to-many column="function_id" class="Function" />
</set>
</class>
</hibernate-mapping>
关于连接表的配置信息,在文档中也是有的,如图:
hibernate.cfg.xml代码:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 配置数据库连接信息 -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">jdbc:mysql:///hibernate4</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 数据库方言 -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- 是否打印sql语句 -->
<property name="show_sql">true</property>
<!-- 格式化sql语句 -->
<property name="format_sql">true</property>
<!-- 数据库更新方式:
1、create:每次更新都先把原有数据库表删除,然后创建该表;
2、create-drop:使用create-drop时,在显示关闭SessionFacroty时(sessionFactory.close()),将drop掉数据库Schema(表)
3、validate:检测;
4、update(常用):如果表不存在则创建,如果存在就不创建
-->
<property name="hbm2ddl.auto">update</property>
<!-- 加载Score实体类对应的配置文件 -->
<mapping resource="com/robert/pojo/Function.hbm.xml" />
<mapping resource="com/robert/pojo/Role.hbm.xml" />
</session-factory>
</hibernate-configuration>
HIbernateUtil代码:
package com.robert.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
/**
* hibernate工具类
*/
public class HibernateUtil {
private static Configuration cfg = null;
private static SessionFactory factory = null;
private static Session session = null ;
static {
init();
}
/**
* 初始化获得Configuration和SessionFacroty对象
*/
public static void init() {
cfg = new Configuration().configure();
factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build());
}
/**
* 获得Session对象
* @return
*/
public static Session getSession() {
if (factory != null){
return session = factory.openSession();
}
init();
return session = factory.openSession();
}
/**
* 关闭Session
*/
public static void closeSession() {
if(session!=null && session.isOpen())
session.close();
}
}
HibernateTest中testCreateDB代码:
/**
* 根据*.hbm.xml文件对应的生成数据库表
*/
@Test
public void testCreateDB() {
Configuration cfg = new Configuration().configure();
SchemaExport se = new SchemaExport(cfg);
// 第一个参数:是否生成ddl脚本
// 第二个参数:是否执行到数据库中
se.create(true, true);
}
运行testCreateDB,创建数据库表
控制台打印的sql语句:
alter table Role_Function
drop
foreign key FK_ffk1sq7hplj96dsmj3vsxlfwx
alter table Role_Function
drop
foreign key FK_eogfmuh5hen05bqkg8sufs2pa
drop table if exists Function
drop table if exists Role
drop table if exists Role_Function
create table Function (
id integer not null auto_increment,
name varchar(255),
code varchar(255),
url varchar(255),
primary key (id)
)
create table Role (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
create table Role_Function (
role_id integer not null,
function_id integer not null,
primary key (role_id, function_id)
)
alter table Role_Function
add constraint FK_ffk1sq7hplj96dsmj3vsxlfwx
foreign key (function_id)
references Function (id)
alter table Role_Function
add constraint FK_eogfmuh5hen05bqkg8sufs2pa
foreign key (role_id)
references Role (id)
生成的数据库表如图:
testSave()方法代码如下:
/**
* 保存数据
*
* @throws HibernateException
* @throws SerialException
* @throws SQLException
* @throws IOException
*/
@Test
public void testSave() throws HibernateException, SerialException,
SQLException, IOException {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSession();
tx = session.beginTransaction();
Function function1 = new Function("用户管理", "user_mag", "userAction") ;
Function function2 = new Function("角色管理", "role_mag", "roleAction") ;
Function function3 = new Function("系统管理", "sys_mag", "sysAction") ;
Function function4 = new Function("权限管理", "prev_mag", "prevAction") ;
Role role = new Role() ;
role.setName("admin") ;
role.getFunctions().add(function1) ;
role.getFunctions().add(function2) ;
role.getFunctions().add(function3) ;
role.getFunctions().add(function4) ;
Role role2 = new Role() ;
role2.setName("vip") ;
role2.getFunctions().add(function1) ;
role2.getFunctions().add(function2) ;
session.save(role) ;
session.save(role2) ;
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
throw e;
} finally {
HibernateUtil.closeSession();
}
}
使用Junit4运行,控制台打印sql语句如下:
Hibernate:
insert
into
Role
(name)
values
(?)
Hibernate:
insert
into
Function
(name, code, url)
values
(?, ?, ?)
Hibernate:
insert
into
Function
(name, code, url)
values
(?, ?, ?)
Hibernate:
insert
into
Function
(name, code, url)
values
(?, ?, ?)
Hibernate:
insert
into
Function
(name, code, url)
values
(?, ?, ?)
Hibernate:
insert
into
Role
(name)
values
(?)
Hibernate:
insert
into
Role_Function
(role_id, function_id)
values
(?, ?)
Hibernate:
insert
into
Role_Function
(role_id, function_id)
values
(?, ?)
Hibernate:
insert
into
Role_Function
(role_id, function_id)
values
(?, ?)
Hibernate:
insert
into
Role_Function
(role_id, function_id)
values
(?, ?)
Hibernate:
insert
into
Role_Function
(role_id, function_id)
values
(?, ?)
Hibernate:
insert
into
Role_Function
(role_id, function_id)
values
(?, ?)
数据库表中的数据如:
==============================================================
二、多向
项目结构以及大部分代码都和上面单向的项目一样,下面只列举出不同的代码
Role实体类新增加了关联Function代码,如下:
package com.robert.pojo;
import java.util.HashSet;
import java.util.Set;
public class Role {
private int id ;
private String name ;
private Set<Function> functions = new HashSet<Function>() ;//关联function
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<Function> getFunctions() {
return functions;
}
public void setFunctions(Set<Function> functions) {
this.functions = functions;
}
}
Role.hbm.xml代码增加了function的多对多的配置,代码如下:
<?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="com.robert.pojo">
<class name="Role">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<!-- table:连接表表名;
key中的column:在Role角度出发,连接表的主键key;
many-to-many中的column:因为是多对多关系,所以用many-to-many,column是连接表中多对多列的列名,这个列名数据来自Function类
cascade:设置为save-update:保存和更新多的一端的数据时,一的一端的数据,可以一起保存和更新 ;
-->
<set name="functions" table="Role_Function" cascade="save-update">
<key column="role_id" />
<many-to-many column="function_id" class="Function" />
</set>
</class>
</hibernate-mapping>
注意:cascade必须是save-update才可以,
all时会报错,delete时会将function中的数据也删除。
运行testCreateDB,生成数据库表
运行testSave()方法,保存数据
都和上线的单向一样
写一个删除方法,删除role对象时,查看关联的表中对应的数据,是否会被删除,
testDelete()方法如下:
/**
* 删除方法
* @throws HibernateException
* @throws SerialException
* @throws SQLException
* @throws IOException
*/
@Test
public void testDelete() throws HibernateException, SerialException,
SQLException, IOException {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSession();
tx = session.beginTransaction();
Role role = (Role) session.get(Role.class, 1) ;
System.out.println("--------------------------------------");
session.delete(role) ;
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
throw e;
} finally {
HibernateUtil.closeSession();
}
}
运行后,控制台打印的sql语句如下:
Hibernate:
select
role0_.id as id1_1_0_,
role0_.name as name2_1_0_
from
Role role0_
where
role0_.id=?
--------------------------------------
Hibernate:
delete
from
Role_Function
where
role_id=?
Hibernate:
delete
from
Role
where
id=?