Java: hibernate @OneToOne 映射

标签 java hibernate jpa one-to-one hibernate-annotations

我正在尝试让 Hibernate @OneToOne 注释正常工作,但在这里没有取得太大成功...

假设我有一个名为 status 的表,如下所示:

+------------------------------------------------+
|                     status                     |
+------------------------------------------------+
| id | frn_user_id | frn_content_id |   status   |
+----+-------------+----------------+------------+
|  1 |     111     |        0       |  "active"  |
+----+-------------+----------------+------------+
|  2 |      0      |       222      | "inactive" |
+----+-------------+----------------+------------+

我有一个 User 的实体,看起来像这样:

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Integer id;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "userId")
    private Status status;

    // getters and setters
}

Content 有一个类似的实体,Status 的另一个实体如下所示:

@Entity
@Table(name = "status")
public class Status {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Integer id;

    @Column(name = "frn_user_id")
    private Integer userId;

    @Column(name = "frn_content_id")
    private Integer contentId;

    @Column(name = "status")
    private String status;

    // getters and setters
}

当我对 User 执行读取操作时,我希望 User.getStatus() 将返回带有 id 的 Status 对象=1。相反,我得到一个 AnnotationException:“Referenced property not a (One|Many)ToOne: Status.userId in mappedBy User.status”

我已经在 SO 上翻阅了文档、教程和示例,但到目前为止我尝试的一切都失败了。

另外值得注意的是:这应该支持一对零或一的关系,因为一些 usercontent 记录在 状态表。

任何帮助将不胜感激!

最佳答案

您的状态实体不得具有使用 @Column 映射的整数类型的属性 userIdcontentId。它必须具有 User 和 Content 类型的属性 usercontent,用 @OneToOne 映射:

public class User {
    @OneToOne(mappedBy = "user")
    private Status status;
    // ...
}

public class Status {
    @OneToOne
    @JoinColumn(name = "frn_user_id")
    private User user;
    // ...
}

一个用户有一个状态。一个状态有一个用户。

关于Java: hibernate @OneToOne 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21762328/

相关文章:

java - JPA - 通过对象集合中的多个属性查找

hibernate - 对象的动态延迟加载不起作用

java - 如何让多对多关系船的双方拥有?

java - 通过 Activity 快捷方式启动时,如何在字段中设置数据库中的特定数据?

java - 如何在运行时获取 TestNG 线程数

java - Spring Controller /服务/存储库中的泛型

java - 如何知道是什么让 hibernate 持久化对象变脏了?

java - 使用 JPA 和 JasperReports 的复杂报告

Java:如何从内部类中的方法返回外部方法

java - 在 Java 中验证来自字符串的语句