我在jpa / hibernate中映射复合键时遇到了问题。父实体和子实体都具有复合主键。
当父实体有一个简单的键而子实体有一个复合键时,我可以使用@mapsId。
在hibernate文档中,他们在映射中使用@JoinCoumns来演示两个复合键的映射。但是在他们的例子中,还不清楚这些列引用是在哪里定义的。
我有以下几点:
@Embeddable
public class PriceRequestLegKey implements Serializable {
@Column(name = "leg_request_id")
private String requestId;
@Column(name = "display_index")
private int displayIndex;
...
}
@Embeddable
public class AllocationKey implements Serializable {
@Column(name = "leg_request_id")
private String requestId;
@Column(name = "display_index")
private int displayIndex;
@Column(name = "allocation_index")
private int allocationIndex;
...
}
@Entity(name = "PriceRequestLeg")
public class PriceRequestLegModel {
@EmbeddedId
private PriceRequestLegKey legKey;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumns({
@JoinColumn(name = "leg_request_id", referencedColumnName = "leg_request_id"),
@JoinColumn(name = "display_index", referencedColumnName = "display_index")
})
private List<AllocationModel> allocations;
...
}
@Entity(name = "Allocation")
public class AllocationModel {
@EmbeddedId
private AllocationKey allocationKey;
@ManyToOne
@MapsId
@JoinColumns({
@JoinColumn(name = "leg_request_id", referencedColumnName = "leg_request_id"),
@JoinColumn(name = "display_index", referencedColumnName = "display_index")
})
private PriceRequestLegModel leg;
...
}在运行时,保存时会出现以下异常:
org.springframework.orm.jpa.JpaSystemException: could not get a field value by reflection getter of com.lbg.legato.rfq.data.entity.AllocationKey.displayIndex; nested exception is org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.lbg.legato.rfq.data.entity.AllocationKey.displayIndex我认为这是假的,因为有getter和setter。如果在mappedBy=上使用priceRequestLegModel“腿”和AllocationModel上使用@MapsId,我也会得到相同的错误。有人能指出我在这里做错了什么吗?
发布于 2018-06-19 18:40:29
您应该将mappedBy="leg"还原到PriceRequestLegModel @OneToMany注释:
@Entity(name = "PriceRequestLeg")
public class PriceRequestLegModel {
@EmbeddedId
private PriceRequestLegKey legKey;
@OneToMany(mappedBy="leg", cascade = CascadeType.ALL)
private List<AllocationModel> allocations;
...
}然后,您应该将AllocationKey更改为引用PriceRequestLegKey
@Embeddable
public class AllocationKey implements Serializable {
PriceRequestLegKey legKey; // corresponds to PK type of PriceRequestLegModel
@Column(name = "allocation_index")
private int allocationIndex;
...
}然后适当地设置Allocation.leg @MapsId注释的值:
@Entity(name = "Allocation")
public class AllocationModel {
@EmbeddedId
private AllocationKey allocationKey;
@ManyToOne
@MapsId("legKey")
@JoinColumns({
@JoinColumn(name = "leg_request_id", referencedColumnName = "leg_request_id"),
@JoinColumn(name = "display_index", referencedColumnName = "display_index")
})
private PriceRequestLegModel leg;
...
}在JPA2.2规范 2.4.1节中有一些类似的例子。
https://stackoverflow.com/questions/50931495
复制相似问题