hibernate多对多保存(中间表不更新)
问题是这样的,我想实现Menu(菜单类), MenuItem(菜单项类),两个类是多对多关系,public class Menu {
/* 主键 */
private Integer Id;
/* 菜单名 */
private String name;
/* 一个菜单有多个菜单项, 多对多的关系 */
private Set menuItems = new HashSet(0);
/**
* @hibernate.id generator-class="native" column="menu_id" type="java.lang.Integer"
*
*/
public Integer getId() {
return Id;
}
/**
* @param id
* the id to set
*/
public void setId(Integer id) {
Id = id;
}
/**
* @hibernate.set table="menu_menu_item" lazy="true" inverse="true" cascade="save- update"
* @hibernate.collection-key column="menu_id"
* @hibernate.collection-many-to-many class="com.zhidian.model.MenuItem" column="menu_item_id"
* @return 菜单项的集合
*/
public Set getMenuItems() {
return menuItems;
}
/**
* @param menuItems
* the menuItems to set
*/
public void setMenuItems(Set menuItems) {
this.menuItems = menuItems;
}
/**
* @hibernate.property column="name" type="java.lang.String" length="60"
* @return 菜单名
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
}
public class MenuItem {
/* 主键 */
private Integer id;
/* 菜单项名称 */
private String name;
/* 一个菜单项对应多个菜单。多对多关系 */
private Set menus = new HashSet(0);
/**
* @hibernate.id generator-class="native" column="menu_item_id" type="java.lang.Integer"
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @hibernate.set table="menu_menu_item" lazy="true" inverse="true" cascade="save- update"
* @hibernate.collection-key column="menu_item_id"
* @hibernate.collection-many-to-many class="com.zhidian.model.Menu" column="menu_id"
* @return 菜单项的集合
*/
public Set getMenus() {
return menus;
}
/**
* @param menus
* the menus to set
*/
public void setMenus(Set menus) {
this.menus = menus;
}
/**
* @hibernate.property column="name" type="java.lang.String" length="40"
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
}
测试: /*菜单加菜单项*/
public void testMenuAddItem()
{
Session sn = HibernateUtil.getSession();
Transaction tx = sn.beginTransaction();
Menu menu = new Menu();
menu.setName("文件");
MenuItem menuItem = new MenuItem();
menuItem.setName("打开");
menu.getMenuItems().add(menuItem);