java – Hibernate @OneToOne与多个对象的关系?
作者:互联网
如果我有这样的桌子……
+------------------------------------------------------+
| Code |
+------------------------------------------------------+
| id | target_uuid | code |
+----+----------------------------------------+--------+
| 1 | "01BE898A-C5A9-4F86-B0AA-4ACCDCE81B8F" | 0 |
+----+----------------------------------------+--------+
| 2 | "E139F21E-8C93-492B-9E0F-CC773FAE832D" | 2 |
+----+----------------------------------------+--------+
…而target_uuid可以引用Post或User uuid字段,我如何在Hibernate中映射它?
假设uuid不是Post或User的主键.我知道我知道.糟糕的数据模型,但我坚持下去.
我试过这个:
@Entity
@Table(name = "User")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "uuid")
private String uuid;
@OneToOne(mappedBy = "user")
@JoinColumn(name = "uuid")
private Code code;
// getters and setters
}
@Entity
@Table(name = "Post")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "uuid")
private String uuid;
@OneToOne(mappedBy = "post")
@JoinColumn(name = "uuid")
private Code code;
// getters and setters
}
@Entity
@Table(name = "Code")
public class Code {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "code")
private Integer code;
@Column(name = "target_uuid")
private String targetUuid;
@OneToOne
@JoinColumn(name = "target_uuid", insertable = false, updatable = false)
private User user;
@OneToOne
@JoinColumn(name = "target_uuid", insertable = false, updatable = false)
private Post post;
// getters and setters
}
这不会抛出异常并且似乎有效,但我的User和Post对象不断为其代码属性获取NULL值.
任何人都可以对此有所了解吗?
解决方法:
正如评论中所解释的那样,这种关联是AFAIK,不可能映射为双向关联.您可以将其映射为从Post到Code(以及从User到Code)的OneToOne单向关联,只需将JoinColumn批注的referencedColumnName设置为“target_uuid”即可.
标签:java,hibernate,one-to-one,hibernate-annotations 来源: https://codeday.me/bug/20190703/1365877.html