HibernateTemplate 提供了非常多的常用方法來完成基本的操作,比如增加、刪除、修改及查詢等操作,Spring 2.0 更增加對命名 SQL 查詢的支持,也增加對分頁的支持。大部分情況下,使用Hibernate 的常規用法,就可完成大多數DAO對象的 CRUD操作。
下面是 HibernateTemplate的常用方法。
delete(Object entity): 刪除指定持久化實例。
deleteAll(Collection entities): 刪除集合內全部持久化類實例。
find(String queryString): 根據 HQL 查詢字符串來返回實例集合。
findByNamedQuery(String queryName): 根據命名查詢返回實例集合。
load或get(Classentity Class,Serializable id): 根據主鍵加載特定持久化類的實例。
save(Object entity): 保存新的實例。
saveOrUpdate(Object entity): 根據實例狀態,選擇保存或者更新。
update(Object entity): 更新實例的狀態,要求entity 是持久狀態。
setMaxResults(intmax Results): 設置分頁的大小。
HibernateTemplate與session的區別
使用方法沒有多大的區別,只是使用時不用自己設置事務,也不用關閉session。
我們使用HibernateTemplate,有一個很重要的原因就在於我們不想直接控制事務,不想直接去獲取,打開Session,開始一個事務,處理異常,提交一個事務,最后關閉一個SessionHibernateTemplate 是Hibernate操作進行封裝,我們只要簡單的條用HibernateTemplate 對象,傳入hql和參數,就獲得查詢接口,至於事務的開啟,關閉,都交給HibernateTemplate 對象來處理我們自己只專注於業務,不想去作這些重復而繁瑣的操作。我們把這些責任全部委托給了 HibernateTemplate,然后使用聲明式的配置來實現這樣的功能。
如果我們通過類似getSession()這樣的方法獲得了Session,那就意味着我們放棄了上面所說的一切好處。
在使用Spring的時候 DAO類繼承了 HibernateDaoSupport 類又因為HibernateDaoSupport 類里面有個屬性 hibernateTemplate;所以就可以進行設置注,也就是Spring的一大優點面向切面式編程,進行設置注入,在Tomcat啟動的時候由 Tomcat 加載 ApplicationContext.xml,配置文件給 hibernateTemplate賦值,這樣的話就實現了,在使用某個對象之前不用給他實例化
實例:
hibernate自動生成數據庫表的實體類

hibernate.cfg.xml
<?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> <!-- <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/mydb</property> <property name="hibernate.connection.username">root</property> --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <!-- <mapping resource="com/itnba/maya/entities/Family.hbm.xml"/> <mapping resource="com/itnba/maya/entities/Info.hbm.xml"/> <mapping resource="com/itnba/maya/entities/Nation.hbm.xml"/> <mapping resource="com/itnba/maya/entities/Title.hbm.xml"/> <mapping resource="com/itnba/maya/entities/Work.hbm.xml"/> --> </session-factory> </hibernate-configuration>
db.properties文件
driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/mydb user=root password= minPoolSize=5 maxPoolSize=20 initialPoolSize=5
Spring的beans.xml文件
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd" > <!-- 自動掃描 --> <context:component-scan base-package="com.itnba.maya.entities"></context:component-scan> <!--加載資源對象 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 實例化c3p0對象 --> <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource"> <property name="driverClass" value="${driverClass}"></property> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> <property name="minPoolSize" value="${minPoolSize}"></property> <property name="maxPoolSize" value="${maxPoolSize}"></property> <property name="initialPoolSize" value="${initialPoolSize}"></property> </bean> <!-- 配置Hibernate的SessionFactory --> <bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" id="factory"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <property name="mappingLocations" value="com/itnba/maya/entities/*.hbm.xml"></property> </bean> <!-- 配置spring的聲明性事務 --> <bean class="org.springframework.orm.hibernate5.HibernateTransactionManager" id="transactionManager"><!-- 要根據hibernate的版本配置 --> <property name="sessionFactory" ref="factory"></property> </bean> <!-- 配置事務屬性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 配置事務切入點 --> <aop:config> <aop:pointcut expression="execution(* com.itnba.maya.entities.*.*(..))" id="pointCut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/> </aop:config> <!-- 配置 HibernateTemplate --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> <property name="sessionFactory" ref="factory"></property> </bean> </beans>
InfoDao類
package com.itnba.maya.entities; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.stereotype.Repository; @Repository//自動掃描 public class InfoDao { @Autowired//注解 private HibernateTemplate ht; public void select() { Info data =ht.get(Info.class, "p005"); System.out.println(data.getName()); } /* 之前用是下面的之中寫法 private SessionFactory factory; public Session getSession(){ return factory.getCurrentSession(); } public void select() { Info data = getSession().get(Info.class, "p005"); System.out.println(data.getName()); } */ }
main方法類
package com.itnba.maya.entities; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) throws SQLException { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); InfoDao data=(InfoDao) context.getBean("infoDao"); data.select(); } }
結果還是一樣的

