0
1父實體可以具有0或多個懶惰子實體合併父和懶子收集列表
例如,有一種功能改變父母和孩子的實體狀態列,而合併(父),父實體被更新,但子實體插入新的而不是更新。
這兩個子實體的id,數據都與調試時在數據庫中完全一樣。
父對象放在Spring控制器的@SessionAttributes中,會是原因嗎?
即使我只合併子列表merge(childList),它也會創建新記錄而不是更新。
@Entity
@Table(name = "member")
public class Member implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "memberParent", cascade = CascadeType.ALL)
public List<Child> ChildList
getter setter......
}
@Entity
@Table(name = "child")
public class Child implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="member_id")
private int mem_id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumns({
@JoinColumn(name = "member_id", referencedColumnName = "id", insertable = false, updatable = false)
})
public Member memberParent;
getter setter......
}
//Controller
@SessionAttributes({"member"})
public class Appcontroller {
@Transactional
@RequestMapping(value = {"/update-member/{id}"}, method = RequestMethod.GET)
public String viewEditRepresetative(ModelMap model, @PathVariable ind id) {
Member member = memberService.find(id);
model.addAttributes("member", member);
}
@Transactional
@RequestMapping(value = {"/update-member"}, method = RequestMethod.POST)
public String viewEditRepresetative(ModelMap model, HttpServletRequest reques, @Valid @ModelAttribute("member") Member member, BindingResult result,
RedirectAttributes redirectAttributes, SessionStatus status) {
if (!result.hasErrors()) {
memberService.merge(member);
}
}
把你的代碼也一樣,所以它會有助於理解你是如何嘗試和確切的問題是什麼 –
@JekinKalariya您好,我剛更新了代碼 –
http://www.programmingforfuture.com/2011/02/hibernate -merge-may-insert-new-record.html可能對你有所幫助 –