[英]Are composite primary keys in JPA with Quarkus possible?
如何使用 Quarkus JPA 聲明復合鍵?
嘗試在帶有 Quarkus 的@Entity
class 中使用多個@Id
注釋,會導致錯誤:
Currently the @Id annotation can only be placed on a single field or method. Offending class is abc.model.Property
at io.quarkus.spring.data.deployment.generate.StockMethodsAdder.getIdAnnotationTargetRec(StockMethodsAdder.java:940)
但首先,在聲明之后
interface PropertyRepository : CrudRepository<Property, Pair<String, abc.model.Entity>>
沒有上述聲明,就沒有投訴,但沒有可能主動管理Property
的實例。
如何規避這個錯誤?
我正在處理兩個 JPA 實體:
1.第一個名為Entity
(不要誤認為是注解)
2.第二個叫Property
一個Entity
可以有 0..n 個Property
實例。 代碼如下:
@Entity
data class Entity (
@Id
@Column(name = "entity_id", updatable = false)
var entityId: String? = null,
@Column(nullable = true)
var type: String? = null
) {
@OneToMany(mappedBy = "entity")
var properties: List<Property>? = null
}
@Entity
data class Property (
@Id
@Column(name = "type")
var type: String? = null,
@Id
@ManyToOne
@JoinColumn(name = "entity_id")
private var entity: abc.model.Entity? = null
) : Serializable
如下將復合主鍵聲明為@EmbeddedId
並不能解決問題,因為 Quarkus 目前在這種情況下不允許使用除@Id
之外的其他注釋:
@Entity
data class Entity (
@Id
@Column(name = "entity_id", updatable = false)
var entityId: String? = null,
@Column(nullable = true)
var type: String? = null
) {
@OneToMany(mappedBy = "propertyId.entityId")
var properties: List<Property>? = null
}
interface PropertyRepository : CrudRepository<Property, PropertyId>
@Embeddable
data class PropertyId (
var type: String? = null,
@Column(name = "entity_id")
private var entityId: String? = null
) : Serializable
@Entity
data class Property (
@EmbeddedId
var propertyId: PropertyId? = null,
@Column(name = "constant_value")
var constantValue: String? = null
)
java.lang.IllegalArgumentException: Currently only Entities with the @Id annotation are supported. Offending class is abc.model.Property
at io.quarkus.spring.data.deployment.generate.StockMethodsAdder.getIdAnnotationTargetRec(StockMethodsAdder.java:932)
有可能,您的實體必須擴展 PanacheEntityBase 並使用 class 級別注釋 @Table,@Entity,@IdClass(PK.class),其中 Pk 是具有復合主鍵字段的 POJO,然后您必須聲明相同的字段實體中的 @Id 注釋。 例如:
@Entity()
@Table(name = "agent")
@IdClass(AgentPK.class)
public class AgentBRA extends PanacheEntityBase {
@Id
public Integer idUsuario;
@Id
public Integer idAgent;
和 AgentPk:
public class AgentPK implements Serializable{
protected Integer idUsuario;
protected Integer idAgent;
// getters setters and hascode and equals methods
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.