Java:Hibernate @OneToOne 映射

2024-01-07

我正在尝试进入休眠状态@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()将返回一个Status对象与id=1。相反,我得到 AnnotationException:“引用的属性不是 (One|Many)ToOne:mappedBy User.status 中的 Status.userId”

我已经在此处详细介绍了文档、教程和示例,但到目前为止我尝试过的所有内容都失败了。

另外值得注意的是:这应该支持一对零或一的关系,因为某些user and content记录中不会有引用status table.

任何帮助将不胜感激!


您的 Status 实体不得具有属性userId and contentId类型为 Integer,映射为@Column。它必须有属性user and content用户和内容类型,映射为@OneToOne:

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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java:Hibernate @OneToOne 映射 的相关文章

随机推荐