项目图片
这里写图片描述配置文件hibernate.cfg.xml
<mapping resource="com/jege/hibernate/one/way/manytoone/User.hbm.xml" />
<mapping resource="com/jege/hibernate/one/way/manytoone/Dept.hbm.xml" />
映射文件
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="com.jege.hibernate.one.way.manytoone">
<class name="User" table="t_user">
<id name="id">
<generator class="native" />
</id>
<property name="username" column="name" />
<!-- class属性:配置一方的全限定类名或者类名,也可以不用配置,Hibernate可以通过反射获取 -->
<!-- column属性:配置外键,对应于一方Dept的主键id,也可以不配置默认用属性名称name=dept作为多方的外键列名 -->
<many-to-one name="dept" class="Dept" column="dept_id" />
</class>
</hibernate-mapping>
Dept.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.jege.hibernate.one.way.manytoone">
<class name="Dept" table="t_dept">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
</class>
</hibernate-mapping>
测试类CrudTest.java
package com.jege.hibernate.one.way.manytoone;
import org.hibernate.Session;
import org.junit.Before;
import org.junit.Test;
import com.jege.hibernate.util.HibernateUtils;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:单向多对一的处理
*/
public class CrudTest {
// 单个保存:一次性保存1个部门,保存3个员工
// 在单向多对一保存的时候需要先保存一方,不是会出现多余的update语句,影响性能
@Before
public void before() throws Exception {
Dept dept = new Dept();
dept.setName("部门1");
// 传入dept的本质是处理数据库user表的dept_id外键
User user1 = new User("员工1", dept);
User user2 = new User("员工2", dept);
Session session = HibernateUtils.INSTANCE.getSession();
session.beginTransaction();
System.out.println("保存之前:" + dept);
session.save(dept);// Hibernate会自动把保存后的主键放到当前对象的id里面
System.out.println("保存之后:" + dept);
session.save(user1);
session.save(user2);
session.getTransaction().commit();
session.close();
}
@Test
public void save() throws Exception {
}
@Test
public void update() throws Exception {
Session session = HibernateUtils.INSTANCE.getSession();
User user = (User) session.get(User.class, 1L);
user.setUsername("jege");
session.beginTransaction();
session.update(user);
session.getTransaction().commit();
session.close();
}
@Test
public void delete() throws Exception {
Session session = HibernateUtils.INSTANCE.getSession();
User user = (User) session.get(User.class, 1L);
session.beginTransaction();
session.delete(user);
session.getTransaction().commit();
session.close();
}
@Test
public void get() throws Exception {
Session session = HibernateUtils.INSTANCE.getSession();
User user = (User) session.get(User.class, 1L);
System.out.println(user);
System.out.println(user.getDept());
}
}
源码地址
https://github.com/je-ge/hibernate
如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。
**您的支持将鼓励我继续创作!谢谢! **
支付宝打赏
网友评论