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. "1.0" encoding="utf-8"?>   
  2. 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" type="java.lang.Integer">   
  8.             "id" />   
  9.             class="native" />   
  10.            
  11.         "name" type="java.lang.String">   
  12.             "name" not-null="true" />   
  13.            
  14.            
  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>  

hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    
        
            
            
        
        
            
        
        
        <one-to-one cascade="delete,save-update" name="computer" class="com.domain.Computer" property-ref="student">one-to-one>
    
hibernate-mapping>


Computer.hbm.xml:
Java代码
  1. "1.0" encoding="utf-8"?>   
  2. 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" type="java.lang.Integer">   
  8.             "id" />   
  9.             class="native" />   
  10.            
  11.           
  12.         "name" type="java.lang.String">   
  13.             "name" not-null="true" />   
  14.            
  15.            
  16.             
  17.         "student" class="com.domain.Student"  unique="true">   
  18.             "student_id" />   
  19.            
  20.     class>   
  21. hibernate-mapping>  

hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    
        
            
            
        
       
        
            
        
        
         
        
            
        
    
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. "1.0" encoding="utf-8"?>   
  2. 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" type="java.lang.Integer">   
  8.             "id" />   
  9.             class="native" />   
  10.            
  11.         "name" type="java.lang.String">   
  12.             "name" not-null="true" />   
  13.            
  14.            
  15.         <one-to-one name="computer"/>   
  16.     class>   
  17. hibernate-mapping>  

hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    
        
            
            
        
        
            
        
        
    	<one-to-one name="computer"/>
    
hibernate-mapping>


Comuter.hbm.xml:
Java代码
  1. "1.0" encoding="utf-8"?>   
  2. 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" type="java.lang.Integer">   
  8.             "id" />   
  9.                
  10.                
  11.                
  12.             class="foreign">   
  13.                 "property">student   
  14.                
  15.            
  16.           
  17.         "name" type="java.lang.String">   
  18.             "name" not-null="true" />   
  19.            
  20.            
  21.             
  22.         <one-to-one name="student"/>   
  23.     class>   
  24. hibernate-mapping>  

hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    
        
            
            
            
            
            
            	student
            
        
       
        
            
        
        
         
        <one-to-one name="student"/>
    
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.   
  2. "stu-com" optional="true" inverse="true">   
  3.     "com_id"/>   
  4.     "student" column="stu_id" unique="true"/>   
  5.   


	
	

你可能感兴趣的:(持久层)