gpt4 book ai didi

java - 如何使用其 id 将另一个实体嵌入到 Hibernate 实体中?

转载 作者:太空宇宙 更新时间:2023-11-03 12:16:11 26 4
gpt4 key购买 nike

假设我有一个 Role 类型,它包含一个 long idString name 等。我还有另一个 User 类。每个用户都有一个 roleId 列,该列将指向 Role.id

在我的数据库中,我将使用 2 个表,一个用于用户,另一个用于角色。 user 表中的 roleId 将是 role.id 表的外键。

我的问题是,我如何在 Hibernate 中映射它,以便我能够在我的 User 类中有一个 Role role 列,并且将是能够做 user.getRole().getName() 之类的事情吗?

最佳答案

From the manual :

Many-to-one associations are declared at the property level with the annotation @ManyToOne:

 @Entity
public class User {
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
@JoinColumn(name="roleId")
public Role getRole() {
return role;
}
...
}

The @JoinColumn attribute is optional, the default value(s) is like in one to one, the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column in the owned side. In this example company_id because the property name is company and the column id of Company is id.

关于java - 如何使用其 id 将另一个实体嵌入到 Hibernate 实体中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22044264/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com