简体   繁体   中英

How to save a List of persistent objects bound to another objects with Hibernate

I have a main Object called Menu, with a List of objects VoceMenu

public class Menu implements Serializable{
...
@OneToMany(mappedBy="menu", fetch=FetchType.EAGER)  
private List<VoceMenu> voceMenuList;
...
}

when I edit a object Menu and then I save it with

...
getCurrentSessionFactory().saveOrUpdate(menu);  
...

I can see that on the DB, the value of the fields of the object Menu are edited, the fields of the objects VoceMenu aren't.

Probably I miss something.

Did you set Menu on VoceMenu object before persisting? Try the following:

Menu menu = new Menu();
VoceMenu voce = new VoceMenu();
voce.setMenu(menu);
voceMenuList.add(voce);

...
getCurrentSessionFactory().saveOrUpdate(menu);

Also, you need to add cascade = Cascade.PERSIST to make it happen:

@OneToMany(mappedBy="menu", fetch=FetchType.EAGER, cascade = Cascade.PERSIST) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM