时隔半年,再次发布配置类的相关Blog,因为左手受伤原因先做一个简述。

首先利用idea创建一个Spring+SpringMVC+Hibernate项目,注意的是因为我们要完全放弃Hibernate以及SessionFactory配置文件,所以Hibernate不需勾选配置文件。

全部三个框架都要用Annotation的方式简化配置。

按我的个人习惯,把配置文件集中在web.xml和applicationContext.xml(集成Spring和SpringMVC)

目录结构:

web.xml 几乎不需要修改,你也可以按自己的习惯调一下配置文件名,路径规则等。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

application.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config />
<context:component-scan base-package="com.cielo.*"/>
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="transactionManager"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.cielo.entity.HelloEntity</value>
<value>com.cielo.entity.TestEntity</value>
</list>
</property>
</bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/temp" />
<property name="username" value="cielo" />
<property name="password" value="hahaschool" />
</bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> </beans>

接下来我分别说明每一段的意义

<context:annotation-config />

加入此行可以引用@Transactional标签,后面讲解

<context:component-scan base-package="com.cielo.*"/>
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="transactionManager"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

这段为SpringMVC配置文件,可以参考上一篇博客。

接下来我讲解一下用Spring托管Hibernate的流程。

众所周知,当仅使用Hibernate操作数据库时,如果仅仅读数据库,需要调用Session,而如果需要写数据库,则还需调用Transaction。在纯Hibernate中,Session来自于手动生成的SessionFactory。而Transaction则作为Session的一个成员。

事实上,对于Spring托管的Hibernate项目也是如此。如果我们想使用HibernateTemplate,则需要构建这个Bean并向其注入一个SessionFactory(或者用Annotation去注入,但当你有多个dao时,这并不简洁)。

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

而构建这个SessionFactory,我们需要注入数据源dataSource或者用一个configuration文件去注入。由于我们不想使用hibernate.cfg.xml,我们选择用dataSource注入。由于dataSource由jdbc提供,本身不能像hibernate配置文件那样全面,还好Spring提供了其他的property便于配置。

 <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.cielo.entity.HelloEntity</value>
<value>com.cielo.entity.TestEntity</value>
</list>
</property>
</bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/temp" />
<property name="username" value="cielo" />
<property name="password" value="hahaschool" />
</bean>

最后,就是配置transaction了,我选择用Annotation的方法去配置,这样配置文件里就可以很简单

    <bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

当需要使用Transaction时,可以在方法名上标注@Transactional

一个使用例子:

@Repository
public class HelloDao{
@Autowired
public HibernateTemplate hibernateTemplate;
@Transactional
public void add(HelloEntity helloEntity){
hibernateTemplate.save(helloEntity);
}
}

关于hibernateTemplate的用法,可以直接查看接口定义,这样省去了大量的重复代码。

选择hibernateTemplate而不是直接继承HibernateSupportDao是为了保持耦合度不破坏,这也是目前更推荐的做法,实际上确实会相对麻烦一些。

最后放一个demo:HibernateTemplateDemo

Spring4托管Hibernate5并利用HibernateTemplate进行数据库操作的更多相关文章

  1. SSH框架的简化(struts2、spring4、hibernate5)

    目的: 通过对ssh框架有了基础性的学习,本文主要是使用注解的方式来简化ssh框架的代码编写. 注意事项: 1.本文提纲:本文通过一个新闻管理系统的实例来简化ssh框架的代码编写,功能包括查询数据库中 ...

  2. Spring4整合Hibernate5时不能自动生成表结构

    © 版权声明:本文为博主原创文章,转载请注明出处 1.问题描述: Spring4整合Hibernate5时,不再使用hibernate.cfg.xml,将其内容整合到Spring配置文件中,启动后不能 ...

  3. 利用SQl对数据库实行数据拆分与组合

    利用SQl对数据库实行数据拆分与组合实现提供以下几种方案: 方法一: WITH CTE AS (SELECT A.Id,A.[Uid],UserName FROM (SELECT A.[id], RE ...

  4. (喷血分享)利用.NET生成数据库表的创建脚本,类似SqlServer编写表的CREATE语句

    (喷血分享)利用.NET生成数据库表的创建脚本,类似SqlServer编写表的CREATE语句 在我们RDIFramework.NET代码生成器中,有这样一个应用,就是通过数据库表自动生成表的CREA ...

  5. 利用powerdesigner反向数据库结构,生成ER图

    参考月下狼~图腾~:<利用powerdesigner反向数据库结构,生成ER图> https://www.zybuluo.com/Jpz/note/123582 首先新建一个"P ...

  6. 利用python2.7正则表达式进行豆瓣电影Top250的网络数据采集及MySQL数据库操作

    转载请注明出处 利用python2.7正则表达式进行豆瓣电影Top250的网络数据采集 1.任务 采集豆瓣电影名称.链接.评分.导演.演员.年份.国家.评论人数.简评等信息 将以上数据存入MySQL数 ...

  7. PhoneGap,Cordova[3.5.0-0.2.6]:利用插件Cordova-SQLitePlugin来操作SQLite数据库

    在PhoneGap应用程序中,我们可以利用一款名叫Cordova-SQLitePlugin的插件来方便的操作基于浏览器内置数据库或独立的SQLite数据库文件,此插件的基本信息: 1.项目地址:htt ...

  8. 利用.NET生成数据库表的创建脚本,类似SqlServer编写表的CREATE语句

    利用.NET生成数据库表的创建脚本,类似SqlServer编写表的CREATE语句 (喷血分享)利用.NET生成数据库表的创建脚本,类似SqlServer编写表的CREATE语句 在我们RDIFram ...

  9. 【DG】利用闪回数据库(flashback)修复Failover后的DG环境

    利用闪回数据库(flashback)修复Failover后的DG环境 1.1  BLOG文档结构图 1.2  前言部分 1.2.1  导读和注意事项 各位技术爱好者,看完本文后,你可以掌握如下的技能, ...

随机推荐

  1. ubuntu中taglist和ctags安装使用

    1.使用命令安装ctags: 2.安装taglist 下载: http://vim.sourceforge.net/scripts/download_script.php?src_id=6416 拷贝 ...

  2. window环境下搭建react native及相关插件

    可以先浏览一下中文翻译的开发文档具体了解一下关于React Native,想要查看官方文档可以点http://facebook.github.io/react-native/docs/getting- ...

  3. Linux用户配置文件(第二版)

    /etc/passwd文件剖析 文件格式: root:x:0:0:root:/root:/bin/bash 用户名:密码位:UID:GID[缺省组ID]:注释性的描述信息:宿主目录:shell[7部分 ...

  4. 如何写好一个UITableView(完整版)

    本文是直播分享的简单文字整理,直播共分为上.下两部分.第一部分:优酷 Or YouTube,第二部分:优酷 Demo 地址:KtTableView 如果你觉得UITableViewDelegate和U ...

  5. LeetCode之“动态规划”:Best Time to Buy and Sell Stock I && II && III && IV

    Best Time to Buy and Sell Stock I 题目链接 题目要求: Say you have an array for which the ith element is the ...

  6. Media Player Classic - HC 源代码分析 4:核心类 (CMainFrame)(3)

    ===================================================== Media Player Classic - HC 源代码分析系列文章列表: Media P ...

  7. Android开发技巧——自定义控件之自定义属性

    Android开发技巧--自定义控件之自定义属性 掌握自定义控件是很重要的,因为通过自定义控件,能够:解决UI问题,优化布局性能,简化布局代码. 上一篇讲了如何通过xml把几个控件组织起来,并继承某个 ...

  8. 安卓系统底层C语言算法之测试参数是几个long型的算法

    #include <stdio.h> #define BITS_PER_LONG (sizeof(unsigned long) * 8) //求一个数x是几个long的长度 #define ...

  9. LeetCode(29)-Plus One

    题目: Given a non-negative number represented as an array of digits, plus one to the number. The digit ...

  10. 线程ava.lang.OutOfMemoryError: unable to create new native thread

    近日开发遇到多线程的问题: java.lang.OutOfMemoryError: unable to create new native thread Exception in thread &qu ...