休眠 OneToOne NullPointerException

hibernate OneToOne NullPointerException

我有这个代码

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;
}

在数据库上 posttable

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内容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

问题是 当 post table 上的 PostId = post content table 上的 PostContentId 它是 return 成功数据
但如果它不等于 PostContentId return NullPointerException

我添加了 @JoinColumn(name = "PostId",referencedColumnName = "PostId") 加入 PostId 而不是 PostContentId 但同样的问题!!

我认为您的实体之间的关系映射不正确。

让我从 Oracle Javadoc

复制此示例代码

示例 1:One-to-one 映射外键列的关联

// 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; }

正如您通常看到的那样,注释 @JoinColumn 放置在表示获得 FOREIGN_KEY 的 table 的实体中。在你的例子中,外键似乎放在 POST_CONTENT 指向 POST。

您必须将 @JoinColumn 放在 class PostsContentsEntity 中。 按照示例,PostsEntity 应该有一个对象映射到 PostsContentsEntity

中的 属性

像这样

// 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; }