在 PlayFramework 2 / Ebean ORM 中使用 @OneToOne,其中子级和父级共享相同的主键

2024-06-19

有两种型号:

模型/User.java

@Entity
@Table(name="users")
public class User extends Model
{
    @Id
    public int user_id;
    public String firstName;
    public String lastName;

    @OneToOne
    @PrimaryKeyJoinColumn
    public UserProfile profile;

    public static Finder<Integer,User> find = new Finder<Integer,User>( Integer.class, User.class );
}

模型/UserProfile.java

@Entity
@Table(name="user_profiles")
public class UserProfile extends Model
{
    @Id
    public int user_id;
    public String bio;

    @OneToOne(mappedBy = "user_id")
    public User user;

    public static Finder<Integer,UserProfile> find = new Finder<Integer,UserProfile>( Integer.class, UserProfile.class );
}

一些数据:

INSERT INTO users VALUES(1,"Joe","Bloh");
INSERT INTO users VALUES(2,"Maria","Luis");
INSERT INTO user_profiles VALUES(1, "programmer");
INSERT INTO user_profiles VALUES(2, "tester");

以及从用户获取个人资料的相同代码:

User user = User.find.byId(2);
UserProfile profile = UserProfile.find.byId(1);

这会触发异常:

javax.persistence.PersistenceException: Error on models.UserProfile.user. mappedBy property [models.UserBad.user_id]is not a OneToOne?

两个模型如何在 Ebean ORM 中共享相同的主键,并具有 @OneToOne 关系?


我发现,关联应该是:

模型/User.java

[...]
@OneToOne(mappedBy = "user")
public UserProfile profile;
[...]

模型/UserProfile.java

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

在 PlayFramework 2 / Ebean ORM 中使用 @OneToOne,其中子级和父级共享相同的主键 的相关文章

随机推荐