Why Lazy loading not working in one to one association?

后端 未结 2 718
陌清茗
陌清茗 2021-01-06 01:06
@Entity
public class Person {
    @Id
    @GeneratedValue
    private int personId;

    @OneToOne(cascade=CascadeType.ALL, mappedBy=\"person\", fetch=FetchType.LAZY         


        
相关标签:
2条回答
  • 2021-01-06 01:39

    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...
    }
    
    0 讨论(0)
  • 2021-01-06 01:41

    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

    0 讨论(0)
提交回复
热议问题