Hibernate的映射(集合)

1. Hibernate配置文件(src/hibernate.cfg.xml)

    在hibernate.cfg.xml中增加 <property name="hbm2ddl.auto">update</property> 方便在测试的时候自动生成数据库表字段。

2. Model(src/test/Person.java)

public class Person{
    private Integer id;
    private String name;
    private int age;
    private List<String> schools = new ArrayList<String>(); //List
    private String[] schools2; //数组
    private Set<String> schools3 = new HashSet<String>(); //无序不重复集合
    private Collection<String> schools4 = new ArrayList<String>(); //集合属性,通过bag映射为无序
    private Map<String ,Float> scores = new HashMap<String ,Float>(); //map键值对属性
    private SortedSet<String> trainings = new TreeSet<String>(); //有序Set集合属性

    ........... .//getter And setter
}

3. 映射文件(src/test/hibernate.cfg.xml)

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="test">
    <class name="Person" table="person_inf">
        <id name="id" column="person_id">
            <!-- 指定主键生成器策略 -->
            <generator class="identity"/>
        </id>
        <property name="name" type="string"/>
        <property name="age" type="int"/>
        
        <!-- 映射List集合属性  有序-->
        <list name="schools" table="school" lazy="false">
            <!-- 映射集合属性数据表的外键列 -->
            <key column="person_id" not-null="true"/>
            <!-- 映射集合属性数据表的集合索引列 -->
            <list-index column="list_order"/>
            <!-- 映射保存集合元素的数据列 -->
            <element type="string" column="school_name"/>
        </list>
        
        <!-- 映射数组属性 -->
        <array name="schools2" table="school2">
            <!-- 映射数组属性数据表的外键列 -->
            <key column="person_id" not-null="true"/>
            <!-- 映射数组属性数据表的数组索引列 -->
            <list-index column="list_order"/>
            <!-- 映射保存数组元素的数据列 -->
            <element type="string" column="school_name"/>
        </array>
        
        <!-- 映射Set集合属性  无序-->
        <set name="schools3" table="school3">
            <!-- 映射集合属性数据表的外键列 -->
            <key column="person_id" not-null="true"/>
            <!-- 映射保存集合元素的数据列,增加非空约束 -->
            <element type="string" column="school_name" not-null="true"/>
        </set>
        
        <!-- 使用bag元素映射集合属性  无序-->
        <bag name="schools4" table="school4">
            <!-- 映射集合属性数据表的外键列 -->
            <key column="person_id" not-null="true"/>
            <!-- 映射保存集合元素的数据列 -->
            <element type="string" column="school_name" not-null="true"/>
        </bag>
        
        <!-- 映射Map集合属性 -->
        <map name="scores" table="score">
            <!-- 映射集合属性数据表的外键列 -->
            <key column="person_id" not-null="true"/>
            <!-- 映射集合属性数据表的Map key列 -->
            <map-key column="subject" type="string"/>
            <!-- 映射保存集合元素的数据列 -->
            <element column="grade" type="float"/>
        </map>
        
        <!-- 映射SortedSet集合属性,使用自然排序 增加sort="natural"定义-->
        <set name="trainings" table="training" sort="natural">
            <!-- 映射集合属性数据表的外键列 -->
            <key column="person_id" not-null="true"/>
            <!-- 映射保存集合元素的数据列,增加非空约束 -->
            <element type="string" column="training_name" not-null="true"/>
        </set>
    </class>
    
    <!-- 使用data-object元素定义数据库对象,必须将Hibernate配置文件里的hbm2ddl.auto改为create -->
    <database-object>
        <!-- 定义创建数据库对象的语句 -->
        <create>create table test(t_name varchar(255));</create>
        <!-- 让drop元素为空,不删除任何对象 -->
        <drop></drop>
        <!-- 指定仅对MySQL数据库有效 -->
        <dialect-scope name="org.hibernate.dialect.MySQLDialect"/>
        <dialect-scope name="org.hibernate.dialect.MySQLInnoDBDialect"/>
    </database-object>
</hibernate-mapping>

4. 测试类

package test;

import org.hibernate.Transaction;
import org.hibernate.Session;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

public class PersonManager{
    public static void main(String[] args){
        PersonManager mgr = new PersonManager();
        mgr.createAndStorePerson();
        HibernateUtil.sessionFactory.close();
    }
    //创建并保存Person对象
    private void createAndStorePerson(){
        Session session = HibernateUtil.currentSession();//打开线程安全的session对象
        Transaction tx = session.beginTransaction();//打开事务
        
        //创建Person对象
        Person yeeku = new Person();
        yeeku.setAge(29);
        yeeku.setName("crazyit.org");
        
        //创建List集合
        List<String> schools = new ArrayList<String>();
        schools.add("小学");
        schools.add("中学");
        yeeku.setSchools(schools);
        
        //创建数组对象
        String[] schools2 = new String[]{"小学2" , "中学2"};
        yeeku.setSchools2(schools2);
        
        //创建Set集合
        Set<String> s = new HashSet<String>();
        s.add("小学");
        s.add("中学");
        yeeku.setSchools3(s);
        
        //创建List集合
        Collection<String> schools4 = new ArrayList<String>();
        schools4.add("小学");
        schools4.add("中学");
        //设置Collection集合属性
        yeeku.setSchools4(schools4);
        
        //创建Map集合
        Map<String ,Float> m = new HashMap<String ,Float>();
        m.put("语文" , 67f);
        m.put("英文" , 45f);
        yeeku.setScores(m);
        
        //创建Set集合,其中11、22有序。在hbm文件中增加 order-by="training desc"时将逆序查出数据
        SortedSet<String> s2 = new TreeSet<String>();
        s2.add("11");
        s2.add("22");
        //设置Set集合属性
        yeeku.setTrainings(s2);
        
        session.save(yeeku);
        
        //为id为2的Person添加trainings属性,与前面添加的同样保持有序
        Person p = (Person)session.get(Person.class , 2);
        p.getTrainings().add("33");
        
        //此处如需查出list对象需在hbm文件中加入lazy="false"
        List<Person> listPersonList = session.createQuery("from Person").list();
        
        tx.commit();
        HibernateUtil.closeSession();
    }
}

5. 工具类

package test;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class HibernateUtil{
    public static final SessionFactory sessionFactory;
    static{
        try{
            //采用默认的hibernate.cfg.xml来启动一个Configuration的实例
            Configuration configuration = new Configuration().configure();
            
            //创建SchemaExport对象
            SchemaExport se = new SchemaExport(configuration);
            //设置输出格式良好的SQL脚本
            se.setFormat(true)
                //设置保存SQL脚本的文件名
                .setOutputFile("new.sql")
                //输出SQL脚本,并执行SQL脚本
                .create(true, true);
            
            //由Configuration的实例来创建一个SessionFactory实例
            sessionFactory = configuration.buildSessionFactory();
        }catch (Throwable ex){
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    //ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步    
    public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
    
    public static Session currentSession() throws HibernateException{
        Session s = session.get();
        //如果该线程还没有Session,则创建一个新的Session
        if (s == null){
            s = sessionFactory.openSession();
            //将获得的Session变量存储在ThreadLocal变量session里
            session.set(s);
        }
        return s;
    }
    
    public static void closeSession() throws HibernateException {
        Session s = session.get();
        if (s != null)
            s.close();
        session.set(null);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值