我的代码如下:
设备型号
@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;
...
}
统计模型
@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;
...
}
但是,如果设备中没有逻辑列fk_user,则会出现错误。
Caused by: org.hibernate.MappingException: Unable to find column with logical name: fk_user in device
我想这是因为fk_user是一个外键。但是我该如何解决这个问题呢?感谢。
答案 0 :(得分:2)
根据您的架构,我将按如下方式映射Device实体:
公共阶级Devince {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = true)
private User user;
...
}
}
您不需要referencedColumnName
,因为您指的是User
实体主键。如果您要引用非主键列,那么这是必要的。
关于统计实体:
public class Statistic {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({ @JoinColumn(name = "device_id", nullable = false),
@JoinColumn(name = "device_user_id", nullable = false,
referencedColumnName = "user_id") })
...
}
}
同样,您只需要第二个referencesColumnName
中的@JoinColumn
。