Search code examples
hibernatejpaeclipselinkpojo

Multiple writable mappings in JPA?


I would like to make a review about some user at my system, this review is made by others users. So here it's my user's table:

user table

And this is my user_review table:

user review table

The EclipseLink is generating like this (actually it insted of @PrimaryJoinColumn was @JoinColumn it change it because of this post ):

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    @Temporal(TemporalType.DATE)
    private Date date;

    private String review;

    //bi-directional many-to-one association to User
//  @PrimaryKeyJoinColumn(name="id_user_reviewer")
    @ManyToOne 
    @JoinColumn(name="id_user_reviewer")
    private User reviewer;

    //bi-directional many-to-one association to User
//  @JoinColumn(name="id_user")
    @ManyToOne 
    @PrimaryKeyJoinColumn(name="id_user")
    private User user;

    //bi-directional many-to-one association to UserInfo
    @ManyToOne
    @JoinColumn(name="id_user")
    private UserInfo userInfo; 

And keeps giving me this error:

Join column "user_id" cannot be resolved on table "user_review"

I really don't what to do 'cause I already try many things, different associations but nothing seems to be working. Any ideas ?


Solution

  • Hmmm - your summary:

    Multiple writable mappings in JPA?

    does not match what seems to be your question:

    Why do I get this error: Join column "user_id" cannot be resolved on table "user_review"?

    So I'm guessing you experience the "multiple writable..." problem when you specify a @JoinColumn on your user field; and you get the "...cannot be resolved..." problem when you specify a @PrimaryKeyJoinColumn on your user field.

    @PrimaryKeyJoinColumn cannot be used on a @ManyToOne mapping. (It can be used on a @OneToOne mapping when entities share a primary key.) As a result, Eclipse is calculating the default join column name as defined by the JPA spec (which is "user_id"), and since that column is not on your user_review table, you get an error message indicating the field cannot be resolved on the database table.

    You should un-comment the @JoinColumn on your user field. That results in two @OneToMany mappings that will determine the foreign key to be written to the id_user column on the database - it will take the value of the primary key of either the User referenced by the user field or the UserInfo referenced by the userInfo field. This is not allowed. Either you need to rework your database relations or your object model or mark one of the mappings read-only (@JoinColumn(name="id_user", insertable = false, updatable = false)).