分享
 
 
 

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

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

题记: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!

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有