用户类
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="PK_USER_ID")
private Integer userId;
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_NAME")
private String lastName;
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name="FK_USER_ID",referencedColumnName="PK_USER_ID")
private Set<DeviceInfo> deviceInfos;
}
DeviceInfo
@Entity
@Table(name="device_info")
public class DeviceInfo {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="DEVICE_ID")
private Integer deviceId;
@Column(name="DEVICE_KEY")
private String deviceKey;
@Column(name="FK_USER_ID")
private Integer userId;
}
当我尝试将数据插入用户表和device_info表时,插入了数据,但是device_info表的外键列未使用用户表的主键更新。
Hibernate版本:4.3.6.Final 春季版:4.3.1
答案 0 :(得分:1)
您是否错过了在持久化之前在deviceInfo对象中设置用户对象,代码应如下所示:
user.setDeviceInfo(setOfDeviceInfo);
deviceInfo.setUser(user);
session.save(user);
答案 1 :(得分:1)
我认为您的实体DeviceInfo
中缺少@ManyToOne映射@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="PK_USER_ID")
private Integer userId;
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_NAME")
private String lastName;
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY, mappedBy = "user")
private Set<DeviceInfo> deviceInfos;
}
@Entity
@Table(name="device_info")
public class DeviceInfo {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="DEVICE_ID")
private Integer deviceId;
@Column(name="DEVICE_KEY")
private String deviceKey;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PK_USER_ID", nullable = false)
private User user;
}