Hibernate element使用

 

  一.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();
    }
}

 

  数据库表结构

 

  

  最后附上源码以供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值