hibernate基于外键的一对一映射--单向和双向

hibernate基于外键的一对一映射和单向的多对一映射,很相似,不同的地方就是,在单向多对一映射中的实体类多的一端配置unique=“true”,就变为了外键的一对一映射。

基于外键的一对一映射可以分为两种情况:

一种是:单向;

一种是:双向;


下面先说单向

具体如下:

新建一个java项目,名称为:13hibernate_single_one_to_one_foreign

项目结构如图:



需要的jar包以及如何从hibernate官网获得,可以参见《Hibernate环境搭建和配置


实体类IdCard代码:

package com.robert.pojo;

public class IdCard {

	private int id ;
	private String code ;//身份证号
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
}


IdCard.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="IdCard">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="code"></property>
	</class>
</hibernate-mapping>




实体类Person代码:

package com.robert.pojo;

public class Person {

	private int id ;
	private String name ;//姓名
	private int age ;//年龄
	private IdCard idCard ;//身份证实体类
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public IdCard getIdCard() {
		return idCard;
	}
	public void setIdCard(IdCard idCard) {
		this.idCard = idCard;
	}
	
}

Person.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="Person">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="name"></property>
		<property name="age"></property>
		<!-- 当unique="true",可以设置一对一的关系 -->
		<many-to-one name="idCard" class="IdCard" column="idcard_id"
			foreign-key="fk_idcard" not-null="true" unique="true" cascade="save-update" />

	</class>
</hibernate-mapping>

HibernateUtil封装的操作session的代码,请参见《 Hibernate联合主键》中的HibernateUtil类代码


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/IdCard.hbm.xml" />
	<mapping resource="com/robert/pojo/Person.hbm.xml" />

</session-factory>
</hibernate-configuration>


测试类HibernateTest代码:

package com.robert.test;

import java.io.IOException;
import java.sql.SQLException;

import javax.sql.rowset.serial.SerialException;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

import com.robert.pojo.IdCard;
import com.robert.pojo.Person;
import com.robert.util.HibernateUtil;

public class HibernateTest {

	/**
	 * 根据*.hbm.xml文件对应的生成数据库表
	 */
	@Test
	public void testCreateDB() {
		Configuration cfg = new Configuration().configure();
		SchemaExport se = new SchemaExport(cfg);
		// 第一个参数:是否生成ddl脚本
		// 第二个参数:是否执行到数据库中
		se.create(true, true);
	}

	/**
	 * 保存数据
	 * 
	 * @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();

			IdCard idCard = new IdCard() ;
			idCard.setCode("1525271000000000000") ;
			
			Person person = new Person() ;
			person.setAge(23) ;
			person.setName("张三") ;
			person.setIdCard(idCard) ;

			session.save(person) ;
			
			IdCard idCard2 = new IdCard() ;
			idCard2.setCode("11011010000000000") ;
			
			Person person2 = new Person() ;
			person2.setAge(24) ;
			person2.setName("李四") ;
			person2.setIdCard(idCard2) ;
			
			session.save(person2);
			

			tx.commit();

		} catch (HibernateException e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
			throw e;
		} finally {
			HibernateUtil.closeSession();
		}
	}


}




首先使用Junit4执行testCreateDB类,根据实体类重新生成数据库表

sql语句如下:

    alter table Person 
        drop 
        foreign key fk_idcard

    drop table if exists IdCard

    drop table if exists Person

    create table IdCard (
        id integer not null auto_increment,
        code varchar(255),
        primary key (id)
    )

    create table Person (
        id integer not null auto_increment,
        name varchar(255),
        age integer,
        idcard_id integer not null,
        primary key (id)
    )

    alter table Person 
        add constraint UK_cbcosmln3841mbhco46ibil26 unique (idcard_id)

    alter table Person 
        add constraint fk_idcard 
        foreign key (idcard_id) 
        references IdCard (id)


执行testSave()方法,控制台console打印的sql语句如下:

Hibernate: 
    insert 
    into
        IdCard
        (code) 
    values
        (?)
Hibernate: 
    insert 
    into
        Person
        (name, age, idcard_id) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        IdCard
        (code) 
    values
        (?)
Hibernate: 
    insert 
    into
        Person
        (name, age, idcard_id) 
    values
        (?, ?, ?)

由打印的sql语句,可见保存数据时,当往person表中添加person的数据时,发现有关联的IdCard外键,所以要先添加它关联的IdCard数据,然后在添加person数据,然后添加person2时,同理。


数据库表数据如图:



下面测试一下unique是否起作用,

修改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();

			IdCard idCard = new IdCard() ;
			idCard.setCode("1525271000000000000") ;
			
			Person person = new Person() ;
			person.setAge(23) ;
			person.setName("张三") ;
			person.setIdCard(idCard) ;

			session.save(person) ;
			
			IdCard idCard2 = new IdCard() ;
			idCard2.setCode("11011010000000000") ;
			
			Person person2 = new Person() ;
			person2.setAge(24) ;
			person2.setName("李四") ;
			person2.setIdCard(idCard2) ;
			
			session.save(person2);
			
			Person person3 = new Person() ;
			person3.setAge(25) ;
			person3.setName("王五") ;
			person3.setIdCard(idCard2) ;//依然使用idCard2身份信息
			
			session.save(person3) ;
			

			tx.commit();

		} catch (HibernateException e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
			throw e;
		} finally {
			HibernateUtil.closeSession();
		}
	}

运行testCreateDB,重新生成数据库表


运行testSave()方法




报错了,说明unique起作用了


========================================================================

再说说双向的

新建一个java项目,名为:14hibernate_double_one_to_one_foreign


项目结构如下:



其他的大部分和上面单向的是一样的,我只把不一样的列出来


IdCard实体类代码:

package com.robert.pojo;

public class IdCard {

	private int id ;
	private String code ;//身份证号
	private Person person ;//公民
	
	public Person getPerson() {
		return person;
	}
	public void setPerson(Person person) {
		this.person = person;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
}



IdCard.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="IdCard">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="code"></property>
		<one-to-one name="person" property-ref="idCard"></one-to-one>
	</class>
</hibernate-mapping>

其中property-ref对应关系如图:



使用Junit4执行testCreateDB,重新生成数据库表

执行testSave()执行保存方法,验证已成功,

下面说说获取方法

testGet()代码:

	/**
	 * 获取数据
	 * @throws HibernateException
	 * @throws SerialException
	 * @throws SQLException
	 * @throws IOException
	 */
	@Test
	public void testGet() throws HibernateException, SerialException,
			SQLException, IOException {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();

			Person person = (Person)session.get(Person.class, 1) ;
			System.out.println("pseron_name="+person.getName()+"----Idcard="+person.getIdCard().getCode());
			
			System.out.println("==================================");
			
			IdCard idCard = (IdCard)session.get(IdCard.class, 2) ;
			System.out.println("idcard="+idCard.getCode()+"----person_name="+idCard.getPerson().getName());

			tx.commit();

		} catch (HibernateException e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
			throw e;
		} finally {
			HibernateUtil.closeSession();
		}
	}

执行以后,控制台打印数据如下:

Hibernate: 
    select
        person0_.id as id1_1_0_,
        person0_.name as name2_1_0_,
        person0_.age as age3_1_0_,
        person0_.idcard_id as idcard_i4_1_0_ 
    from
        Person person0_ 
    where
        person0_.id=?
Hibernate: 
    select
        idcard0_.id as id1_0_0_,
        idcard0_.code as code2_0_0_,
        person1_.id as id1_1_1_,
        person1_.name as name2_1_1_,
        person1_.age as age3_1_1_,
        person1_.idcard_id as idcard_i4_1_1_ 
    from
        IdCard idcard0_ 
    left outer join
        Person person1_ 
            on idcard0_.id=person1_.idcard_id 
    where
        idcard0_.id=?
Hibernate: 
    select
        person0_.id as id1_1_0_,
        person0_.name as name2_1_0_,
        person0_.age as age3_1_0_,
        person0_.idcard_id as idcard_i4_1_0_ 
    from
        Person person0_ 
    where
        person0_.idcard_id=?
pseron_name=张三----Idcard=1525271000000000000
==================================
Hibernate: 
    select
        idcard0_.id as id1_0_0_,
        idcard0_.code as code2_0_0_,
        person1_.id as id1_1_1_,
        person1_.name as name2_1_1_,
        person1_.age as age3_1_1_,
        person1_.idcard_id as idcard_i4_1_1_ 
    from
        IdCard idcard0_ 
    left outer join
        Person person1_ 
            on idcard0_.id=person1_.idcard_id 
    where
        idcard0_.id=?
idcard=11011010000000000----person_name=李四

解释:

等于号(=======)上面是从Person端获取person和idcard信息,一共打印了三条sql语句,且有重复;

等于号(=======)下面是从IdCard端获取perosn和idcard信息,只有一个sql语句。

由此可见,从idCard端效率会高一点









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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值