- 背景:
一个部门只有一个一把手,这在程序开发中就会设计数据映射应该设置为一对一关联。
在hibernate代码开发中,实现这个业务有两种方案:
1)基于外键映射的1-1关联;
2)基于主键映射的1-1关联。
本篇文章主要是用来学习如何使用外键实现1-1关联关系。
- 新建项目hibernate05
新建java project,引入依赖包,在src下添加hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate_01</property> <!-- <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.c3p0.max_size">500</property>
<property name="hibernate.c3p0.min_size">20</property>
<property name="hibernate.c3p0.max_statements">10</property>
<property name="hibernate.c3p0.timeout">2000</property>
<property name="hibernate.c3p0.idle_test_period">2000</property>
<property name="hibernate.c3p0.acquire_increment">10</property> <mapping resource="com/dx/hibernate005/onetoonebyforigenkey/Deparment.hbm.xml" />
<mapping class="com.dx.hibernate005.onetoonebyforigenkey.Deparment" />
<mapping resource="com/dx/hibernate005/onetoonebyforigenkey/Manager.hbm.xml" />
<mapping class="com.dx.hibernate005.onetoonebyforigenkey.Manager" />
</session-factory>
</hibernate-configuration>
在src下新建包com.dx.hibernate005.onetoonebyforigenkey
在com.dx.hibernate005.onetoonebyforigenkey包下创建
Deparment.java
package com.dx.hibernate005.onetoonebyforigenkey; public class Deparment {
private Integer departId;
private String departName;
private Manager manager; public Deparment() {
super();
} public Deparment(Integer departId, String departName) {
super();
this.departId = departId;
this.departName = departName;
} public Integer getDepartId() {
return departId;
} public void setDepartId(Integer departId) {
this.departId = departId;
} public String getDepartName() {
return departName;
} public void setDepartName(String departName) {
this.departName = departName;
} public Manager getManager() {
return manager;
} public void setManager(Manager manager) {
this.manager = manager;
} }
Deparment.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">
<!-- Generated 2017-6-2 10:54:26 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.dx.hibernate005.onetoonebyforigenkey.Deparment" table="DEPARMENTS">
<id name="departId" type="java.lang.Integer">
<column name="DEPART_ID" />
<generator class="native" />
</id>
<property name="departName" type="java.lang.String">
<column name="DEPART_NAME" />
</property> <!-- 在Deparment中定义一个Many-to-one就可以实现在Deparments表中多一个外键列 -->
<many-to-one name="manager" class="com.dx.hibernate005.onetoonebyforigenkey.Manager" column="MANAGER_ID" unique="true"></many-to-one>
</class>
</hibernate-mapping>
Manager.java
package com.dx.hibernate005.onetoonebyforigenkey; public class Manager {
private Integer managerId;
private String managerName;
private Deparment deparment; public Manager() {
super();
} public Manager(Integer managerId, String managerName) {
super();
this.managerId = managerId;
this.managerName = managerName;
} public Integer getManagerId() {
return managerId;
} public void setManagerId(Integer managerId) {
this.managerId = managerId;
} public String getManagerName() {
return managerName;
} public void setManagerName(String managerName) {
this.managerName = managerName;
} public Deparment getDeparment() {
return deparment;
} public void setDeparment(Deparment deparment) {
this.deparment = deparment;
} }
Deparment.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">
<!-- Generated 2017-6-2 10:54:26 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.dx.hibernate005.onetoonebyforigenkey.Manager" table="MANAGERS">
<id name="managerId" type="java.lang.Integer">
<column name="MANAGER_ID" />
<generator class="native" />
</id>
<property name="managerName" type="java.lang.String">
<column name="MANAGER_NAME" />
</property> <!-- 在对应的数据表中已经有了外键,当前持久化类使用one-to-one进行映射 -->
<one-to-one name="deparment" class="com.dx.hibernate005.onetoonebyforigenkey.Deparment" property-ref="manager"></one-to-one>
</class>
</hibernate-mapping>
TestMain.java测试类,并引入JUnit4所需的依赖包。
package com.dx.hibernate005.onetoonebyforigenkey; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; public class TestMain {
private SessionFactory sessionFactory = null;
private Session session = null;
private Transaction transaction = null; @Before
public void init() {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build();
Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build(); sessionFactory = metadata.getSessionFactoryBuilder().build();
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
} @After
public void destory() {
transaction.commit();
session.close();
sessionFactory.close();
}
}
运行空测试类,初始化sql:
Hibernate: create table DEPARMENTS (
DEPART_ID integer not null auto_increment,
DEPART_NAME varchar(255),
MANAGER_ID integer,
primary key (DEPART_ID)
) engine=InnoDB
Hibernate: create table MANAGERS (
MANAGER_ID integer not null auto_increment,
MANAGER_NAME varchar(255),
primary key (MANAGER_ID)
) engine=InnoDB
Hibernate: alter table DEPARMENTS
drop index UK_j9bdvgylyeboig73ntlfcuyf6
Hibernate: alter table DEPARMENTS
add constraint UK_j9bdvgylyeboig73ntlfcuyf6 unique (MANAGER_ID)
Hibernate: alter table DEPARMENTS
add constraint FKnlmf88ii3maigw7hgc182cqi4
foreign key (MANAGER_ID)
references MANAGERS (MANAGER_ID)
- 测试:
1)测试insert:
@Test
public void testInsert(){
Deparment deparment=new Deparment();
deparment.setDepartName("Depart1"); Manager manager=new Manager();
manager.setManagerName("manager1"); deparment.setManager(manager);
manager.setDeparment(deparment); session.save(manager);
session.save(deparment);
}
测试通过,测试打印sql
Hibernate:
insert
into
MANAGERS
(MANAGER_NAME)
values
(?)
Hibernate:
insert
into
DEPARMENTS
(DEPART_NAME, MANAGER_ID)
values
(?, ?)
2)测试select
@Test
public void testSelect() {
// 1.查询时,采用懒加载。
Deparment deparment = (Deparment) session.get(Deparment.class, 1);
System.out.println(deparment.getDepartName()); // // 2.会出现懒加载异常问题
// session.close();
// Manager manager = deparment.getManager();
// System.out.println(manager.getClass());
// System.out.println(manager.getManagerName());
}
3)测试Select Manager
@Test
public void testSelectManager() {
// 1.查询时,没采用懒加载。
Manager manager = session.get(Manager.class, 1);
System.out.println(manager.getManagerName()); // 2.不会出现懒加载异常问题
session.close();
System.out.println(manager.getDeparment().getDepartName());
}
4)测试修改
@Test
public void testUpdate() {
// // 1) session关闭时,修改执行
// Manager manager = session.get(Manager.class, 1);
// manager.setManagerName("Mgr11111");
// // session.save(manager);
//
// Deparment deparment = session.get(Deparment.class, 1);
// deparment.setDepartName("Depart111111");
// // session.save(deparment); // // 2)通过manager 关联修改deparment
// Manager manager = session.get(Manager.class, 1);
// manager.setManagerName("Mgr222");
// manager.getDeparment().setDepartName("DEPT22"); // 3)通过department关联修改manager
Deparment deparment = session.get(Deparment.class, 1);
deparment.setDepartName("DPT333");
deparment.getManager().setManagerName("Mgr333");
}
5)测试删除
@Test
public void testDelete() {
// 1)在department表中有记录与之关联时,删除失败
// Manager manager = session.get(Manager.class, 1);
// session.delete(manager); // 2)删除成功,只删除了deparment表中的记录,manger表中的记录并没有删除,之后再删除manager就不会出现错误。
Deparment deparment = session.get(Deparment.class, 1);
session.delete(deparment);
}