Home > Net >  How to access the join column (Foreign key) in Spring Data JPA without loading the mapped entity
How to access the join column (Foreign key) in Spring Data JPA without loading the mapped entity

Time:08-31

I have a POST entiry and HeadingSlugEntity.

public class PostEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String postId;
    private String uid;
    private String dateCreated;
    private String dateUpdated;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "headingSlugId", referencedColumnName = "headingSlugId")
    private HeadingSlugEntity headingSlugEntity;
}

I have a 1:1 mapping for HeadingSlugEntity. When I save post entity and headingSlugEntity together, headingSlugId is getting auto-populated. That is working fine. The next time when I fetch the post entity, I need to access the headingSlugId without getting the headingSlugEntity. (At this point of time, I don't need HeadingSlugEntity, I just need its ID.) I just need to get the headingSlugId. How to do it. Since this entity is not having the field headingSlugId, I can't set and get it. If I add a field named headingSlugId inside post entity, I will get hibernate duplicate field error. If I put

insertable = false, updatable = false)

and add field headingSlugId, the headingSlugId will be Null.

What basic stuff I am missing here ?

CodePudding user response:

You can map the foreign key to the entity twice in this case, one for actual ORM and another for getting the FK without actually firing a new query.

public class Answer {
   @Column(name = "headingSlugId", insertable = false, updatable = false)
   private Integer headingSlugId;

   @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
   @JoinColumn(name = "headingSlugId", referencedColumnName = "headingSlugId")
   private HeadingSlugEntity headingSlugEntity;
}
  • Related