Hello,
for my project i have a many to many relationship between two Entities. It is total 3 tables in database: menuitems, menuitemcategories and menuitemcategorylookup. For every menuitem can belong to many categories and every category can have many menuitems.
The following are the codes for objects:
code for object MenuItem
Code:
@Entity
@Table(name = "menuItems")
public class MenuItem implements Serializable {
@Id
@Column(name = "id")
int id;
@Column(name = "itemName", nullable = false)
String itemName;
@ManyToMany(
targetEntity = MenuItemCategory.class,
fetch = FetchType.EAGER,
cascade = {CascadeType.ALL})
@JoinTable(
name="menuItemCategoryLookup",
joinColumns={@JoinColumn(name="menuItemID")},
inverseJoinColumns={@JoinColumn(name="menuItemCategoryID")}
)
@IndexColumn(name = "MenuItemID")
private Set<MenuItemCategory> menuItemCategories = new HashSet<MenuItemCategory>(0);
... ... // getting and setting methods
}
and the code for object MenuItemCategory:
Code:
@Entity
@Table(name = "menuItemCategories")
public class MenuItemCategory implements Serializable {
@Id
@Column(name = "id")
private int id;
@Column(name = "categoryName", nullable = false)
private String categoryName;
@ManyToMany(
targetEntity = MenuItem.class,
fetch = FetchType.EAGER,
cascade = CascadeType.ALL,
mappedBy = "menuItemCategories")
private Set<MenuItem> menuItems = new HashSet<MenuItem>(0);
... ... // getting and setting methods
}
i use function fetchMenuItem() to get the MenuItem object from database:
Code:
public MenuItem fetchMenuItem(int i) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
try {
session.beginTransaction();
MenuItem menuItem = (MenuItem) session.get(MenuItem.class, i);
session.getTransaction().commit();
session.close();
return menuItem;
} catch (Exception e) {
session.close();
System.out.println(e.getMessage());
return null;
}
}
My Problem is:
When I save the MenuItem object with MenuItemCategory to database is ok. In database it adds the all records successfully in 3 Tables: MenuItems, MenuItemCategories and MenuitemCategoryLookup.
Following is the code:
Code:
@Test
public void testSaveMenuItemWithMenuItemCategories() throws Exception {
// MenuManipulator manage the MenuItem and the other objects (CRUD).
MenuManipulator menuMan = new MenuManipulator();
MenuItemCategory softDrink = new MenuItemCategory(3, "Soft Drink");
MenuItemCategory juice = new MenuItemCategory(4, "Juice");
MenuItem orangeJuice = new MenuItem(1, "Orange Juice");
orangeJuice.getMenuItemCategories().add(softDrink);
orangeJuice.getMenuItemCategories().add(juice);
assertTrue(menuMan.addMenuItem(orangeJuice));
}
But, when i fetch the MenuItem to object. I have got the MenuItem object
without MenuItemCategories Attribute. I don't know, what is wrong? It is the erorr in definition of object or in fetch function?
thanks for help!