[英]Hibernate One To One mapping, Foreign Key is NULL
This is my first attempt to map with One to One relation.这是我第一次尝试映射一对一关系。 I have the following entities:
我有以下实体:
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Client {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Size(max = 100)
private String name;
@Email(message = "Email should be valid")
private String email;
@OneToOne
@PrimaryKeyJoinColumn
private Key key;
}
AND和
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Key {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private UUID number;
@OneToOne
private Client client;
public Key(UUID number) {
this.number = number;
}
}
They do not see each other, I get NULL in the foreign key section.他们没有看到对方,我在外键部分得到 NULL。 There is a solution when using the EntityManager class in the following post:
在以下帖子中使用 EntityManager 类时有一个解决方案:
JPA / Hibernate OneToOne Null in foreign key JPA / Hibernate OneToOne Null 外键
Unfortunately, that method doesn't work for me.不幸的是,这种方法对我不起作用。
Database snapshot:数据库快照:
Thank you for the answers!谢谢你的回答!
We don't need to mention the @PrimaryKeyJoinColumn
annotation.我们不需要提及
@PrimaryKeyJoinColumn
注释。 When we are mapping the tables it will create primary key and foreign key.当我们映射表时,它将创建主键和外键。 We just need to map properly.
我们只需要正确地映射。
In the Client model class you have to create the mapping like below在 Client 模型类中,您必须创建如下映射
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "key_id", referencedColumnName = "id")
private Key key;
and in the Key model class like this并在这样的 Key 模型类中
@OneToOne(mappedBy = "key")
private Client client;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.