Hibernate关系映射:一对多关联(示例)

30 篇文章 0 订阅
30 篇文章 0 订阅

Hibernate关系映射:一对多关联

set

name属性: 设定待映射的持久化类的属性的

inverse 属性:

  • 在hibernate中通过对 inverse 属性的来决定是由双向关联的哪一方来维护表和表之间的关系。 inverse = false 的为主动方,inverse = true 的为被动方, 由主动方负责维护关联关系。在没有设置 inverse=true 的情况下,父子两边都维护父子关系
  • 在 1-N 关系中,将 N 方设为主控方将有助于性能改善(如果要国家元首记住全国人民的名字,不是太可能,但要让全国人民知道国家元首,就容易的多)
  • 在 1-N 关系中,若将 1 方设为主控方,会额外多出 update 语句。插入数据时无法同时插入外键列,因而无法为外键列添加非空约束.

order-by 属性:

  • 如果设置了该属性, 当 Hibernate 通过 select 语句到数据库中检索集合对象时, 利用 order by 子句进行排序
  • order-by 属性中还可以加入 SQL 函数例如:图3

key

设定与所关联的持久化类对应的表的外键

  • column: 指定关联表的外键名

one-to-many

设定集合属性中所关联的持久化类

  • class: 指定关联的持久化类的类名

案例:

市区表实体类:

package com.liuyongqi.MavenHibernateDemo05.entity;

import java.io.Serializable;
/**
 * 市区表实体类(多端)
 * @author Administrator
 * @data   2018年8月6日
 * @time   下午4:36:55
 */
public class City implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8117542325630083142L;
	private Integer cid ;						//市区编号
	private String cname ;						//市区名称
	private Integer pid ;						//省份编号
	private Province province;					//省份对象
	public City() {
		super();
		// TODO Auto-generated constructor stub
	}
	public City(String cname, Integer pid) {
		super();
		this.cname = cname;
		this.pid = pid;
	}
	public City(Integer cid, String cname, Integer pid) {
		super();
		this.cid = cid;
		this.cname = cname;
		this.pid = pid;
	}
	public Integer getCid() {
		return cid;
	}
	public void setCid(Integer cid) {
		this.cid = cid;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
	public Integer getPid() {
		return pid;
	}
	public void setPid(Integer pid) {
		this.pid = pid;
	}	
	public Province getProvince() {
		return province;
	}
	public void setProvince(Province province) {
		this.province = province;
	}
	@Override
	public String toString() {
		return "City [cid=" + cid + ", cname=" + cname + ", province=" + province + "]";
	}
	
	
	
	
	
	
	
	
}

省份表实体类:

package com.liuyongqi.MavenHibernateDemo05.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
 * 省份表实体类(一端)
 * @author Administrator
 * @data   2018年8月6日
 * @time   下午4:35:15
 */
public class Province implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4463486324531064401L;
	private Integer pid ;							//省份编号
	private String pname ;							//省份名称
	private Set<City> set=new HashSet<City>();		//城市集合
	public Province() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Province(String pname) {
		super();
		this.pname = pname;
	}
	public Province(Integer pid, String pname) {
		super();
		this.pid = pid;
		this.pname = pname;
	}
	public Integer getPid() {
		return pid;
	}
	public void setPid(Integer pid) {
		this.pid = pid;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	
	public Set<City> getSet() {
		return set;
	}
	public void setSet(Set<City> set) {
		this.set = set;
	}
	@Override
	public String toString() {
		return "Province [pid=" + pid + ", pname=" + pname + "]";
	}
	
	
	
	
	
	
	
	
}

City.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 2018-8-6 16:39:06 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.liuyongqi.MavenHibernateDemo05.entity.City" table="city">
        <id name="cid" type="java.lang.Integer">
            <column name="cid" />
            <generator class="native" />
        </id>
        <property name="cname" type="java.lang.String">
            <column name="cname" />
        </property>
       <!--  <property name="pid" type="java.lang.Integer">
            <column name="pid" />
        </property> -->
        <!--  多端--> 
        <many-to-one name="province" class="com.liuyongqi.MavenHibernateDemo05.entity.Province" column="pid" lazy="false" fetch="join"></many-to-one>      
    </class>
</hibernate-mapping>

Province.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 2018-8-6 16:39:06 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.liuyongqi.MavenHibernateDemo05.entity.Province" table="province" >
        <id name="pid" type="java.lang.Integer">
            <column name="pid" />
            <generator class="native" />
        </id>
        <property name="pname" type="java.lang.String">
            <column name="pname" />
        </property>
        <!--  一端-->
        <set name="set" table="city" inverse="true" lazy="false" cascade="all-delete-orphan">
        	<key column="pid"></key>
        	<one-to-many class="com.liuyongqi.MavenHibernateDemo05.entity.City" />
        </set>        
    </class>
</hibernate-mapping>

SessionFactoryUtil工具类:

package com.liuyongqi.MavenHibernateDemo05.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * 提供了开启和关闭session的方法
 * @author Administrator
 * @data   2018年8月1日
 * @time   下午3:32:56
 */
public class SessionFactoryUtil {
	//ThreadLocal为每个线程提供一个单独的存储空间
	private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
	
	//私有化静态变量,静态变量只实例化一次
	private static SessionFactory sessionFactory;
	//实例化一次sessionFactory
	static {
		Configuration configure = new Configuration().configure();
		sessionFactory=configure.buildSessionFactory();
	}
	//私有化构造方法
	private SessionFactoryUtil() {
		
	}
	//打开session的方法
	public static Session openSession() {
		//从ThreadLocal中拿取一个session
		Session session = threadLocal.get();
		if(null==session) {
			//sessionFactory打开一个session
			session=sessionFactory.openSession();
			//把session又放入ThreadLocal中
			threadLocal.set(session);
		}
		return session;
	}
	
	//关闭资源
	public static void closeSession() {
		//从ThreadLocal中拿取一个session
		Session session = threadLocal.get();
		if(null==session) {
			if(session.isOpen()) {
				//关闭session
				session.close();
			}
			threadLocal.set(null);
		}		
	}
	
	public static void main(String[] args) {
		Session session = openSession();
		System.out.println(session);
		System.out.println("ok");
	}
	
}

添加测试代码:

package test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.liuyongqi.MavenHibernateDemo05.entity.City;
import com.liuyongqi.MavenHibernateDemo05.entity.Province;
import com.liuyongqi.MavenHibernateDemo05.util.SessionFactoryUtil;

/**
 * 
 * @author Administrator
 * @data   2018年8月6日
 * @time   下午5:06:11
 */
public class TestSave{
	public static void main(String[] args) {
		Session session = SessionFactoryUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Province province = new Province();
		province.setPname("湖南省1");
		
		City c1 = new City();
		c1.setCname("长沙1");
		City c2 = new City();
		c2.setCname("株洲1");
		City c3 = new City();
		c3.setCname("湘潭1");
		
		//互设
		province.getSet().add(c1);
		province.getSet().add(c2);
		province.getSet().add(c3);
		c1.setProvince(province);
		c2.setProvince(province);
		c3.setProvince(province);
		
		session.save(province);
		
		//结果
		/*Hibernate: 
		    insert 
		    into
		        province
		        (pname) 
		    values
		        (?)
		Hibernate: 
		    insert 
		    into
		        city
		        (cname, pid) 
		    values
		        (?, ?)
		Hibernate: 
		    insert 
		    into
		        city
		        (cname, pid) 
		    values
		        (?, ?)
		Hibernate: 
		    insert 
		    into
		        city
		        (cname, pid) 
		    values
		        (?, ?)
		Hibernate: 
		    update
		        city 
		    set
		        pid=? 
		    where
		        cid=?
		Hibernate: 
		    update
		        city 
		    set
		        pid=? 
		    where
		        cid=?
		Hibernate: 
		    update
		        city 
		    set
		        pid=? 
		    where
		        cid=?*/
		//为啥会出现update语句
		//缺少配置
		//解决方法
		//在一端的set集合那里加上inverse="true"		
		transaction.commit();
		SessionFactoryUtil.closeSession();
	}
}

控制台结果;

Hibernate: 
		    insert 
		    into
		        province
		        (pname) 
		    values
		        (?)
		Hibernate: 
		    insert 
		    into
		        city
		        (cname, pid) 
		    values
		        (?, ?)
		Hibernate: 
		    insert 
		    into
		        city
		        (cname, pid) 
		    values
		        (?, ?)
		Hibernate: 
		    insert 
		    into
		        city
		        (cname, pid) 
		    values
		        (?, ?)

 查询测试代码:

package test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.liuyongqi.MavenHibernateDemo05.entity.City;
import com.liuyongqi.MavenHibernateDemo05.entity.Province;
import com.liuyongqi.MavenHibernateDemo05.util.SessionFactoryUtil;

/**
 * 
 * @author Administrator
 * @data   2018年8月6日
 * @time   下午5:06:11
 */
public class TestSelect{
	public static void main(String[] args) {
		Session session = SessionFactoryUtil.openSession();
		Transaction transaction = session.beginTransaction();
		//默认延时加载
		Province province = session.get(Province.class, 1);		
		transaction.commit();
		SessionFactoryUtil.closeSession();
		System.out.println(province);
		for (City c : province.getSet()) {
			System.out.println(c);
		}
		//关闭延时加载(修改配置)
		//解决方法:在一端和多端都加上lazy="false"
	}
}

控制台结果:

Hibernate: 
    select
        province0_.pid as pid1_1_0_,
        province0_.pname as pname2_1_0_ 
    from
        province province0_ 
    where
        province0_.pid=?
Hibernate: 
    select
        set0_.pid as pid3_0_0_,
        set0_.cid as cid1_0_0_,
        set0_.cid as cid1_0_1_,
        set0_.cname as cname2_0_1_,
        set0_.pid as pid3_0_1_ 
    from
        city set0_ 
    where
        set0_.pid=?
Province [pid=1, pname=湖南省]
City [cid=1, cname=长沙, province=Province [pid=1, pname=湖南省]]
City [cid=3, cname=株洲, province=Province [pid=1, pname=湖南省]]
City [cid=2, cname=湘潭, province=Province [pid=1, pname=湖南省]]

修改测试代码:

package test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.liuyongqi.MavenHibernateDemo05.entity.City;
import com.liuyongqi.MavenHibernateDemo05.entity.Province;
import com.liuyongqi.MavenHibernateDemo05.util.SessionFactoryUtil;

/**
 * 
 * @author Administrator
 * @data   2018年8月6日
 * @time   下午5:06:11
 */
public class TestUpdate{
	public static void main(String[] args) {
		Session session = SessionFactoryUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Province province = session.get(Province.class, 2);
		if(province!=null) {
			province.setPname("湖南省2");
			session.update(province);
		}
		transaction.commit();
		SessionFactoryUtil.closeSession();
	}
}

控制台结果:

Hibernate: 
		    select
		        province0_.pid as pid1_1_0_,
		        province0_.pname as pname2_1_0_ 
		    from
		        province province0_ 
		    where
		        province0_.pid=?
		Hibernate: 
		    select
		        set0_.pid as pid3_0_0_,
		        set0_.cid as cid1_0_0_,
		        set0_.cid as cid1_0_1_,
		        set0_.cname as cname2_0_1_,
		        set0_.pid as pid3_0_1_ 
		    from
		        city set0_ 
		    where
		        set0_.pid=?
		Hibernate: 
		    update
		        province 
		    set
		        pname=? 
		    where
		        pid=?

删除测试代码:

package test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.liuyongqi.MavenHibernateDemo05.entity.City;
import com.liuyongqi.MavenHibernateDemo05.entity.Province;
import com.liuyongqi.MavenHibernateDemo05.util.SessionFactoryUtil;

/**
 * 
 * @author Administrator
 * @data   2018年8月6日
 * @time   下午5:06:11
 */
public class TestDelete{
	public static void main(String[] args) {
		Session session = SessionFactoryUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Province province = session.get(Province.class, 2);
		if(province!=null) {
			session.delete(province);
		}
		transaction.commit();
		SessionFactoryUtil.closeSession();
	}
}

控制台结果

Hibernate: 
		    select
		        province0_.pid as pid1_1_0_,
		        province0_.pname as pname2_1_0_ 
		    from
		        province province0_ 
		    where
		        province0_.pid=?
		Hibernate: 
		    select
		        set0_.pid as pid3_0_0_,
		        set0_.cid as cid1_0_0_,
		        set0_.cid as cid1_0_1_,
		        set0_.cname as cname2_0_1_,
		        set0_.pid as pid3_0_1_ 
		    from
		        city set0_ 
		    where
		        set0_.pid=?
		Hibernate: 
		    delete 
		    from
		        city 
		    where
		        cid=?
		Hibernate: 
		    delete 
		    from
		        city 
		    where
		        cid=?
		Hibernate: 
		    delete 
		    from
		        city 
		    where
		        cid=?
		Hibernate: 
		    delete 
		    from
		        province 
		    where
		        pid=?

今天的测试就到这里了,希望大家看完以后自己测试一下

如果大家想浏览我的下一篇文章,请留言

此文章属于原创,不准转载:https://blog.csdn.net/LYQ2332826438

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

银色亡灵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值