Why Lazy loading not working in one to one association?

非 Y 不嫁゛ 提交于 2019-11-30 17:46:29

问题


@Entity
public class Person {
    @Id
    @GeneratedValue
    private int personId;

    @OneToOne(cascade=CascadeType.ALL, mappedBy="person", fetch=FetchType.LAZY)
    private PersonDetail personDetail;

    //getters and setters
}

@Entity
public class PersonDetail {
    @Id
    @GeneratedValue
    private int personDetailId;

    @OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
    private Person person;

        //getters and setters

    }

when i do

 Person person1=(Person)session.get(Person.class, 1);

i see two queries being fired. one for fetching person data and another for person detail data.

As per my understanding only 1 query should have been fired that is for fetching person data not for person detail data as i have mentioned lazy loading. Why personDetail data is getting fetched along with person data ?


回答1:


Hibernate cannot proxy your own object as it does for Sets / Lists in a @ToMany relation, so Lazy loading does not work.

I think this link could be useful to understand your problem: http://justonjava.blogspot.co.uk/2010/09/lazy-one-to-one-and-one-to-many.html




回答2:


Based on your comment and since the PersonDetail entity contains a foreign key column that references the Person entity, it looks like you only have 1 problem:

Entity relationships include the concept of a relationship owner (in this case PersonDetail), which means that you want to add a @JoinColumn annotation in the PersonDetail entity.

You have already correctly defined the inverse side of the relationship (the entity that is not the owner of the relationship) with the mappedBy attribute that was added to the association annotation (@OneToOne in your case) to make the relationship bi-directional, which means that the associated PersonDetail may be reached from a Person instance.

Given the relationship that is clarified in your comment, you should only have to make 1 change to your code as shown here:

@Entity
public class Person {
    @Id
    @GeneratedValue
    private int personId;

    //Retain the mappedBy attribute here: 
    @OneToOne(cascade=CascadeType.ALL, mappedBy="person",
                fetch=FetchType.LAZY)
    private PersonDetail personDetail;
    //getters and setters...
}

@Entity
public class PersonDetail {
    @Id
    @GeneratedValue
    private int personDetailId;

    @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    //Change: add the @JoinColumn annotation here:
    @JoinColumn(name="PERSON_FK_COLUMN")
    private Person person;
    //getters and setters...
}


来源:https://stackoverflow.com/questions/21499580/why-lazy-loading-not-working-in-one-to-one-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!