Spring+hibernate

来源:互联网 发布:win7开机优化 编辑:程序博客网 时间:2024/06/05 11:47
模拟one-to-one的时候出了点问题,看Hibernate文档:

There are two varieties of one-to-one association:

  • primary key associations

  • unique foreign key associations

Primary key associations don't need an extra table column; if two rows are related by the association then the two table rows share the same primary key value. So if you want two objects to be related by a primary key association, you must make sure that they are assigned the same identifier value!

Alternatively, a foreign key with a unique constraint, from Employee to Person, may be expressed as:

<many-to-one name="person" class="Person" column="PERSON_ID" unique="true"/>
有2种,主键相同/用many-to-one.
主键相同的时候不需要额外的column。如果2个表不共享一个主键,那么必须要注意,2个对象的主键必须相同!


另外出了一个问题:
分别保存关联的3个对象,在最后一个报错,大概意思是非法的将一个集合关联到2个session。找了半天,网上有说用merge()代替update()即解决了该问题。经过讨论分析,根本的原因是OpenSessionInViewFilter的singleton设置为false。
文档:
If set to false, each data access operation or transaction will use its own session (like without Open Session in View).

Alternatively, turn this filter into deferred close mode, by specifying "singleSession"="false": It will not use a single session per request then, but rather let each data access operation or transaction use its own session (like without Open Session in View). Each of those sessions will be registered for deferred close, though, actually processed at request completion.

A single session per request allows for most efficient first-level caching, but can cause side effects, for example on saveOrUpdate or if continuing after a rolled-back transaction. The deferred close strategy is as safe as no Open Session in View in that respect, while still allowing for lazy loading in views (but not providing a first-level cache for the entire request).