一对多自身关联双向映射 (三)

2014-11-24 10:41:10 · 作者: · 浏览: 1
tends TestCase {
public void addCategory(){
//创建session
Session session = null;
try{
session = HibernateUtils.getSession();
session.beginTransaction();

Category food = new Category();
food.setName("food");

Category vegetable = new Category();
vegetable.setName("vegetable");

Category fruit = new Category();
fruit.setName("fruit");

Category tomato = new Category();
tomato.setName("tomato");

Category apple = new Category();
apple.setName("apple");

Category orange = new Category();
orange.setName("orange");

food.getChildCategory().add(vegetable);
vegetable.setParentCategory(food);

food.getChildCategory().add(fruit);
fruit.setParentCategory(food);

fruit.getChildCategory().add(apple);
apple.setParentCategory(fruit);

fruit.getChildCategory().add(orange);
orange.setParentCategory(fruit);

fruit.getChildCategory().add(tomato);
tomato.setParentCategory(fruit);

session.save(food);
session.beginTransaction().commit();
} catch(Exception e){
session.beginTransaction().rollback();
e.printStackTrace();
} finally{
HibernateUtils.closeSession(session);
}
}
public void modifyCategory(){
//创建session
Session session = null;
try{
session = HibernateUtils.getSession();
session.beginTransaction();

Category tomato = (Category)session.get(Category.class, 5);
Category vegetable = (Category)session.get(Category.class, 6);
Category fruit = (Category)session.get(Category.class, 2);

fruit.getChildCategory().remove(tomato);
vegetable.getChildCategory().add(tomato);
tomato.setParentCategory(vegetable);

session.beginTransaction().commit();
} catch(Exception e){
session.beginTransaction().rollback();
e.printStackTrace();
} finally{
HibernateUtils.closeSession(session);
}
}
}