Spring+hibernate

模擬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).










發佈了60 篇原創文章 · 獲贊 1 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章