Foreign Key Hibernate Annotation

I can not manage to make this simple foreign key constraint work.

@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;
    ...

When I want to insert a new bike, here is the error I get when persisting the 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)

Can not set java.lang.Integer to java.lang.Integer. mmmmmm? Strange!

Many thanks for the help

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

In hibernate you create relation by having reference of Entity1 inside Entity2. The correct way is:

@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;