hibernate双向一对一主键关联映射XML与注解版

栏目: Hibernate · 发布时间: 7年前

内容简介:hibernate双向一对一主键关联映射XML与注解版

双向一对一关联映射原理: 

双向的主键关联其实是单向一对一主键关联的一种特殊情况,只不过要在关联对象的两端的映射文件中都要进行<one-to-one>的配置,另外还要在主映射的主键一端采用foreign外键关联属性。

这里同样使用Person和IdCard来讨论,一个人对应着一个唯一的身份证,而且一个身份证也唯一映射着一个人,所以这就产生了双向的关联关系,Person的主键同样也是IdCard的主键,分别是主键的同时也是外键,这种关联关系成为双向一对一映射,表现到关系模型中可如下图:

hibernate双向一对一主键关联映射XML与注解版

(1)XML版

SQL文件:

CREATE TABLE `person` (
  `id` varchar(255) NOT NULL,
  `pname` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `idcard` (
  `id` varchar(255) NOT NULL,
  `cardnum` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Person类:

package Hibernate_demo1.Demo11.Entity;

public class Person {
	private String id;
	private String pname;
	private IdCard idcards;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public IdCard getIdcards() {
		return idcards;
	}
	public void setIdcards(IdCard idcards) {
		this.idcards = idcards;
	}
	
}

IdCard类:

package Hibernate_demo1.Demo11.Entity;

public class IdCard {
	
	private String id;
	private String cardNum;
	private Person persons;
	
	
	
	public Person getPersons() {
		return persons;
	}
	public void setPersons(Person persons) {
		this.persons = persons;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getCardNum() {
		return cardNum;
	}
	public void setCardNum(String cardNum) {
		this.cardNum = cardNum;
	}
}

IdCard.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">  
<hibernate-mapping>  
    <class name="Hibernate_demo1.Demo11.Entity.IdCard" table="IdCard">  
        <id name="id" type="java.lang.String"> 
            <column name="id"/>
            <generator class="uuid">  
            </generator>  
        </id>  
        <property name="cardNum" column="cardNum"/>
        <!-- 
                        在映射文件中添加外键属性persons,并添加对应的<one-to-one>标签
                        目的是强制约束person类来实现一对一的映射关系,最后在映射中将constrained属性设为true
                        保证强制约束关系。
         -->
        <one-to-one name="persons" constrained="true"></one-to-one>
    </class>  
</hibernate-mapping>

双向一对一唯一外键映射关键映射代码——在IdCard端新加入如下标签映射:

<one-to-one name="person"property-ref="idCard"/>

注意:一对一唯一外键关联双向采用<one-to-one>标签映射,必须指定<one-to-one>标签中的property-ref属性为关系字段的名称。

Person.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">  
<hibernate-mapping>  
    <class name="Hibernate_demo1.Demo11.Entity.Person" table="person">  
        <id name="id">  
            <generator class="uuid">  
            </generator>  
        </id>  
        
        <property name="pname" column="pname"/>  
        
        <!--  
            one-to-one标签指示Hibernate如何加载其关联对象,默认根据主键加载,也就是拿到关系字段值,根据对端的主键来加载关联对象 
         --> 
        <one-to-one name="idcards"></one-to-one> 
    </class>  
</hibernate-mapping>

测试类:

package Hibernate_demo1.Demo11;

import org.hibernate.Session;

import Hibernate_demo1.Demo11.Entity.IdCard;
import Hibernate_demo1.Demo11.Entity.Person;
import Hibernate_demo1.Demo11.Util.HibernateUtils;

public class App 
{
    public static void main( String[] args )
    {
    	Session session = null;
    	try{  
    		  
    	    session = HibernateUtils.getSession();
    	    session.beginTransaction();  
    	      
    	    //创建person对象,并保存  
            Person person=new Person();  
            person.setPname("fendo");  
            session.save(person);  
              
            //创建idCard对象,并保存  
            IdCard idcard=new IdCard();  
            idcard.setCardNum("123456789");  
            idcard.setPersons(person);
            session.save(idcard);  
    	      
    	    session.getTransaction().commit();  
    	}catch(Exception e){  
    	    e.printStackTrace();  
    	    session.getTransaction().rollback();  
    	}finally{  
    	    HibernateUtils.closeSession(session);  
    	}
    }
}

执行结果如下:

Hibernate: 
    insert 
    into
        person
        (pname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        IdCard
        (cardNum, id) 
    values
        (?, ?)

运行结果如下:

Person表

hibernate双向一对一主键关联映射XML与注解版

idcard表

hibernate双向一对一主键关联映射XML与注解版

示例: http://download.csdn.net/detail/u011781521/9834854

(2)注解版

Person类:

package Hibernate_demo1.Demo12.Entity;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="person")
public class Person {
	
	@Id
        @GenericGenerator(name="uuidGenerator", strategy="uuid")
        @GeneratedValue(generator="uuidGenerator")
	private String id;
	
	@Column(name="pname")
	private String pname;
	
        @OneToOne(cascade=CascadeType.ALL)
        @PrimaryKeyJoinColumn
	private IdCard idcards;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public IdCard getIdcards() {
		return idcards;
	}
	public void setIdcards(IdCard idcards) {
		this.idcards = idcards;
	}
	
}

IdCard类:

package Hibernate_demo1.Demo12.Entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="idcard")
public class IdCard {
	
	@Id
        @GenericGenerator(name="uuidGenerator", strategy="uuid")
        @GeneratedValue(generator="uuidGenerator")
	private String id;
	
	@Column(name="cardNum")
	private String cardNum;
	
	@OneToOne
        @PrimaryKeyJoinColumn
	private Person persons;
	
	
	
	public Person getPersons() {
		return persons;
	}
	public void setPersons(Person persons) {
		this.persons = persons;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getCardNum() {
		return cardNum;
	}
	public void setCardNum(String cardNum) {
		this.cardNum = cardNum;
	}
}

测试类:

package Hibernate_demo1.Demo12;

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

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

import Hibernate_demo1.Demo12.Entity.IdCard;
import Hibernate_demo1.Demo12.Entity.Person;



public class App 
{
    public static void main( String[] args )
    {
    	SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();  
    	Session session = sessionFactory.getCurrentSession();  
    	Transaction tx = session.beginTransaction();  
        
    	//创建person对象,并保存  
        Person person=new Person();  
        person.setPname("fendo");  
        session.save(person);  
          
        //创建idCard对象,并保存  
        IdCard idcard=new IdCard();  
        idcard.setCardNum("123456789");  
        idcard.setPersons(person);
        session.save(idcard);  
    	
        tx.commit();
        session.close();
    }
}

执行结果如下:

Hibernate: 
    insert 
    into
        person
        (pname, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        idcard
        (cardNum, id) 
    values
        (?, ?)

示例:  http://download.csdn.net/detail/u011781521/9834858


以上所述就是小编给大家介绍的《hibernate双向一对一主键关联映射XML与注解版》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTML Dog

HTML Dog

Patrick Griffiths / New Riders Press / 2006-11-22 / USD 49.99

For readers who want to design Web pages that load quickly, are easy to update, accessible to all, work on all browsers and can be quickly adapted to different media, this comprehensive guide represen......一起来看看 《HTML Dog》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具