Multiple writable mappings in JPA?

可紊 提交于 2019-12-09 05:50:30

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

This would be the most strange thing .. but I just delete the line:

//  @JoinColumn(name="id_user")

And Eclipse do not alarm anymore about.. (so far =] ) I will leave this thread open 'cause I really think this is very strange to happen and solve like this.

UPDATE

I did as Brian instructed and it seems to solve my problem:

@Entity
@Table(name="user_review")
public class UserReview implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private Integer id;

    @Temporal(TemporalType.DATE)
    private Date date;

    private String review;

    //bi-directional many-to-one association to User
    @ManyToOne
    @JoinColumn(name="id_user_reviewer", insertable=false, updatable=false)
    private User user1;

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

    //bi-directional many-to-one association to UserInfo
    @ManyToOne
    @JoinColumn(name="id_user", insertable=false, updatable=false)
    private UserInfo userInfo;
        .. more code

It looks like there is a mismatch between the code and the error message you posted. The error message is complaining about a column named 'user_id', in your code however the @JoinColumn annotations uses 'id_user'.

That doesn't seem right, could it be that you copied the exception at one point and then changed the code?

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