HibernateTemplate 提供了非常多的常用方法來完成基本的操作,比如增加、刪除、修改及查詢等操作,Spring 2.0 更增加對(duì)命名 SQL 查詢的支持,也增加對(duì)分頁的支持。大部分情況下,使用Hibernate 的常規(guī)用法,就可完成大多數(shù)DAO對(duì)象的 CRUD操作。
下面是 HibernateTemplate的常用方法。
delete(Object entity): 刪除指定持久化實(shí)例。
deleteAll(Collection entities): 刪除集合內(nèi)全部持久化類實(shí)例。
find(String queryString): 根據(jù) HQL 查詢字符串來返回實(shí)例集合。
findByNamedQuery(String queryName): 根據(jù)命名查詢返回實(shí)例集合。
load或get(Classentity Class,Serializable id): 根據(jù)主鍵加載特定持久化類的實(shí)例。
save(Object entity): 保存新的實(shí)例。
saveOrUpdate(Object entity): 根據(jù)實(shí)例狀態(tài),選擇保存或者更新。
update(Object entity): 更新實(shí)例的狀態(tài),要求entity 是持久狀態(tài)。
setMaxResults(intmax Results): 設(shè)置分頁的大小。
使用方法沒有多大的區(qū)別,只是使用時(shí)不用自己設(shè)置事務(wù),也不用關(guān)閉session。
我們使用HibernateTemplate,有一個(gè)很重要的原因就在于我們不想直接控制事務(wù),不想直接去獲取,打開Session,開始一個(gè)事務(wù),處理異常,提交一個(gè)事務(wù),最后關(guān)閉一個(gè)SessionHibernateTemplate 是Hibernate操作進(jìn)行封裝,我們只要簡(jiǎn)單的條用HibernateTemplate 對(duì)象,傳入hql和參數(shù),就獲得查詢接口,至于事務(wù)的開啟,關(guān)閉,都交給HibernateTemplate 對(duì)象來處理我們自己只專注于業(yè)務(wù),不想去作這些重復(fù)而繁瑣的操作。我們把這些責(zé)任全部委托給了 HibernateTemplate,然后使用聲明式的配置來實(shí)現(xiàn)這樣的功能。
如果我們通過類似getSession()這樣的方法獲得了Session,那就意味著我們放棄了上面所說的一切好處。
在使用Spring的時(shí)候 DAO類繼承了 HibernateDaoSupport 類又因?yàn)镠ibernateDaoSupport 類里面有個(gè)屬性 hibernateTemplate;所以就可以進(jìn)行設(shè)置注,也就是Spring的一大優(yōu)點(diǎn)面向切面式編程,進(jìn)行設(shè)置注入,在Tomcat啟動(dòng)的時(shí)候由 Tomcat 加載 ApplicationContext.xml,配置文件給 hibernateTemplate賦值,這樣的話就實(shí)現(xiàn)了,在使用某個(gè)對(duì)象之前不用給他實(shí)例化
實(shí)例:
hibernate自動(dòng)生成數(shù)據(jù)庫(kù)表的實(shí)體類
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.DriverjdbcUrl=jdbc:mysql://localhost:3306/mydbuser=rootpassword=minPoolSize=5maxPoolSize=20initialPoolSize=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" > <!-- 自動(dòng)掃描 --> <context:component-scan base-package="com.itnba.maya.entities"></context:component-scan> <!--加載資源對(duì)象 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 實(shí)例化c3p0對(duì)象 --> <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的聲明性事務(wù) --> <bean class="org.springframework.orm.hibernate5.HibernateTransactionManager" id="transactionManager"><!-- 要根據(jù)hibernate的版本配置 --> <property name="sessionFactory" ref="factory"></property> </bean> <!-- 配置事務(wù)屬性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 配置事務(wù)切入點(diǎn) --> <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//自動(dòng)掃描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(); }}
結(jié)果還是一樣的
聯(lián)系客服