日期:2014-05-19 浏览次数:20949 次
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.linuslan.model"> <class name="Category" table="CATEGORIES"> <id name="id" column="ID"> <generator class="sequence"> <param name="sequence">CATEGORIES_SEQ</param> </generator> </id> <property name="name" column="NAME"></property> <many-to-one name="parentCategory" column="CATEGORY_ID" class="com.linuslan.model.Category" cascade="save-update" lazy="false"></many-to-one> <set name="childCategories" table="CATEGORIES" inverse="true" cascade="all-delete-orphan"> <key column="CATEGORY_ID"></key> <one-to-many class="com.linuslan.model.Category"/> </set> </class> </hibernate-mapping>
package com.linuslan.model; import java.util.HashSet; import java.util.Set; public class Category { private Long id; private String name; private Category parentCategory; private Set<Category> childCategories = new HashSet<Category>(); public Category() { } public Category(String name, Set<Category> childCategories, Category parentCategory) { this.name = name; this.childCategories = childCategories; this.parentCategory = parentCategory; } public Long getId() { return id; } @SuppressWarnings("unused") private void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getParentCategory() { return parentCategory; } public void setParentCategory(Category parentCategory) { this.parentCategory = parentCategory; } public Set<Category> getChildCategories() { return childCategories; } public void setChildCategories(Set<Category> childCategories) { this.childCategories = childCategories; } }
package com.linuslan.business; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.linuslan.model.Category; import com.linuslan.util.HibernateUtil; public class CategoryBusinessService { public void saveParentCategory() { Category food = new Category(); food.setName("food"); Category fruit = new Category(); fruit.setName("fruit"); Category vegetable = new Category(); vegetable.setName("vegetable"); Set<Category> secondChildCategories = new HashSet<Category>(); secondChildCategories.add(fruit); secondChildCategories.add(vegetable); food.setChildCategories(secondChildCategories); Session session = this.sessionFactory.openSession();