0

我使用Java + Spring + Hibernate的@OneToOne隨着@JoinColumn只保存在UUID,而不是整個對象

當測試下面的代碼,我得到一個錯誤:

javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.XXX.XXX.entity.Policy.id

@Entity 
@Table(name = "assignment") 
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) 
public class Assignment extends BaseEntity { 

    @Id 
    @Column(name = "id") 
    @Type(type = "pg-uuid") 
    @NotTracked 
    private UUID id; 

    @OneToOne(targetEntity = Policy.class) 
    @JoinColumn(name = "policy_id", nullable = false, referencedColumnName = "policy_id") 
    @OnDelete(action = OnDeleteAction.CASCADE) 
    @TrackedEntity(isIdentityField = true) 
    private UUID policyID; 
} 

@Entity 
@Table(name = "policy") 
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "policy") 
@Inheritance(strategy = InheritanceType.JOINED) 
public class Policy extends BaseEntity { 

    @Id 
    @Column(name = "policy_id") 
    @Type(type = "pg-uuid") 
    @NotTracked 
    private UUID id; 

    ... 
    ... 
    .. 

} 

當改變從UUIDprivate UUID policyID;Policy,它的工作就好了,有沒有一種方法來設置莫名其妙內政策對特定對象的引用作爲ID,而不是等待策略的整個對象的分配對象裏面?

回答

1

可能只包含UUID,但它不再是hibernate託管的FK。只要你想Hibernate來處理您的FK ..你會簡單地改變Assignment到我不建議這樣的:

@Entity 
@Table(name = "assignment") 
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) 
public class Assignment extends BaseEntity { 

    @Id 
    @Column(name = "id") 
    @Type(type = "pg-uuid") 
    @NotTracked 
    private UUID id; 

    @Column(name="policy_id") 
    private UUID policyID; 
} 

有了這樣說,你將失去所有級聯選項和FK檢查約束對這一領域的,除非你手動將它們添加到您的數據庫。

0

我認爲沒有理由使用UUID而不是對策略對象的引用。 你可以註釋你想延遲加載對象,所以它只是從數據庫加載,如果你想訪問另一個屬性的策略對象:

@OneToOne(targetEntity = Policy.class,fetch = FetchType .LAZY)

相關問題