如何将一对一的基本元素加入实体?

How to join one-to-one basic element to entity?

我有 2 tables useruser_password,我想加载 User 实体,以便在输入时填充实体中的 password 字段在 user_password table 存在。

表格:

user
--------
id
name

user_password
--------
user_id
password

实体:

@Entity
public class User implements Serializable {

    @Id
    @GeneratedValue( strategy = IDENTITY )
    private Long id;

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

    // @ElementCollection
    @JoinTable( name = "user_password", 
                joinColumns = @JoinColumn( name = "user_id" ) )
    @Column( name = "password" )
    private String password;

}

当我使用 @ElementCollection 并将 password 字段从 String 更改为 List 时它起作用,但是 user_password 中的 user_id 列也是一个主键,这意味着永远不会超过 1 个密码。

你可以试试这样的

@Entity
@SecondaryTable(name="user_password",
                pkJoinColumns=@PrimaryKeyJoinColumn(name="user_id"))
public class User implements Serializable {
    ...
    @Column(table = "user_password", name = "password" )
    private String password;
    ...
}