Hibernate中one-to-one的深入学习

原创 2005年04月23日 17:51:00

题记:Hibernate是个好东西,可我感觉这个好东东不好驾御,一个one-to-one就让我花费了很多时间,现在终于有点理解,所以想给大家分享分享我的观点,如有差错,还请各位批评指正!

1.关于one-to-one

    持久化对象之间一对一的关联关系是通过one-to-one元素定义:

<one-to-one
        name="propertyName"                                (1)
        class="ClassName"                                  (2)
        cascade="all|none|save-update|delete"              (3)
        constrained="true|false"                           (4)
        outer-join="true|false|auto"                       (5)
        property-ref="propertyNameFromAssociatedClass"     (6)
        access="field|property|ClassName"                  (7)
        
/>
(1)

name: 属性的名字[POJO中的]。

(2)

class (可选 - 默认是通过反射得到的属性类型):被关联的类的名字。

(3)

cascade(级联) (可选) 表明操作是否从父对象级联到被关联的对象。

(4)

constrained(约束) (可选) 表明该类对应的表对应的数据库表,和被关联的对象所对应的数据库表之间,通过一个外键引用对主键进行约束。这个选项影响save()delete()在级联执行时的先后顺序(也在schema export tool中被使用)。

(5)

outer-join(外连接) (可选 - 默认为 自动): 当设置hibernate.use_outer_join的时候,对这个关联允许外连接抓取。

(6)

property-ref: (可选) 指定关联类的一个属性,这个属性将会和本外键相对应。如果没有指定,会使用对方关联类的主键[POJO中POJO类的实例]。

(7)

access (可选 - 默认是 property): Hibernate用来访问属性的策略。

2.one-to-one分类

主键关联

惟一外键关联

主键关联不需要额外的表字段;两行是通过这种一对一关系相关联的,那么这两行就共享同样的主关键字值。所以如果你希望两个对象通过主键一对一关联,你必须确认它们被赋予同样的标识值!

另一种方式是一个外键和一个惟一关键字对应。

3.one-to-one中惟一外键关联操作

(1)数据库DDL

#
# Table structure for table 'author'
#

CREATE TABLE author (
  author_id char(20) NOT NULL default '',
  person_id char(20) default NULL,
  PRIMARY KEY  (author_id)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;

#
# Table structure for table 'person'
#

CREATE TABLE person (
  person_id char(20) NOT NULL default '',
  name char(20) default NULL,
  PRIMARY KEY  (person_id)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;

(2)映射文件

Author.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
                            "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
                            "
http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration.                   -->
<!-- Created Sat Apr 23 14:28:37 CST 2005                         -->
<hibernate-mapping package="po">

    <class name="Author" table="author">
        <id name="authorId" column="author_id" type="java.lang.String">
            <generator class="assigned"/>
        </id>
       
        <many-to-one
   cascade="all"
   class="po.Person"
   column="person_id"
   name="person"
   not-null="true"
   outer-join="auto"
   unique="true"
   />
       
    </class>
   
</hibernate-mapping>

Person.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
                            "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
                            "
http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration.                   -->
<!-- Created Sat Apr 23 14:28:39 CST 2005                         -->
<hibernate-mapping package="po">

    <class name="Person" table="person">
        <id name="personId" column="person_id" type="java.lang.String">
            <generator class="assigned"/>
        </id>
 
        <property name="name" column="name" type="java.lang.String" />
       
        <one-to-one name="author" class="Author" property-ref="person"/>
       
    </class>
   
</hibernate-mapping>

(2)POJO文件

AbstractAuthor.java

package po;

import java.io.Serializable;

public abstract class AbstractAuthor
    implements Serializable
{
    /** The cached hash code value for this instance.  Settting to 0 triggers re-calculation. */
    private int hashValue = 0;

    /** The composite primary key value. */
    private java.lang.String authorId;

    /** The value of the simple personId property. */
    private java.lang.String personId;

    /**
     * Simple constructor of AbstractAuthor instances.
     */
    public AbstractAuthor()
    {
    }

    /**
     * Constructor of AbstractAuthor instances given a simple primary key.
     * @param authorId
     */
    public AbstractAuthor(java.lang.String authorId)
    {
        this.setAuthorId(authorId);
    }

    /**
     * Return the simple primary key value that identifies this object.
     * @return java.lang.String
     */
    public java.lang.String getAuthorId()
    {
        return authorId;
    }

    /**
     * Set the simple primary key value that identifies this object.
     * @param authorId
     */
    public void setAuthorId(java.lang.String authorId)
    {
        this.hashValue = 0;
        this.authorId = authorId;
    }

    /**
     * Return the value of the person_id column.
     * @return java.lang.String
     */
    public java.lang.String getPersonId()
    {
        return this.personId;
    }

    /**
     * Set the value of the person_id column.
     * @param personId
     */
    public void setPersonId(java.lang.String personId)
    {
        this.personId = personId;
    }

    /**
     * Implementation of the equals comparison on the basis of equality of the primary key values.
     * @param rhs
     * @return boolean
     */
    public boolean equals(Object rhs)
    {
        if (rhs == null)
            return false;
        if (! (rhs instanceof Author))
            return false;
        Author that = (Author) rhs;
        if (this.getAuthorId() != null && that.getAuthorId() != null)
        {
            if (! this.getAuthorId().equals(that.getAuthorId()))
            {
                return false;
            }
        }
        return true;
    }

    /**
     * Implementation of the hashCode method conforming to the Bloch pattern with
     * the exception of array properties (these are very unlikely primary key types).
     * @return int
     */
    public int hashCode()
    {
        if (this.hashValue == 0)
        {
            int result = 17;
            int authorIdValue = this.getAuthorId() == null ? 0 : this.getAuthorId().hashCode();
            result = result * 37 + authorIdValue;
            this.hashValue = result;
        }
        return this.hashValue;
    }
}

Author.java

package po;

import java.io.Serializable;

public class Author
    extends AbstractAuthor
    implements Serializable
{
    private Person person;
 
 /**
     * Simple constructor of Author instances.
     */
    public Author()
    {
    }

    /**
     * Constructor of Author instances given a simple primary key.
     * @param authorId
     */
    public Author(java.lang.String authorId)
    {
        super(authorId);
    }

    /* Add customized code below */
 public void setPerson(Person person){
  this.person=person;
 }
 public Person getPerson(){
  return person;
 }

}

AbstractPerson.java

package po;

import java.io.Serializable;

public abstract class AbstractPerson
    implements Serializable
{
    /** The cached hash code value for this instance.  Settting to 0 triggers re-calculation. */
    private int hashValue = 0;

    /** The composite primary key value. */
    private java.lang.String personId;

    /** The value of the simple name property. */
    private java.lang.String name;

    /**
     * Simple constructor of AbstractPerson instances.
     */
    public AbstractPerson()
    {
    }

    /**
     * Constructor of AbstractPerson instances given a simple primary key.
     * @param personId
     */
    public AbstractPerson(java.lang.String personId)
    {
        this.setPersonId(personId);
    }

    /**
     * Return the simple primary key value that identifies this object.
     * @return java.lang.String
     */
    public java.lang.String getPersonId()
    {
        return personId;
    }

    /**
     * Set the simple primary key value that identifies this object.
     * @param personId
     */
    public void setPersonId(java.lang.String personId)
    {
        this.hashValue = 0;
        this.personId = personId;
    }

    /**
     * Return the value of the name column.
     * @return java.lang.String
     */
    public java.lang.String getName()
    {
        return this.name;
    }

    /**
     * Set the value of the name column.
     * @param name
     */
    public void setName(java.lang.String name)
    {
        this.name = name;
    }

    /**
     * Implementation of the equals comparison on the basis of equality of the primary key values.
     * @param rhs
     * @return boolean
     */
    public boolean equals(Object rhs)
    {
        if (rhs == null)
            return false;
        if (! (rhs instanceof Person))
            return false;
        Person that = (Person) rhs;
        if (this.getPersonId() != null && that.getPersonId() != null)
        {
            if (! this.getPersonId().equals(that.getPersonId()))
            {
                return false;
            }
        }
        return true;
    }

    /**
     * Implementation of the hashCode method conforming to the Bloch pattern with
     * the exception of array properties (these are very unlikely primary key types).
     * @return int
     */
    public int hashCode()
    {
        if (this.hashValue == 0)
        {
            int result = 17;
            int personIdValue = this.getPersonId() == null ? 0 : this.getPersonId().hashCode();
            result = result * 37 + personIdValue;
            this.hashValue = result;
        }
        return this.hashValue;
    }
}

Person.java
package po;

import java.io.Serializable;

public class Person
    extends AbstractPerson
    implements Serializable
{
    private Author author;
 /**
     * Simple constructor of Person instances.
     */
    public Person()
    {
    }

    /**
     * Constructor of Person instances given a simple primary key.
     * @param personId
     */
    public Person(java.lang.String personId)
    {
        super(personId);
    }

    /* Add customized code below */
 public void setAuthor(Author author){
  this.author=author;
 }
 public Author getAuthor(){
  return author;
 }

}

(3)测试文件

TestOO.java

package test;

import po.Author;
import po.Person;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;


public class TestOO {
 
 private Session sesssion=null;

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try {
       Configuration cfg = new Configuration().configure();
       SessionFactory sessions = cfg.buildSessionFactory();
       Session session = sessions.openSession();
       Transaction tx = session.beginTransaction();
      
       Person person = new Person();
         
       person.setPersonId("1");
    person.setName("Blake Stone");
         
       Author author = new Author();

       author.setAuthorId("11");
    author.setPerson(person);

       
   session.save(person);
   session.save(author);

   System.out.print("i will dead if i don't get success!");
     
       tx.commit();
      session.close();
     } catch (Exception e) {
      System.out.println(e);
     }
   }
}

(4)分享喜悦

     运行测试类,数据正常添加进数据库。

(5)深入探讨

     a.由于主键采用assigned方式,必须自己指定ID;

    b.如果只采用session.save(author);将会产生级联错误[ Could not synchronize database state with session             net.sf.hibernate.HibernateException: Batch update row count wrong: 0],看看执行的SQL语句[Hibernate: insert into author (person_id, author_id) values (?, ?)   Hibernate: update person set name=? where person_id=?]很明白是吧,因为person表还是空的,当然执行update操作会失败!虽然解决的方法很简单,可问题值得思考!虽然对person进行了setter方法,可不要忘了他仍旧是VO而不是PO!



版权声明:本文为博主原创文章,未经博主允许不得转载。

hibernate学习5之one-to-many双向关联

一对多双向关联映射:  * 在一一端的集合上使用,在对方表中加入一个外键指向一一端  * 在多一端采用  Xml代码     "-//Hibernate/Hibernate...

hibernate学习之——one-to-many(双向一对多关系)

hibernate学习4之one-to-many单向关联(不推荐)

一对多和多对一的映射策略是一样的,只是站的角度不同. 多对一关联映射:在多的一端加入一个外键指向一的一端,它维护的关系是多指向一 一对多关联映射:在多的一端加入一个外键指向一的一端,它维护的关系是一...

使用注解的Hibernate one-to-many映射

One to many映射关系指的是两个实体间一个实体可以和多个实体有关联关系,但是多的这一端只能和一的这一端的一个实例有关系。它是一个1 到 n的关系。例如在任何的公司员工可以注册多个银行账户,一个...

hibernate单向一对多关联映射(one-to-many)XML与注解版

单向一对多关联映射原理:  hibernate对于一对多的关系的处理,是通过操作classess端,间接操作或者自动操作Student端。比如添加,我直接添加classess端的数据,多个S...

hibernate annotation one-to-many

hibernate一对多,多的一方建立外键,例: CREATE TABLE `person` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `pe...

Hibernate的配置文件的映射many-to-one错误

先看一下错误 虽然,这么多错误挺吓人的,还有SessionFactory为空,但是其实就一个错误文件是这样的Customer.javapackage ch06.pojo;import jav...

Hibernate one-to-many example

1. “One-to-many” example This is a one-to-many relationship table design, a STOCK table has many oc...

hibernate:many to one

这里就拿练手的图书馆系统来说吧… 这个案例用到其中的表 tb_book 图书信息表 tb_bookcase 书架信息表 tb_booktype 图书类型表 ...

Hibernate中one-to-many的基本操作

数据库 drop database if exists stuInfo; create database if not exists stuInfo; use stuInfo; drop ta...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Hibernate中one-to-one的深入学习
举报原因:
原因补充:

(最多只允许输入30个字)