How can I make a JPA OneToOne relation lazy

前端 未结 10 1830
暖寄归人
暖寄归人 2020-11-22 03:34

In this application we are developing, we noticed that a view was particularly slow. I profiled the view and noticed that there was one query executed by hibernate which too

10条回答
  •  迷失自我
    2020-11-22 04:28

    As I explained in this article, unless you are using Bytecode Enhancement, you cannot fetch lazily the parent-side @OneToOne association.

    However, most often, you don't even need the parent-side association if you use @MapsId on the client side:

    @Entity(name = "PostDetails")
    @Table(name = "post_details")
    public class PostDetails {
    
        @Id
        private Long id;
    
        @Column(name = "created_on")
        private Date createdOn;
    
        @Column(name = "created_by")
        private String createdBy;
    
        @OneToOne(fetch = FetchType.LAZY)
        @MapsId
        private Post post;
    
        public PostDetails() {}
    
        public PostDetails(String createdBy) {
            createdOn = new Date();
            this.createdBy = createdBy;
        }
    
        //Getters and setters omitted for brevity
    }
    

    With @MapsId, the id property in the child table serves as both Primary Key and Foreign Key to the parent table Primary Key.

    So, if you have a reference to the parent Post entity, you can easily fetch the child entity using the parent entity identifier:

    PostDetails details = entityManager.find(
        PostDetails.class,
        post.getId()
    );
    

    This way, you won't have N+1 query issues that could be caused by the mappedBy @OneToOne association on the parent side.

提交回复
热议问题