在子代和父代共享相同主键的PlayFramework 2/Ebean ORM中使用@OneToOne [英] Using @OneToOne in PlayFramework 2 / Ebean ORM where the child and parent shares the same primary key

查看:83
本文介绍了在子代和父代共享相同主键的PlayFramework 2/Ebean ORM中使用@OneToOne的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种型号:

模型/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 );
}

models/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");

和用于从用户那里获取个人资料的相同代码:

and same code that fetches the profile from a user:

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关系?

How can two models share the same primary key in Ebean ORM, and have a @OneToOne relationship ?

推荐答案

我找到了,关联应该是:

I found it, the associations should be:

模型/User.java

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

models/UserProfile.java

[...]
@OneToOne
@JoinColumn(name = "user_id")
public User user;
[...]

这篇关于在子代和父代共享相同主键的PlayFramework 2/Ebean ORM中使用@OneToOne的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆