2017-05-06 221 views
1

我無法設法使這個簡單的外鍵約束工作。外鍵休眠註釋

@Entity 
@Table(name = "wheel") 
@Data 
public class WheelEntity { 
    @Id 
    @Column(name = "id") 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Integer id; 
    ... 

@Entity 
@Table(name = "bike") 
@Data 
public class BikeEntity { 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Integer id; 

    @ManyToOne(targetEntity = WheelEntity.class, fetch=FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}) 
    @JoinColumn(name = "wheel_1_id", referencedColumnName = "id") 
    @NotNull 
    private Integer wheel_1_id; 

    @ManyToOne(targetEntity = WheelEntity.class, fetch=FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}) 
    @JoinColumn(name = "wheel_2_id", referencedColumnName = "id") 
    @NotNull 
    private Integer wheel_2_id; 
    ... 

當我要插入一個新的自行車,這裏是持續的BikeEntity時,我得到的錯誤:

Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Integer field com.xxx.xxx.xxx.storage.WheelEntity.id to java.lang.Integer 
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) 
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) 
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58) 
    at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36) 
    at java.lang.reflect.Field.get(Field.java:393) 
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:39) 

無法設置爲java.lang.Integer到java.lang.Integer中。 MMMMMM?奇怪!

的幫助

回答

1

非常感謝在休眠您具有內部ENTITY2 ENTITY1參考創建關係。正確的方法是:

@Entity 
@Table(name = "wheel") 
@Data 
public class WheelEntity { 
    @Id 
    @Column(name = "id") 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Integer id; 
    ... 

@Entity 
@Table(name = "bike") 
@Data 
public class BikeEntity { 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Integer id; 

    @ManyToOne(targetEntity = WheelEntity.class, fetch=FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}) 
    @JoinColumn(name = "wheel_1_id", referencedColumnName = "id") 
    @NotNull 
    private WheelEntity wheelEntity; 
+0

很多感謝傑伊史密斯,這是正確的答案。在開始時聽起來像是一件奇怪的事情,但後來我意識到我可以使用'em.getReference()'來獲取一個實例而不碰到數據庫。 – user3173237