JPA/Hibernate tries to store too many parameters in entity with composite Id (and doubling properties)

痞子三分冷 提交于 2019-12-10 16:12:56

问题


I have entity with composite Id

@Entity
@IdClass(value = BorrowId.class)
@Table(name = "BORROW")
public class Borrow {

    @Id
    @Column(name = "BOOK_ID", insertable = false, updatable = false)
    private long bookId;

    @Id
    @Column(name = "BORROWER_ID", insertable = false, updatable = false)
    private long borrowerId;

    @Id
    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
    @JoinColumn(name = "BOOK_ID")
    private Book book;

    @Id
    @ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
    @JoinColumn(name = "BORROWER_ID")
    private Borrower borrower;

    @Id
    @Column(name = "BORROW_DATE")
    private Date borrowDate;

    @Column(name = "RETURN_DATE")
    private Date returnDate;

BorrowId has properties (everything with getters/setters)

    private long bookId;
    private long borrowerId;

    private Date borrowDate;

and equals,hashCode methods

when I'm trying to persist Borrow entity (book and borrower properties set to corresponding entities, then calling entityManager.persist(borrow); ) I've got in my logs:

Hibernate: insert into BORROW (BORROWER_ID, BOOK_ID, RETURN_DATE, BORROW_DATE) values (?, ?, ?, ?) // this insert statement is correct (that's a look of my table) Invalid value "5" for parameter "parameterIndex" [90008-174]

So it looks like someone is doing something wrong :) How to solve this? is my entity declaration faulty? (I wanted to use CompositeId to learn something about using it)


回答1:


Thanks to @JB nizet

@Id
@Column(name = "BOOK_ID", insertable = false, updatable = false)
private long bookId;

@Id
@Column(name = "BORROWER_ID", insertable = false, updatable = false)
private long borrowerId;

@MapsId("bookId")
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST,
                                              CascadeType.MERGE,
                                              CascadeType.REFRESH})
@JoinColumn(name = "BOOK_ID")
private Book book;

@MapsId("borrowerId")
@ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, 
                                               CascadeType.MERGE,
                                               CascadeType.REFRESH})
@JoinColumn(name = "BORROWER_ID")
private Borrower borrower;

@Id
@Column(name = "BORROW_DATE")
private Date borrowDate;

Solves the problem, strange, because nowhere, in any example/tutorial there was no @MapsId used with @IdClass. I'm not sure if now @JoinColumn is needed



来源:https://stackoverflow.com/questions/20146155/jpa-hibernate-tries-to-store-too-many-parameters-in-entity-with-composite-id-an

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