Hibernate一对多之级联保存、删除

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maty_wang/article/details/80508366

本例子用来练习Hibernate一对多的级联保存、删除数据。

涉及到的实体类为Staff(多)和Company(一)

Staff类

package com.maty.entity;

/**
 * @author maty e-mail:512181558@qq.com
 * @version 创建时间:2018年5月30日 上午11:27:11 类说明 员工类
 */
public class Staff
{
	private int sid;
	private String name;
	private String sex;
	private Company company;

	public int getSid()
	{
		return sid;
	}

	public void setSid(int sid)
	{
		this.sid = sid;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public String getSex()
	{
		return sex;
	}

	public void setSex(String sex)
	{
		this.sex = sex;
	}

	public Company getCompany()
	{
		return company;
	}

	public void setCompany(Company company)
	{
		this.company = company;
	}

	@Override
	public String toString()
	{
		return "Staff [sid=" + sid + ", name=" + name + ", sex=" + sex + ", company=" + company + "]";
	}

}

Company类

package com.maty.entity;

import java.util.HashSet;
import java.util.Set;

/**
 * @author maty e-mail:512181558@qq.com
 * @version 创建时间:2018年5月30日 上午11:27:19 类说明
 */
public class Company
{
	private int cid;
	private String name;
	private String nature;
	private Set<Staff> staffs = new HashSet<Staff>();

	public int getCid()
	{
		return cid;
	}

	public void setCid(int cid)
	{
		this.cid = cid;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public String getNature()
	{
		return nature;
	}

	public void setNature(String nature)
	{
		this.nature = nature;
	}

	public Set<Staff> getStaffs()
	{
		return staffs;
	}

	public void setStaffs(Set<Staff> staffs)
	{
		this.staffs = staffs;
	}

}

Staff.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.maty.entity.Staff" table="t_staff">
		<id name="sid" column="sid">
			<generator class="native"></generator>
		</id>
		<property name="name" column="sname"></property>
		<property name="sex" column="ssex"></property>
		<many-to-one name="company" class="com.maty.entity.Company"
			column="cid"></many-to-one>
	</class>
</hibernate-mapping>

Company.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.maty.entity.Company" table="t_company">
		<id name="cid" column="cid">
			<generator class="native"></generator>
		</id>
		<property name="name" column="cname"></property>
		<property name="nature" column="cnature"></property>
		<set name="staffs" cascade="save-update,delete" inverse="true">
			<key column="cid"></key>
			<one-to-many class="com.maty.entity.Staff" />
		</set>
	</class>
</hibernate-mapping>

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- 引入Hibernate的核心配置文件的约束,该约束位于hibernate-core包中的org.hibernate.hibernate-configuration-3.0.dtd -->
<!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.dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<!-- 配置数据库的驱动 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- 配置数据库的url -->
		<property name="hibernate.connection.url">jdbc:mysql://localhost/tx</property>
		<!-- 配置数据库的用户名 -->
		<property name="hibernate.connection.username">root</property>
		<!-- 配置数据库的密码 -->
		<property name="hibernate.connection.password">wangxiaowei</property>

		<!-- 第二步:配置Hibernate本身的设置 -->
		<!-- 是否在console显示sql语句 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 是否对sql语句进行格式化 -->
		<property name="hibernate.format_sql">true</property>
		<!-- 是否自动建表 -->
		<property name="hibernate.hbm2ddl.auto">update</property>

		<!-- 第三步:加载hibernate mapping文件 -->
		<mapping resource="com/maty/entity/Company.hbm.xml" />
		<mapping resource="com/maty/entity/Staff.hbm.xml" />
	</session-factory>
</hibernate-configuration>

测试类

package com.maty.test;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.NativeQuery;
import org.junit.Test;

import com.maty.entity.Company;
import com.maty.entity.Staff;
import com.maty.utils.HibernateUtil;

/**
 * @author maty e-mail:512181558@qq.com
 * @version 创建时间:2018年5月30日 上午11:48:29 类说明 测试类
 */
public class MyTest
{
	// 测试是否能正确创建两个表
	@Test
	public void test()
	{
		HibernateUtil.getSessionFactory();
	}

	// 一对多的级联保存
	@Test
	public void add()
	{
		Transaction transaction = null;
		SessionFactory sessionFactory = null;
		Session session = null;
		try
		{
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			// 编写业务逻辑(级联添加数据)
			Staff staff1 = new Staff();
			staff1.setName("maty");
			staff1.setSex("man");
			Staff staff2 = new Staff();
			staff2.setName("jason");
			staff2.setSex("man");

			Company company = new Company();
			company.setName("npartner");
			company.setNature("台企");

			staff1.setCompany(company);
			staff2.setCompany(company);
			Set<Staff> staffs = company.getStaffs();
			staffs.add(staff1);
			staffs.add(staff2);
			session.save(company);
			// ---------------------------------------------------------------------
			transaction.commit();
			System.out.println("程序正常执行成功");
		} catch (Exception e)
		{
			transaction.rollback();
		} finally
		{
			session.close();
			sessionFactory.close();
		}
	}

	// 一对多的级联delete
	@Test
	public void delete()
	{
		Transaction transaction = null;
		SessionFactory sessionFactory = null;
		Session session = null;
		try
		{
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			// 编写业务逻辑(级联添加数据)

			// 第一步:先要获取对象
			Company company = session.get(Company.class, 1);
			session.delete(company);

			// ---------------------------------------------------------------------
			transaction.commit();
			System.out.println("程序正常执行成功");
		} catch (Exception e)
		{
			transaction.rollback();
		} finally
		{
			session.close();
			sessionFactory.close();
		}
	}

	// 使用sqlquery来查询
	@Test
	public void Query()
	{
		Transaction transaction = null;
		SessionFactory sessionFactory = null;
		Session session = null;
		try
		{
			sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			// 编写业务逻辑(级联添加数据)

			String sql = "select * from t_staff where cid = ?";
			NativeQuery sqlQuery = session.createSQLQuery(sql);
			sqlQuery.addEntity(Staff.class);
			sqlQuery.setParameter(1, "2");
			List<Staff> list = sqlQuery.list();
			for (Staff staff : list)
			{
				System.out.println(staff);
			}

			// ---------------------------------------------------------------------
			transaction.commit();
			System.out.println("程序正常执行成功");
		} catch (Exception e)
		{
			transaction.rollback();
		} finally
		{
			session.close();
			sessionFactory.close();
		}
	}
}


展开阅读全文

没有更多推荐了,返回首页