Spring4學習(四)Spring4中整合Hibernate4

iteye_17429發表於2016-12-26

        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));
	}

}

 

相關文章