简体   繁体   中英

Hibernate Parent Child updating

Let me setup the scenario before asking the questions

First off I'm using an older version of Hibernate Hibernate Version:3.6.10.Final

I have a questionnaire / person tables that have a one to one relationship with each other.

Here's my Questionnaire table (Partial of course) and only the relevant part.

@Entity
public class Questionnaire {

...

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "person_id")
private Person person;

...

}

Here's my Person table (Partial of course) and only the relevant part.

@Entity
public class Person  {

...

@OneToOne(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY, optional = false)
@JoinColumn(name="questionnaireInfo_id", unique=true)
private QuestionnaireInfo questionnaireInfo;


....

}

If I update the questionnaire object and save the questionaire entity (not using HQL or any SQL type syntax) will it also update my person table as well and lock that table when it saves? [even if the id of person remains the same as before]

I'm using PostgreSQL 9.5.6 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-11), 64-bit

One to one isn't actually lazy when you declare it with FetchType.LAZY

Read up here: http://justonjava.blogspot.de/2010/09/lazy-one-to-one-and-one-to-many.html

And try it like in the article described:

There are at least three well known solutions for this problem: The simplest one is to fake one-to-many relationship. This will work because lazy loading of collection is much easier then lazy loading of single nullable property but generally this solution is very inconvenient if you use complex JPQL/HQL queries.

The other one is to use build time bytecode instrumentation. For more details please read Hibernate documentation: 19.1.7. Using lazy property fetching. Remember that in this case you have to add @LazyToOne(LazyToOneOption.NO_PROXY) annotation to one-to-one relationship to make it lazy. Setting fetch to LAZY is not enough.

The last solution is to use runtime bytecode instrumentation but it will work only for those who use Hibernate as JPA provider in full-blown JEE environment (in such case setting "hibernate.ejb.use_class_enhancer" to true should do the trick: Entity Manager Configuration) or use Hibernate with Spring configured to do runtime weaving (this might be hard to achieve on some older application servers). In this case @LazyToOne(LazyToOneOption.NO_PROXY) annotation is also required.

Here the problem is discussed further: Making a OneToOne-relation lazy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM