Hibernate one-to-one一对一映射

 

hibernate 关系映射 one-to-one主要有三种实现方式
1.通过外键方式实现
以学生和电脑为例(Student-Computer)
建表sql语句:
Java代码 复制代码
  1. CREATE DATABASE `onetoone`   
  2. CHARACTER SET 'utf8';   
  3.   
  4. USE `onetoone`;   
  5.   
  6. DROP TABLE IF EXISTS `student`;   
  7. CREATE TABLE `student` (   
  8.   `id` int(11) NOT NULL auto_increment,   
  9.   `name` varchar(255) NOT NULL,   
  10.   PRIMARY KEY  (`id`)   
  11. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;   
  12.   
  13. DROP TABLE IF EXISTS `computer`;   
  14. CREATE TABLE `computer` (   
  15.   `id` int(11) NOT NULL auto_increment,   
  16.   `name` varchar(255) NOT NULL,   
  17.   `student_id` int(11) ,   
  18.   foreign key (`student_id`) references student(`id`),   
  19.   PRIMARY KEY  (`id`)   
  20. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
CREATE DATABASE `onetoone`
CHARACTER SET 'utf8';

USE `onetoone`;

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `computer`;
CREATE TABLE `computer` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `student_id` int(11) ,
  foreign key (`student_id`) references student(`id`),
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


Student.java:
Java代码 复制代码
  1. package com.domain;   
  2.   
  3.   
  4. public class Student implements java.io.Serializable {   
  5.   
  6.     private Integer id;   
  7.   
  8.     private String name;   
  9.   
  10.     private Computer computer;   
  11.   
  12.     public Student() {   
  13.     }   
  14.   
  15.     public Student(String name) {   
  16.         this.name = name;   
  17.     }   
  18.   
  19.     public Integer getId() {   
  20.         return this.id;   
  21.     }   
  22.   
  23.     public void setId(Integer id) {   
  24.         this.id = id;   
  25.     }   
  26.   
  27.     public String getName() {   
  28.         return this.name;   
  29.     }   
  30.   
  31.     public void setName(String name) {   
  32.         this.name = name;   
  33.     }   
  34.   
  35.     public Computer getComputer() {   
  36.         return computer;   
  37.     }   
  38.   
  39.     public void setComputer(Computer computer) {   
  40.         this.computer = computer;   
  41.     }   
  42.   
  43.        
  44. }  
package com.domain;


public class Student implements java.io.Serializable {

	private Integer id;

	private String name;

	private Computer computer;

	public Student() {
	}

	public Student(String name) {
		this.name = name;
	}

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

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

	public Computer getComputer() {
		return computer;
	}

	public void setComputer(Computer computer) {
		this.computer = computer;
	}

	
}

Computer.java:
Java代码 复制代码
  1. package com.domain;   
  2.   
  3. public class Computer implements java.io.Serializable {   
  4.   
  5.     private Integer id;   
  6.   
  7.     private Student student;   
  8.   
  9.     private String name;   
  10.   
  11.   
  12.     public Computer() {   
  13.     }   
  14.   
  15.   
  16.     public Computer(String name) {   
  17.         this.name = name;   
  18.     }   
  19.   
  20.   
  21.     public Computer(Student student, String name) {   
  22.         this.student = student;   
  23.         this.name = name;   
  24.     }   
  25.   
  26.     public Integer getId() {   
  27.         return this.id;   
  28.     }   
  29.   
  30.     public void setId(Integer id) {   
  31.         this.id = id;   
  32.     }   
  33.   
  34.     public Student getStudent() {   
  35.         return this.student;   
  36.     }   
  37.   
  38.     public void setStudent(Student student) {   
  39.         this.student = student;   
  40.     }   
  41.   
  42.     public String getName() {   
  43.         return this.name;   
  44.     }   
  45.   
  46.     public void setName(String name) {   
  47.         this.name = name;   
  48.     }   
  49.   
  50. }  
package com.domain;

public class Computer implements java.io.Serializable {

	private Integer id;

	private Student student;

	private String name;


	public Computer() {
	}


	public Computer(String name) {
		this.name = name;
	}


	public Computer(Student student, String name) {
		this.student = student;
		this.name = name;
	}

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Student getStudent() {
		return this.student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}

	public String getName() {
		return this.name;
	}

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

}

Student.hbm.xml:
Java代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">   
  4.   
  5. <hibernate-mapping>   
  6.     <class name="com.domain.Student" table="student" catalog="onetoone">   
  7.         <id name="id" type="java.lang.Integer">   
  8.             <column name="id" />   
  9.             <generator class="native" />   
  10.         </id>   
  11.         <property name="name" type="java.lang.String">   
  12.             <column name="name" not-null="true" />   
  13.         </property>   
  14.         <!-- class可以不写,因为根据name的值computer(属性),会通过反射自动找到属于哪个类的 -->   
  15.         <one-to-one cascade="delete,save-update" name="computer" class="com.domain.Computer" property-ref="student"></one-to-one>   
  16.     </class>   
  17. </hibernate-mapping>  
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.domain.Student" table="student" catalog="onetoone">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" not-null="true" />
        </property>
        <!-- class可以不写,因为根据name的值computer(属性),会通过反射自动找到属于哪个类的 -->
        <one-to-one cascade="delete,save-update" name="computer" class="com.domain.Computer" property-ref="student"></one-to-one>
    </class>
</hibernate-mapping>


Computer.hbm.xml:
Java代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">   
  4.   
  5. <hibernate-mapping>   
  6.     <class name="com.domain.Computer" table="computer" catalog="onetoone">   
  7.         <id name="id" type="java.lang.Integer">   
  8.             <column name="id" />   
  9.             <generator class="native" />   
  10.         </id>   
  11.           
  12.         <property name="name" type="java.lang.String">   
  13.             <column name="name" not-null="true" />   
  14.         </property>   
  15.            
  16.          <!-- many开头的是代表该表持有外键 -->   
  17.         <many-to-one  name="student" class="com.domain.Student"  unique="true">   
  18.             <column name="student_id" />   
  19.         </many-to-one>   
  20.     </class>   
  21. </hibernate-mapping>  
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.domain.Computer" table="computer" catalog="onetoone">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="native" />
        </id>
       
        <property name="name" type="java.lang.String">
            <column name="name" not-null="true" />
        </property>
        
         <!-- many开头的是代表该表持有外键 -->
        <many-to-one  name="student" class="com.domain.Student"  unique="true">
            <column name="student_id" />
        </many-to-one>
    </class>
</hibernate-mapping>


测试类:
Java代码 复制代码
  1. package com.domain;   
  2.   
  3. import org.hibernate.Query;   
  4. import org.hibernate.Session;   
  5.   
  6. import com.util.HibernateSessionFactory;   
  7.   
  8. public class Test {   
  9.        
  10.     public static void main(String[] args){   
  11.         Session session = HibernateSessionFactory.getSession();   
  12.            
  13.         //save   
  14.         Student student = new Student();   
  15.         student.setName("student9");   
  16.            
  17.         Computer computer = new Computer();   
  18.         computer.setName("Intel 9");   
  19.            
  20.         //computer.setStudent(student)和student.setComputer(computer);都必须要   
  21.         computer.setStudent(student);   
  22.         student.setComputer(computer);   
  23.            
  24.         session.save(student);   
  25.            
  26.         /**  
  27.          执行的sql:  
  28.          Hibernate: insert into onetoone.student (name) values (?)  
  29.          Hibernate: insert into onetoone.computer (name, student_id) values (?, ?)  
  30.          */  
  31.            
  32. //         
  33.         session.beginTransaction().commit();   
  34.            
  35.         //query   
  36.            
  37. //      String hql = "from Student where name=?";   
  38. //      Query query = session.createQuery(hql);   
  39. //      query.setString(0, "student3");   
  40. //         
  41. //      Student student = (Student)query.uniqueResult();   
  42. //      System.out.println(student.getId() + " : " + student.getComputer().getName());   
  43.            
  44.            
  45.         //delete   
  46. //      Student student = (Student)session.load(Student.class, new Integer(1));   
  47. //      session.delete(student);   
  48. //      session.beginTransaction().commit();   
  49.            
  50.         /**  
  51.          执行的sql为:  
  52.     Hibernate: select student0_.id as id0_1_, student0_.name as name0_1_, computer1_.id as id1_0_, computer1_.name as name1_0_, computer1_.student_id as student3_1_0_ from onetoone.student student0_ left outer join onetoone.computer computer1_ on student0_.id=computer1_.student_id where student0_.id=?  
  53.     Hibernate: delete from onetoone.computer where id=?  
  54.     Hibernate: delete from onetoone.student where id=?  
  55.          */  
  56.            
  57.            
  58.         session.close();   
  59.     }   
  60.   
  61. }  
package com.domain;

import org.hibernate.Query;
import org.hibernate.Session;

import com.util.HibernateSessionFactory;

public class Test {
	
	public static void main(String[] args){
		Session session = HibernateSessionFactory.getSession();
		
		//save
		Student student = new Student();
		student.setName("student9");
		
		Computer computer = new Computer();
		computer.setName("Intel 9");
		
		//computer.setStudent(student)和student.setComputer(computer);都必须要
		computer.setStudent(student);
		student.setComputer(computer);
		
		session.save(student);
		
		/**
		 执行的sql:
		 Hibernate: insert into onetoone.student (name) values (?)
		 Hibernate: insert into onetoone.computer (name, student_id) values (?, ?)
		 */
		
//		
		session.beginTransaction().commit();
		
		//query
		
//		String hql = "from Student where name=?";
//		Query query = session.createQuery(hql);
//		query.setString(0, "student3");
//		
//		Student student = (Student)query.uniqueResult();
//		System.out.println(student.getId() + " : " + student.getComputer().getName());
		
		
		//delete
//		Student student = (Student)session.load(Student.class, new Integer(1));
//		session.delete(student);
//		session.beginTransaction().commit();
		
		/**
		 执行的sql为:
	Hibernate: select student0_.id as id0_1_, student0_.name as name0_1_, computer1_.id as id1_0_, computer1_.name as name1_0_, computer1_.student_id as student3_1_0_ from onetoone.student student0_ left outer join onetoone.computer computer1_ on student0_.id=computer1_.student_id where student0_.id=?
	Hibernate: delete from onetoone.computer where id=?
	Hibernate: delete from onetoone.student where id=?
		 */
		
		
		session.close();
	}

}


2.通过主键方式实现(一个表的主键由另一个表的主键决定),在这里Computer的主键由Student的主键决定。
Student.hbm.xml:
Java代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">   
  4.   
  5. <hibernate-mapping>   
  6.     <class name="com.domain.Student" table="student" catalog="onetoone">   
  7.         <id name="id" type="java.lang.Integer">   
  8.             <column name="id" />   
  9.             <generator class="native" />   
  10.         </id>   
  11.         <property name="name" type="java.lang.String">   
  12.             <column name="name" not-null="true" />   
  13.         </property>   
  14.         <!-- class可以不写,因为根据name的值computer(属性),会通过反射自动找到属于哪个类的    
  15.         <one-to-one cascade="delete,save-update" name="computer" class="com.domain.Computer" property-ref="student"></one-to-one>   
  16.         -->   
  17.         <one-to-one name="computer"/>   
  18.     </class>   
  19. </hibernate-mapping>  
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.domain.Student" table="student" catalog="onetoone">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" not-null="true" />
        </property>
        <!-- class可以不写,因为根据name的值computer(属性),会通过反射自动找到属于哪个类的 
        <one-to-one cascade="delete,save-update" name="computer" class="com.domain.Computer" property-ref="student"></one-to-one>
    	-->
    	<one-to-one name="computer"/>
    </class>
</hibernate-mapping>


Comuter.hbm.xml:
Java代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">   
  4.   
  5. <hibernate-mapping>   
  6.     <class name="com.domain.Computer" table="computer" catalog="onetoone">   
  7.         <id name="id" type="java.lang.Integer">   
  8.             <column name="id" />   
  9.             <!--generator class="native" /-->   
  10.                
  11.             <!--Computer的主键由Student的主键决定,可以看成是外键-->   
  12.             <generator class="foreign">   
  13.                 <param name="property">student</param>   
  14.             </generator>   
  15.         </id>   
  16.           
  17.         <property name="name" type="java.lang.String">   
  18.             <column name="name" not-null="true" />   
  19.         </property>   
  20.            
  21.          <!-- many开头的是代表该表持有外键   
  22.         <many-to-one  name="student" class="com.domain.Student"  unique="true">   
  23.             <column name="student_id" />   
  24.         </many-to-one> -->   
  25.         <one-to-one name="student"/>   
  26.     </class>   
  27. </hibernate-mapping>  
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.domain.Computer" table="computer" catalog="onetoone">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <!--generator class="native" /-->
            
            <!--Computer的主键由Student的主键决定,可以看成是外键-->
            <generator class="foreign">
            	<param name="property">student</param>
            </generator>
        </id>
       
        <property name="name" type="java.lang.String">
            <column name="name" not-null="true" />
        </property>
        
         <!-- many开头的是代表该表持有外键
        <many-to-one  name="student" class="com.domain.Student"  unique="true">
            <column name="student_id" />
        </many-to-one> -->
        <one-to-one name="student"/>
    </class>
</hibernate-mapping>


TestMainKey.java:

Java代码 复制代码
  1. package com.domain;   
  2.   
  3. import org.hibernate.Session;   
  4.   
  5. import com.util.HibernateSessionFactory;   
  6.   
  7. public class TestMainKey {   
  8.   
  9.     public static void main(String[] args){   
  10.         Session session = HibernateSessionFactory.getSession();   
  11.            
  12.         //save   
  13.         Student student = new Student();   
  14.         student.setName("student15");   
  15.            
  16.         Computer computer = new Computer();   
  17.         computer.setName("Intel 15");   
  18.            
  19.            
  20.         computer.setStudent(student);   
  21. //      student.setComputer(computer);   
  22.         //因为save 2个表,所以不需要双向赋值   
  23.         session.save(student);   
  24.         session.save(computer);   
  25.            
  26.         session.beginTransaction().commit();   
  27.         session.close();   
  28.     }   
  29. }  
package com.domain;

import org.hibernate.Session;

import com.util.HibernateSessionFactory;

public class TestMainKey {

	public static void main(String[] args){
		Session session = HibernateSessionFactory.getSession();
		
		//save
		Student student = new Student();
		student.setName("student15");
		
		Computer computer = new Computer();
		computer.setName("Intel 15");
		
		
		computer.setStudent(student);
//		student.setComputer(computer);
		//因为save 2个表,所以不需要双向赋值
		session.save(student);
		session.save(computer);
		
		session.beginTransaction().commit();
		session.close();
	}
}





3.通过关系表实现:
Java代码 复制代码
  1. DROP TABLE IF EXISTS `st`;   
  2. create table stu_com(   
  3.     stu_id int not null,   
  4.     com_id int not null  
  5. )ENGINE=InnoDB DEFAULT CHARSET=utf8;  
DROP TABLE IF EXISTS `st`;
create table stu_com(
	stu_id int not null,
	com_id int not null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

Java代码 复制代码
  1. <!--optional="true"的意思是只有当stu_id 和 com_id 都不为空时才在关系表里插入。这样也会插入   
  2.   
  3. 2遍,所以需要inverse="true"把一方设置为虚的。即不让插入到关系表中-->   
  4. <join table="stu-com" optional="true" inverse="true">   
  5.     <key column="com_id"/>   
  6.     <many-to-one name="student" column="stu_id" unique="true"/>   
  7. </join>  
<!--optional="true"的意思是只有当stu_id 和 com_id 都不为空时才在关系表里插入。这样也会插入

2遍,所以需要inverse="true"把一方设置为虚的。即不让插入到关系表中-->
<join table="stu-com" optional="true" inverse="true">
	<key column="com_id"/>
	<many-to-one name="student" column="stu_id" unique="true"/>
</join>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值