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

StackOverflow https://stackoverflow.com/questions/18498418

Question

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 ?

Était-ce utile?

La solution

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;
[...]
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top