Using @OneToOne in PlayFramework 2 / Ebean ORM where the child and parent shares the same primary key

与世无争的帅哥 提交于 2019-12-22 17:53:01

问题


There is two models:

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

some data:

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);

which triggers the exception:

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

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


回答1:


I found it, the associations should be:

models/User.java

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

models/UserProfile.java

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


来源:https://stackoverflow.com/questions/18498418/using-onetoone-in-playframework-2-ebean-orm-where-the-child-and-parent-shares

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!