您的位置:首页 > 其它

浅谈:Hibernate中HibernateUtil工具类

2016-05-07 23:00 399 查看
首先我们需要知道为什么咱们要创建Hibernate工具类

一些固定而且经常使用的步骤我们期望做成一个工具类,以后再需要重复步骤时咱们仅需要引用此工具类就可以,从而避免了一直创建重复代码。比如加载数据库的驱动等,这里Hibernate中我们每个主程序都需要加载hibernate.cfg.xml文件、创建SessionFactory对象、创建Session对象、关闭session。这些都是固定化的步骤,因此我们将它们写在工具类HibernateUtil中,以后咱们直接引用此文件创建各对象即可,大大减少了代码量,提高了代码复用性。

下面以Hibernate映射Map集合来说Hibernate工具类 一些解释都已经加入代码块的注解中

一:PersonMap.java

<span style="font-family:KaiTi_GB2312;font-size:18px;">package com.mao;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapKeyClass;
import javax.persistence.MapKeyColumn;
import javax.persistence.Table;
@Entity
@Table(name="personMap_inf")
public class PersonMap {
@Id
@Column(name="person_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String name;
private String age;
@ElementCollection(targetClass=Float.class)
@CollectionTable(name="score_inf",joinColumns=@JoinColumn(name="person_id",nullable=false))
//映射保存Map key的数据列
@MapKeyColumn(name="subject_name")
//指定Map key的类型为String类型
@MapKeyClass(String.class)
//映射保存 Map value的数据列
@Column(name="mark")
private Map<String,Float>scores=new HashMap<>();
//省略全部属性的set get方法</span>


二:工具类HibernateUtil

package com.mao;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.*;
import org.hibernate.boot.registry.*;
/**
* Description:
* @author  VipMao
* @version  1.0
*/

/**
* 该工具类提供了一个属性:SessionFactory sessionFactory
* 并创建了sessionFactory 将它设置成static 这样其他程序就可以直接通过此工具类引用
* 提供了二个方法:
* 1:通过线程创建Session-->currentSession()
* 2:关闭Session-->closeSession()
* 需要在主类中手动关闭sessionFactory
*/
public class HibernateUtil
{
public static final SessionFactory sessionFactory;
//创建sessionFactory
static
{
try
{
// 采用默认的hibernate.cfg.xml来启动一个Configuration的实例
Configuration cfg = new Configuration()
.configure();
// 以Configuration实例来创建SessionFactory实例
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
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>();
//创建Session
public static Session currentSession()
throws HibernateException
{
//通过线程对象.get()方法安全创建Session
Session s = session.get();
// 如果该线程还没有Session,则创建一个新的Session
if (s == null)
{
s = sessionFactory.openSession();
// 将获得的Session变量存储在ThreadLocal变量session里
session.set(s);
}
return s;
}
//关闭Session
public static void closeSession()
throws HibernateException
{
Session s = session.get();
if (s != null)
s.close();
session.set(null);
}
}


该工具类提供了一个属性:SessionFactory sessionFactory , 并将创建sessionFactory写在了static代码块里, 这样其他程序就可以直接通过HibernateUtil.sessionFactory引用,而不是再通过一系列的代码创建SessionFactory对象。

另外工具类还提供了二个方法:

1:通过线程创建Session-->currentSession()

工具类中通过ThreadLocal创建Session ,可以隔离多个线程的数据共享

2:关闭Session-->closeSession()

可以看出工具类将创建SessionFactory对象、Session对象以及关闭Session放在了不同的代码块以及方法里,这样以后咱们需要创建什么或者关闭什么直接通过HibernateUtil.XXX实现即可,大大缩减了代码量,提高代码复用性。

三:Hibernate主程序 PersonManagerMap.java

<span style="font-family:KaiTi_GB2312;font-size:18px;">package com.mao;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class PersonManagerMap
{
public static void main(String[] args)
{
PersonManagerMap mgr = new PersonManagerMap();
mgr.createAndStorePerson();
//通过工具类关闭sessionFactory
HibernateUtil.sessionFactory.close();
}

private void createAndStorePerson()
{
// 打开线程安全的Session对象
Session session = HibernateUtil.currentSession();
// 打开事务
Transaction tx = session.beginTransaction();
// 创建Person对象
PersonMap person = new PersonMap();
person.setName("VipMao");
person.setAge("24");
// 向person的Map集合属性中添加key-value对
person.getScores().put("语文" , 90f);
person.getScores().put("英文" , 95f);
session.save(person);
tx.commit();
//通过工具类关闭Session
HibernateUtil.closeSession();
}

}

</span>


可以看出上面的创建Session对象、关闭Session等都是通过工具类完成的,我们已经在工具类中创建了SessionFactory sessionFactory,所以只要工具类在项目中,我们就可以直接通过HibernateUtil.sessionFactory使用(因为工具类已经将它设置成静态),非常方便。

四:配置文件hibernate.cfg.xml

<span style="font-family:KaiTi_GB2312;font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.characterEncoding">utf-8</property>
<!-- 指定连接池最大连接数 -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- 指定连接池最小连接数 -->
<property name="hibernate.c3p0.min_size">1</property>
<!-- 指定连接池里连接超时时长 -->
<property name="hibernate.c3p0.timeout">5000</property>
<!-- 指定连接池里做大缓存多少个Statement对象 -->
<property name="hibernate.c3p0.max_statements">50</property>
<!-- 是否根据需要自动建表 -->
<property name="hbm2ddl.auto">update</property>
<!-- 是否显示sql语句 -->
<property name="show_sql">true</property>
<!-- 将SQL脚本进行格式化后再输出 -->
<property name="hibernate.format_sql">true</property>
<!-- 设置连接数据库所使用的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 罗列所有持久化类名 -->
<mapping class="com.mao.PersonMap"/>

</session-factory>
</hibernate-configuration>
</span>


五:运行结果





可以看出,与不使用工具类一样,同样实现了数据库中映射Map集合。

这仅仅是我的Hibernate工具类,当然大家可以根据自己的项目需求改写自己的工具类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: