Spring4学习(四)Spring4中整合Hibernate4

        Spring4.2.8版本官方文档说明,这一版本的Spring强烈建议使用Hibernate5,而且Hibernate3.6版本以上才支持,低版本的Hibernate只好选择与之相适应的Spring版本,此例中采用Hibernate4.3.11版本。

        Hibernate配置文件,由于使用Spring,数据库连接池等配置可以有选择配置到spring文件中,这样Hibernate配置文件就可以尽可能简化。

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
		<!-- <property name="current_session_context_class">jta</property> -->
		
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
        
		<!-- maping 可以在spring中配置 -->
        <!-- <mapping resource="conf/hibernate/domain/Music.hbm.xml"/> -->
	
		<!-- <mapping class="org.lian.domain.Group" /> -->
		
    </session-factory>

</hibernate-configuration>

        需要指出的是上面的hibernate配置文件是可选的,可以完全将配置文件内容配置到spring文件。

        Spring配置文件  分两步配置  第一配置数据源 第二配置SessionFactory 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
	<!-- 使用spring注解  -->
   <!--  <context:annotation-config/> -->
    <!-- 下面的配置告诉spring容器自动scanner用注解标注bean -->
   <context:component-scan base-package="org.lian"/>
<!--配置数据源  -->
	<!-- <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean> -->
    <!-- 配置Druid数据库连接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">   
	    <!-- 基本属性 url、user、password -->  
	    <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>     
	    <!-- 配置初始化大小、最小、最大 -->  
	    <property name="initialSize" value="1" />  
	    <property name="minIdle" value="1" />   
	    <property name="maxActive" value="20" />  
	   
	    <!-- 配置获取连接等待超时的时间 -->  
	    <property name="maxWait" value="60000" />  
	   
	    <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->  
	    <property name="timeBetweenEvictionRunsMillis" value="60000" />  
	   
	    <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->  
	    <property name="minEvictableIdleTimeMillis" value="300000" />  
	    
	    <property name="validationQuery" value="SELECT 'x'" />  
	    <property name="testWhileIdle" value="true" />  
	    <property name="testOnBorrow" value="false" />  
	    <property name="testOnReturn" value="false" />  
	   
	    <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->  
	    <property name="poolPreparedStatements" value="true" />  
	    <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />  
	   
	    <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->  
	    <property name="filters" value="stat" />   
	</bean>
	<!-- 配置Hibernate SessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="false">
        <!-- 注入datasource,给sessionfactoryBean内setdatasource提供数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:conf/hibernate/hibernate.cfg.xml"></property>
        <!-- //加载实体类的映射文件位置及名称 -->
        <property name="mappingLocations" value="classpath:conf/hibernate/domain/*.hbm.xml"></property>
        
        <property name="packagesToScan" value="org.lian.**.domain"></property>
    	
    </bean>  
      
    <context:property-placeholder location="classpath*:conf/datasource/jdbc.properties"/>
</beans>

         Dao层中使用SessionFactory

@Repository("musicH4Dao")
public class MusicH4DaoImpl implements MusicDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public String get(Music music) {
		Session session = sessionFactory.openSession();
		try {
			String sql = "from Music as music where music.id = :id ";
			Music bean = (Music) session.createQuery(sql)
					.setParameter("id", music.getId()).uniqueResult();
			return GsonUtil.getInstance().convertToJson(bean);
		} finally {
			session.close();
		}
	}

	@Override
	public String list(Music music) {
		String sql = "from Group as group where group.id = :id ";
		Session session = sessionFactory.openSession();
		try {
			@SuppressWarnings("unchecked")
			List<Group> list = session.createQuery(sql)
					.setParameter("id", music.getId()).list();
			return GsonUtil.getInstance().convertToJson(list);
		} finally {
			session.close();
		}
	}

	

}

     测试代码

public class Main {
	public static void main(String[] args) {
		String classPath = "classpath*:conf/spring/app_hibernate.xml";
		ApplicationContext context = new ClassPathXmlApplicationContext(classPath);
		MusicDao dao = context.getBean("musicH4Dao", MusicDao.class);
		Music music = new Music();
		music.setId("123");
		System.out.println(dao.get(music));
		music.setId("297ed3f359058806015905880d110000");
		System.out.println(dao.list(music));
	}

}

猜你喜欢

转载自blog-chen-lian.iteye.com/blog/2347383