0

我有这个代码

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

在数据库发布表上

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

发布内容表

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

问题是当PostIdon post table= PostContentIdonpost content table它成功返回数据
但如果它不等于PostContentId返回NullPointerException

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

4

1 回答 1

0

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

让我从Oracle Javadoc复制这个示例代码

示例 1:映射外键列的一对一关联

// 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的表的实体中。在您的情况下,外键似乎放在指向 POST 的 POST_CONTENT 中。

你必须@JoinColumn在你的班级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; }
于 2018-02-27T13:58:36.227 回答