Reputation: 350
I'm trying to achieve this with hibernate:
My codes is as follows:
Device model
@Entity
public class Device {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "fk_user", nullable = true, referencedColumnName = "ID")
private User user;
...
}
Statistics model
@Entity
public class Statistic {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({ @JoinColumn(name = "fk_device", nullable = false, referencedColumnName = "ID"),
@JoinColumn(name = "fk_device_user", nullable = false, referencedColumnName = "fk_user") })
private Device device;
...
}
However, there's an error saying there's no logical column fk_user in device.
Caused by: org.hibernate.MappingException: Unable to find column with logical name: fk_user in device
I suppose it is because fk_user is a foreign key. But how can I solve this? Thanks.
Upvotes: 2
Views: 4082
Reputation: 26492
Based on you schema i would map the Device entity as follows:
public class Devince{
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = true)
private User user;
...
}
}
You dont need the referencedColumnName
as you are referring to the User
entity primary key. If you would refer to non-primary key column, then that would be necessary.
Regarding the Statistic entity:
public class Statistic {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({ @JoinColumn(name = "device_id", nullable = false),
@JoinColumn(name = "device_user_id", nullable = false,
referencedColumnName = "user_id") })
...
}
}
Again, you only need the referencesColumnName
in the second @JoinColumn
.
Upvotes: 2