一.Person
package com.aaxis.model;
import java.util.List;
/**
* User: Zhong Gang
*/
public class Person {
private Integer id;
private Integer version;
private String name;
private List<Role> roles;
public Person(String name) {
this.name = name;
}
public Person(String name, List<Role> roles) {
this.name = name;
this.roles = roles;
}
public Person() {
}
}
二.Role
package com.aaxis.model;
/**
* User: Zhong Gang
*/
public enum Role {
CTO,
CEO,
CFO
}
三.Person.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping default-access="field"> <class name="com.aaxis.model.Person" table="present"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native"/> </id> <version name="version" column="version" type="java.lang.Integer"/> <property name="name" column="name" type="java.lang.String"/> <bag name="roles" cascade="all" table="roles"> <key column="present_id"/> <element column="role"> <type name="org.hibernate.type.EnumType"> <param name="enumClass">com.aaxis.model.Role</param> <param name="type">12</param> </type> </element> </bag> </class> </hibernate-mapping>
四.测试
package com.aaxis;
import com.aaxis.model.Person;
import com.aaxis.model.Role;
import junit.framework.TestCase;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: Zhong Gang
* Date: 10/24/11
* Time: 11:50 AM
*/
public class HibernateCoreTest extends TestCase {
public void testElement() throws Exception {
List<Role> roles = new ArrayList<Role>();
roles.add(Role.CEO);
roles.add(Role.CFO);
Person person1 = new Person("present1", roles);
Person person2 = new Person("present2", roles);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(person1);
session.saveOrUpdate(person2);
transaction.commit();
session.close();
}
}
数据库表结构
最后附上源码以供参考