我想在JPA Hibernate中映射一个Map。设置看起来像
@Entity(name = "reservation")
@Table(name = "reservation")
@Access(AccessType.FIELD)
@Audited
public class ReservationEntity {
// other fields
@ElementCollection(fetch = FetchType.EAGER)
@MapKeyColumn(name = "discountType")
@Column(name = "discountAmount")
@CollectionTable(
name="discountTypeAndAmount",
joinColumns=@JoinColumn(name="reservation_id")
)
private Map<DiscountType, BigDecimal> discountTypeAndAmount;
}
我可以第一次将实体写入数据库,但是当我更新实体时,在
entitymanager.getTransaction().commit()
上出现以下错误:Caused by: javax.persistence.EntityExistsException: A different object with
the same identifier value was already associated with the session :
[discountTypeAndAmount_AUD#{REV=DefaultRevisionEntity(id = 3,
revisionDate = Dec 20, 2016 8:52:45 PM), element=10.00,
ReservationEntity_reservation_id=1, mapkey=CASE_STUDY}]
例外情况是
CASE_STUDY
是枚举之一。 discountTypeAndAmount_AUD
是自动生成的审核日志表。看来审核表
discountTypeAndAmount
是用由REV
(修订ID),reservation_id
,discountType
和discountAmount
组成的复合键生成的,并且由于envers不知道如何而引发错误将BigDecimal
作为主键的一部分来处理。是否有注释将审核表的主键设置为仅由
REV
(修订ID),reservation_id
和discountType
组成的组合?由于该字段仍然是地图,因此实际上不需要将discountAmount
作为主键的一部分。 最佳答案
如果键是基本类型,则@MapKeyColumn用于指定键列的映射,但是我不确定,但是我猜DiscountType是实体本身,因此您需要使用@MapKeyJoinColumn映射键。