javahibernateone-to-onewildfly-11

hibernate OneToOne NullPointerException


i have this code

private PostsContentsEntity contentsEntity;

@OneToOne( targetEntity = PostsContentsEntity.class)
@JoinColumn(name = "PostId",referencedColumnName = "PostId", insertable = false, updatable = false)
public PostsContentsEntity getContentsEntity() {
    return this.contentsEntity;
}

public void setContentsEntity(PostsContentsEntity contentsEntity) {
    this.contentsEntity = contentsEntity;
}

on database post table

PostId  UserId  PostTime
7   3   2018-02-27 02:52:21
8   3   2018-02-27 02:52:38
9   3   2018-02-27 02:52:57
10  3   2018-02-27 02:53:52
11  3   2018-02-27 02:54:01

post content table

PostContentId   PostId  Content MediaUrl    ContentType
1   7   text post   noMedia 1
2   8   photo post  image/TueFeb27025238MST2018_1519725158056.jpg   2
3   9   video post  video/TueFeb27025257MST2018_1519725177971.mp4   3
4   10  text post   noMedia 1
5   11  photo post  image/TueFeb27025401MST2018_1519725241249.jpg   2

the problem is when the PostId on post table = PostContentId on post content table it's return successfully data
but if it's not equal PostContentId return NullPointerException

i added @JoinColumn(name = "PostId",referencedColumnName = "PostId") to join with PostId not PostContentId but same problem !!


Solution

  • I think that the relation between your entities is not correctly mapped.

    Let my copy this sample code from Oracle Javadoc

    Example 1: One-to-one association that maps a foreign key column

    // On Customer class:
    
    @OneToOne(optional=false)
    @JoinColumn(
        name="CUSTREC_ID", unique=true, nullable=false, updatable=false)
    public CustomerRecord getCustomerRecord() { return customerRecord; }
    
    // On CustomerRecord class:
    
    @OneToOne(optional=false, mappedBy="customerRecord")
    public Customer getCustomer() { return customer; }
    

    As you can see usually the annotation @JoinColumn is placed in the entity that represents the table that got the FOREIGN_KEY. In your case, the foreign key seems to be placed in POST_CONTENT pointing to POST.

    You have to place @JoinColumn in your class PostsContentsEntity. Following the example, PostsEntity should have an object mapped with a property in PostsContentsEntity

    Something like this

    // On PostsContentsEntity class:
    
    @OneToOne(optional=false)
    @JoinColumn(
        name="POST_ID", unique=true, nullable=false, updatable=false)
    public PostsEntity getPostsEntity() { return postsEntity; }
    
    // On PostsEntity class:
    
    @OneToOne(optional=false, mappedBy="postsEntity")
    public PostsContentsEntity getPostsContentsEntity() { return postsContentsEntity; }