HibernateTemplate的使用
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();
} }
结果还是一样的

HibernateTemplate的使用的更多相关文章
- SSH实战 · 用spring框架下的hibernatetemplate的get方法出现的问题
用get方法查询: return this.getHibernateTemplate().get(Product.class, pid); 出现错误为:id to load is requi ...
- Hibernate整合Spring异常'sessionFactory' or 'hibernateTemplate' is required
今日在写GenericDao时,发现了一个异常,内容如下: org.springframework.beans.factory.BeanCreationException: Error creatin ...
- java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required 严重: Exceptio ...
- HibernateTemplate的一些常用方法总结
1:get/load存取单条数据 public Teacher getTeacherById(Long id) { return (Teacher)this.hibernateTemplate.get ...
- 'sessionFactory' or 'hibernateTemplate' is required解决方法
这种情况就是在通过spring配置hibernate4的时候(注意,这里是hibernate4不是hibernate3,hibernate3的),使用的是HibernateDaoSupport的这种方 ...
- HibernateTemplate和HibernateDaoSupport(spring注入问题)
HibernateTemplate HibernateTemplate是spring提供的一个就hibernate访问持久层技术而言.支持Dao组件的一个工具.HibernateTemplate提供持 ...
- hibernateTemplate.find或hibernateTemplate.save()执行操作没有反应,但是有sql语句
今天使用ssh框架搭建的项目,进行查询和保存操作,使用的是 public Collection<T> getAllEntry() { return this.hibernateTempla ...
- 。。。HibernateTemplate与Session。。。
今天在学习Spring框架的时候,突然发现了这个类----HibernateTemplate,这个类与Session一开始认为是差不多的,这个HibernateTemplate类对象拥有Session ...
- 集成Spring后HibernateTemplate实现分页
spring 整合 hibernate 时候用的 HibernateTemplate 不支持分页,因此需要自己包装一个类进行分页,具体实现如下...使用spring的hibernateTemplate ...
- 在HibernateTemplate里执行Sql语句
如下所示只能执行非Select语句: public static void executeSQL(HibernateTemplate hibernateTemplate, String sql) { ...
随机推荐
- Java Web(十二) commons-fileupload上传下载
今天心态正常...继续努力.. --WH 一.上传原理和代码分析. 上传:我们把需要上传的资源,发送给服务器,在服务器上保存下来. 下载:下载某一个资源时,将服务器上的该资源发送给浏览器. 难点:服务 ...
- 第十六篇 基于Bootstarp 仿京东多条件筛选插件的开发(展示上)
这几天学习Bootstrap,本来是两年前的用的东西,现在又重新拾起来,又有很多重新的认识,看了Bootstrap的样式偏多,插件现在还没有学习到几个,也有写几个插件自己用的想法.正好工作上也会用到, ...
- Bat再次小试
继<Bat小试牛刀>之后,今天又需要一个小的bat文件.需求是这样的,有一个windows服务(服务名:xxxx,进程映像名:xxxx.exe)被数据库拖慢了,但目前又没时间调整代码,所以 ...
- CSS3形变——transform与transform-origin画时钟
css3属性transform和transform-origin"画"时钟 效果图 前言 八哥:哈喽,大家好!好攻城狮就是我就是你们的小八,欢迎收听你的月亮...哦不,是很高兴与你 ...
- BOM基础(二)
跟DOM一样,BOM其实也是由很多的API组成. 不过对于BOM来说,最痛苦的不是不记得API,而是明明记得这个这个API,却没有考虑到它的兼容性. 之前的文章中讲到了offset系列的属性,他的宽高 ...
- 用C#来学习唐诗三百首
Begin 最近把项目做完了,闲来无事,就想做点好玩的事情,刚好前几天下载了[唐诗三百首]和[全唐诗]这两个txt文件,正好用C#来整理一下. [唐诗三百首]文件格式 [全唐诗]文件格式 目标 将每一 ...
- WeMall微信商城签到插件Sign的主要源码
WeMall微信商城源码签到插件Sign,用于商城的签到系统,分享了部分比较重要的代码,供技术员学习参考 AdminController.class.php <?php namespace Ad ...
- c# 将匿名类或者集合转Json格式数据一些方法
要说写这个功能呢也是因为工作需要,白天呢上班写个Web页面需要ajax请求后台并将数据以Json格式传会前端,由于公司特殊性吧,不能连外网(很苦比).所以只有等到晚上回家上网边查边写! public ...
- Web 页面测试总结—控件类
web端页面测试,最常见的是基本控件的测试,只有了解常见的控件和其测试方法,才能掌握测试要点,避免漏测情况发生.根据日常工作总结,将控件和常见逻辑集合在一起,总结了几个控件类测试查场景如下. 导航条 ...
- 10分钟精通SharePoint - SharePoint定位
平台 – "一栋楼房的框架结构" 扩展 – "用户可以根据自己需要随意装修房间"集成 – "插拔式的系统集成能力"业务– "既是全 ...