我有2个实体User和UserSettings。 我正在尝试构建一个流来修改DB中的UserSettings行。 这是我的User和UserSetting对象 -
@Entity
@Table(name = "user")
public class User implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private int id;
private String name;
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime createdat = new DateTime();
@OneToMany( fetch=FetchType.EAGER)
@JoinColumn(referencedColumnName="id", name = "userID")
@BatchSize(size = 50)
@MapKey(name="name")
@Cascade({CascadeType.ALL})
private Map<String,UserSetting> userSetting;
...
}
@Entity
@IdClass(UserSetting.UserSettingId.class)
@Table(name = "usersettings")
public class UserSetting implements Serializable{
@Id
private String name;
private String value;
@Column(name="UserID",insertable = false,updatable = false) //
private Integer userId;
@Id
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="userID")
private User user;
...
}
在修改UserSetting之前我试图获取对象,修改其值,然后使用save方法。
这是保存修改数据的方法 -
public void saveUserSettings(int userId, String name, String value) {
UserSetting userSetting = new UserSetting();
userSetting.setUserId(userId);
userSetting.setName(name);
userSetting.setValue(value);
User user = usersRepository.findOne(userId);
userSetting.setUser(user);
userSettingRepository.save(userSetting);
}
保存总是失败,因为从usersRepository.findOne(userId)返回的用户是一个惰性对象而不是实际对象。
为什么会这样? 如何让find返回实际对象?
提前谢谢
亚伊尔
答案 0 :(得分:0)
使用EntityManager#getReference
@Autowired
EntityManager em;
public void saveUserSettings(int userId, String name, String value) {
UserSetting userSetting = new UserSetting();
userSetting.setUserId(userId);
userSetting.setName(name);
userSetting.setValue(value);
User user = em.getReference(userId,User.class); // no actual fetch
userSetting.setUser(user);
userSettingRepository.save(userSetting);
}
答案 1 :(得分:0)
试试这个:
UserSetting userSettingDb = usersRepository.findOne(userId);
User user = userSettingDb.getUser();
userSetting.setUser(user);`
userSettingRepository.save(userSetting);`
答案 2 :(得分:0)
我通过强制延迟对象返回实现来解决问题(unproxying)。