现在的位置: 首页 > 综合 > 正文

Hibernate one-to-one一对一映射

2018年08月10日 ⁄ 综合 ⁄ 共 15302字 ⁄ 字号 评论关闭

 

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;  

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. }  

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. }  

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>  

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>  

测试类:

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. }  

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>  

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>  

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. }  

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;  

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>  

抱歉!评论已关闭.