hibernate的搭建(包括Spring集成)和调用
2012-12-25 00:11 eoeAndroid社区 阅读(131) 评论(0) 编辑 收藏 举报一.非Spring集成的搭建和使用
1.首先我们得下载Hibernate的需要的jar包(通常情况下导入hibernate3.jar和require文件夹里面的所有jar包).
hibernate3.jar: 这个是Hibernate的核心包,所以是必须的jar包.
cglib-2.2.jar: cglig库,Hibernate用它来实现PO字节码的动态生成,非常核心的包,所以也是必须的包
dom4j.jar
dom4j是一个Java的XML API,类似于jdom,用来读写XML文件的。dom4j是一个非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件,可以在SourceForge上找到它。在IBM developerWorks上面可以找到一篇文章,对主流的Java XML API进行的性能、功能和易用性的评测,dom4j无论在那个方面都是非常出色的。我早在将近两年之前就开始使用dom4j,直到现在。如今你可以看到越来越多的Java软件都在使用dom4j来读写XML,特别值得一提的是连Sun的JAXM也在用dom4j。这是必须使用的jar包,Hibernate用它来读写配置文件。
commons-collections.jar: Apache Commons包中的一个,包含了一些Apache开发的集合类,功能比java.util.*强大。必须使用的jar包。
javassist-3.12.0.GA.jar: 这个包也是必须的.
jta-1.1.jar: 当使用JTA规范时,必须加入,JTA全称是 Java Transaction API (java 事务 API),一般情况下也是必须的.
slf4j-api-1.6.1.jar: 这个包是必须的,因为在Hibernate的核心包中多处用到了,比如Configuration.class中用到了.
slf4j-nop-1.6.1.jar: 这个包是slf4j的实现类,所以也是必须的,注意实现类得和slf4j的版本要匹配.
hibernate-jpa-2.0-api-1.0.1.Final.jar: Hibernate使用Annotation(注解)需加,所以说如果不用Annotation的话就不用加的.
(以上的包是Hibernate3.5以上的版本)
2.编写hibernate.cfg.xml配置文件到src目录下
- <?xml version='1.0' encoding='GBK'?>
- <!DOCTYPE hibernate-configuration
- PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <!-- 是否将运行期生成的SQL输出到日志以供调试 -->
- <property name="show_sql">true</property>
- <!-- SQL方言,这里设定的是MySQL -->
- <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
- <!-- JDBC驱动程序 -->
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
- <!-- JDBC URL, "?useUnicode=true&characterEncoding=GBK" 表示使用GBK进行编码 -->
- <property name="connection.url">
- jdbc:mysql://localhost:3306/HibernateTest?useUnicode=true&characterEncoding=GBK
- </property>
- <!-- 数据库用户名 -->
- <property name="connection.username">root</property>
- <!-- 数据库密码 -->
- <property name="connection.password">javamxj</property>
- <!-- 是否在控制台打印sql语句(true/false) -->
- <propertyname="show_sql">true</property>
- <!-- 指定User的映射文件 -->
- <mapping resource="javamxj/hibernate/User.hbm.xml"/>
- </session-factory>
- </hibernate-configuration>
connection.url:连接数据库的URL
connection.username:数据库登录的用户名
connection.password:用户登录数据库的密码
connection.pool_size:数据库连接池的大小
dialect:数据库所使用的方言(hibernate支持几乎所有数据库的方言)
cache.provider_class:设置二级缓存的启用/禁用
current_session_context_class:为"当前" Session指定一个(自定义的)策略
show_sql:是否在控制台打印sql语句(true/false)
format_sql:在日志或控制台输出更漂亮的sql语句(true/false)
3.创建持久类和对应的xml映射文件
持久类
- public class User {
- private int id;
- private String username;
- private String password;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- }
映射文件
- <?xml version="1.0" encoding="GBK"?>
- <!DOCTYPE hibernate-mapping
- PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
- <hibernate-mapping>
- <class name="javamxj.hibernate.User" table="UserTable">
- <id name="id">
- <generator class="assigned" />
- </id>
- <property name="username" />
- <property name="password" />
- </class>
- </hibernate-mapping>
hibernate.cfg.xml里的配置
- <!-- 指定User的映射文件 -->
- <mapping resource="javamxj/hibernate/User.hbm.xml"/>
4.创建hibernate工具类(获取session)
package util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the current
* thread of execution. Follows the Thread Local Session pattern, see
* {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file. Location should be on the classpath
* as Hibernate uses #resourceAsStream style lookup for its configuration
* file. The default classpath location of the hibernate config file is in
* the default package. Use #setConfigFile() to update the location of the
* configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "./hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize the
* <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
5.使用
protected Object get(Class clazz,Integer id) { Session session = HibernateSessionFactory.getSession(); return session.get(clazz, id); } // 增加操作 protected void save(Object entity) { Session session = HibernateSessionFactory.getSession(); Transaction tr = null; try { tr = session.beginTransaction(); session.save(entity); tr.commit(); } catch (JDBCException ex) { ex.printStackTrace(); if (tr != null) tr.rollback(); }finally{ //HibernateSessionFactory.closeSession(); } }
二.Spring集成的搭建和使用
1.导入jar包同上
2.在spring的配置文件中加入transactionContext.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- 指定Spring配置文件的Schema信息 --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" default-autowire="byName"> <!-- 定义数据源Bean,使用C3P0数据源实现 --> <!-- 设置连接数据库的驱动、URL、用户名、密码 连接池最大连接数、最小连接数、初始连接数等参数 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="com.mysql.jdbc.Driver" p:jdbcUrl="jdbc:mysql://localhost:3306/sshweb?useUnicode=true&characterEncoding=utf-8" p:user="root" p:password="123456" p:maxPoolSize="40" p:minPoolSize="1" p:initialPoolSize="1" p:maxIdleTime="20"/> <!-- 定义Hibernate的SessionFactory --> <!-- 依赖注入数据源,注入正是上面定义的dataSource --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" p:dataSource-ref="dataSource"> <!-- mappingResouces属性用来列出全部映射文件 --> <!--<property name="mappingResources"> <list> <value>com/model/Novel.hbm.xml</value> <value>com/model/NovelType.hbm.xml</value> </list> </property>--> <property name="mappingLocations"> <list> <value>classpath:com/model/mapping/*.hbm.xml</value> </list> </property> <!-- 定义Hibernate的SessionFactory的属性 --> <property name="hibernateProperties"> <!-- 指定数据库方言、是否自动建表 是否生成SQL语句等 --> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.connection.characterEncoding=UTF-8 <!-- hibernate.format_sql=true--> <!-- #开启二级缓存--> <!-- hibernate.cache.use_second_level_cache=true--> <!-- #设置二级缓存的提供者--> <!-- hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider--> </value> </property> </bean> <!-- 配置Hibernate的局部事务管理器,使用HibernateTransactionManager类 --> <!-- 该类实现PlatformTransactionManager接口,是针对Hibernate的特定实现--> <!-- 并注入SessionFactory的引用 --> <bean id="transactionManager" class= "org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory"/> <!-- 配置事务增强处理Bean,指定事务管理器 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- 用于配置详细的事务语义 --> <tx:attributes> <!-- 所有以'get'开头的方法是read-only的 --> <tx:method name="get*" read-only="true"/> <!-- 其他方法使用默认的事务设置 --> <tx:method name="*"/> </tx:attributes> </tx:advice> <aop:config proxy-target-class="true"> <!-- 配置一个切入点,匹配empManager和mgrManager 两个Bean的所有方法的执行 --> <aop:pointcut id="pointcut" expression="execution(* com.service.*.*(..))" /> <!-- 指定在leePointcut切入点应用txAdvice事务增强处理 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/> </aop:config> <!-- 装配HibernateTemplate实例 <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <constructor-arg ref="sessionFactory"/> </bean> --> </beans>
3.创建持久类和映射文件同上
4.操作方法
继承extends HibernateDaoSupport ,使用getHibernateTemplate()
@SuppressWarnings("unchecked") public class BaseDao extends HibernateDaoSupport { /** * 获取类 * * @param clazz * @param id * @return */ protected Object get(Class clazz, Integer id) { try { return getHibernateTemplate().get(clazz, id); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 更新操作 * * @param entity */ protected void save(Object entity) { try { getHibernateTemplate().save(entity); } catch (Exception e) { e.printStackTrace(); } }