[Spring] - Spring + Hibernate
Spring整合Hibernate,花了很长时间研究,其中碰到的比较多问题。
使用的是Spring3.0+Hibernate4.1.6,Spring整合最新版本的Hibernate4.5,会抛些奇奇怪怪的异常。这个官网有说明。
先上代码。
spring的xml配置:springContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.my.entity</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=false
hibernate.cache.provider_class=org.hibernate.cache.internal.NoCacheProvider
hibernate.current_session_context_class= org.springframework.orm.hibernate4.SpringSessionContext
</value>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <context:component-scan base-package="com.my" /> <tx:annotation-driven transaction-manager="txManager" />
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" read-only="true"/>
<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="create*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="remove*" propagation="REQUIRED" rollback-for="Exception"/>
</tx:attributes>
</tx:advice> <aop:config>
<aop:pointcut id="allServiceMethods" expression="execution(* com.my.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="allServiceMethods"/>
</aop:config> </beans>
逐一解释下这个XML,这是最关键的地方:
1、dataSource,这里所使用的是spring自带的org.springframework.jdbc.datasource.DriverManagerDataSource,但这个一般用于个人开发或非并发小项目是可以的,如果用于大型的项目,需要把它替换使用proxool。proxool与spring配置,可以网上搜索下。
2、sessionFactory,里头有个property值为packagesToScan,应该是hibernate所使用的annotation object(即POJO)。使用这个packagesToScan,会自动扫描代码,无需一个个写了。
3、txManager,这是transation管理bean,意思是把声明一个transation bean,以待注入。
4、<context:component-scan base-package="com.my" />,这句是spring使用annotation做注入,基于com.my的命名空间下的所有包和类扫描
5、<tx:annotation-driven transaction-manager="txManager" />,声明一个annotation的transation,让AOP使用。
6、txAdvice,声明一个spring AOP的advice,其意思是内容中定义的attributes对应的方法是否需要开启或禁用transation,以及rollback条件。
7、<aop:config/>是spring的AOP,将txAdvice切入到对应的pointcut中。
补充:
因为测试时使用的是MySql,在测试transation时,发现怎么也不能回滚。原来是MySql数据库要把表引擎修改为InnoDB类型才支持事务。之前使用的是绿色版的MySql,设置了很久也没设置成功,最后去官网下了个安装版的5.7版本,装上默就是InnoDB。-_-#
贴代码:
DAO:
package com.my.dao; import javax.annotation.Resource; import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository; import com.my.entity.Account; @Repository
public abstract class AccountDaoFactory {
@Resource
private SessionFactory sessionFactory; public SessionFactory getSessionFactory() {
return sessionFactory;
} public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
} /*
* Fin account by id
*/
public abstract Integer findAccount(Integer accountID); /*
* Add account
*/
public abstract Account add(String name); /*
* Delete account
*/
public abstract boolean delete(long id);
}
package com.my.dao.mysql; import org.hibernate.Session;
import org.springframework.stereotype.Repository; import com.my.entity.Account; @Repository(value = "accountDao")
public class AccountDao extends com.my.dao.AccountDaoFactory {
/*
* Find account by account id
*/
@Override
public Integer findAccount(Integer accountID) {
return accountID;
} @Override
public Account add(String name) {
Session session = super.getSessionFactory().getCurrentSession(); Account account = new Account();
account.setName(name);
session.save(account);
return account;
} @Override
public boolean delete(long id) {
Session session = super.getSessionFactory().getCurrentSession();
Account account = (Account) session.get(Account.class, id);
session.delete(account);
return true;
}
}
Service:
package com.my.service; import javax.annotation.Resource; import com.my.dao.AccountDaoFactory;
import com.my.entity.Account; public abstract class AccountServiceFactory {
@Resource(name="accountDao")
protected AccountDaoFactory accountDao; public AccountDaoFactory getAccountDAO() {
return accountDao;
} public void setAccountDAO(AccountDaoFactory accountDAO) {
this.accountDao = accountDAO;
} /*
* Find account by id
*/
public abstract Integer findAccount(Integer accountID); /*
* Add account
*/
public abstract Account add(String name); /*
* Delete account
*/
public abstract boolean delete(long id); /*
* Add and Delete account, transaction test.
*/
public abstract boolean addAndDelete(String name);
}
package com.my.service.mysql; import org.springframework.stereotype.Service; import com.my.entity.Account;
import com.my.service.AccountServiceFactory; @Service(value="accountService")
public class AccountService extends AccountServiceFactory { @Override
public Integer findAccount(Integer accountID) {
return accountDao.findAccount(accountID);
} @Override
public Account add(String name) {
return accountDao.add(name);
} @Override
public boolean delete(long id) {
return accountDao.delete(id);
} @Override
public boolean addAndDelete(String name) {
Account account = accountDao.add(name);
boolean result = accountDao.delete(account.getId());
return result;
} }
Controller:
package com.my.controller; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import com.my.entity.Account;
import com.my.service.AccountServiceFactory; @Controller
public class SpringController {
@Resource(name="accountService")
private AccountServiceFactory accountService; public AccountServiceFactory getAccount() {
return accountService;
} public void setAccount(AccountServiceFactory account) {
this.accountService = account;
} public Integer findAccount(Integer accountID){
return accountService.findAccount(accountID);
} public Account add(String name){
return accountService.add(name);
} public boolean delete(long id){
return accountService.delete(id);
} public boolean addAndDelete(String name){
return accountService.addAndDelete(name);
}
}
POJO entity:
package com.my.entity; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name = "account")
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id; @Column(name = "name", length = 200)
private String name; public long getId() {
return id;
} public void setId(long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
JUnit测试:
package com.my.controller; import static org.junit.Assert.*; import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringControllerTest {
private SpringController springController;
private ApplicationContext context; @Before
public void setUp() throws Exception {
context = new ClassPathXmlApplicationContext("springContext.xml");
// Use class load
springController = (SpringController)context.getBean(SpringController.class);
} @Test
public void testFindAccount() {
String name = "Robin";
boolean result = springController.addAndDelete(name);
assertTrue(result);
} }
输出结果:


项目结构:

Spring所需要用到的Jar包:

Hibernate4.1.6所需要用到的Jar包:

[Spring] - Spring + Hibernate的更多相关文章
- 【译】Spring 4 + Hibernate 4 + Mysql + Maven集成例子(注解 + XML)
前言 译文链接:http://websystique.com/spring/spring4-hibernate4-mysql-maven-integration-example-using-annot ...
- 【Java EE 学习 53】【Spring学习第五天】【Spring整合Hibernate】【Spring整合Hibernate、Struts2】【问题:整合hibernate之后事务不能回滚】
一.Spring整合Hibernate 1.如果一个DAO 类继承了HibernateDaoSupport,只需要在spring配置文件中注入SessionFactory就可以了:如果一个DAO类没有 ...
- spring和Hibernate整合
首先导入spring和Hibernate的jar包,以及JDBC和c3p0的jar包, 然后就是Hibernate的XML配置文件,不需要加入映射文件,这里用spring容器管理了. Hibernat ...
- 轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)
轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)(国家级奖项获奖作品升级版,四版累计印刷27次发行量超10万册的轻量级Jav ...
- spring整合hibernate的详细步骤
Spring整合hibernate需要整合些什么? 由IOC容器来生成hibernate的sessionFactory. 让hibernate使用spring的声明式事务 整合步骤: 加入hibern ...
- spring整合hibernate
spring整合hibernate包括三部分:hibernate的配置.hibernate核心对象交给spring管理.事务由AOP控制 好处: 由java代码进行配置,摆脱硬编码,连接数据库等信息更 ...
- spring 整合hibernate
1. Spring 整合 Hibernate 整合什么 ? 1). 有 IOC 容器来管理 Hibernate 的 SessionFactory2). 让 Hibernate 使用上 Spring 的 ...
- 总结Spring、Hibernate、Struts2官网下载jar文件
一直以来只知道搭SSH需要jar文件,作为学习的目的,最好的做法是自己亲自动手去官网下.不过官网都是英文,没耐心一般很难找到下载入口,更何 况版本的变化也导致不同版本jar文件有些不一样,让新手很容易 ...
- spring和hibernate整合时无法自动建表
在使用spring整合hibernate时候代码如下: <property name="dataSource" ref="dataSource" /> ...
- Spring整合Hibernate之AnnotationSessionFactoryBean与LocalSessionFactoryBean
spring集成hibernate由两种形式 1.继续使用Hibernate的映射文件*.hbm.xml 2.使用jpa形式的pojo对象, 去掉*.hbm.xml文件 一.继续使用Hibernate ...
随机推荐
- 【bzoj1084】最大子矩阵
题意 这里有一个n*m的矩阵,请你选出其中k个子矩阵,使得这个k个子矩阵分值之和最大.注意:选出的k个子矩阵不能相互重叠. \(1≤n≤100,1≤m≤2,1≤k≤10\) 分析 由于\(m\)只有两 ...
- 公用表表达式CTE
公用表表达式CTE表面上和派生表非常相似,看起来只是语义上的区别.但和派生表比较起来,CTE具有几个优势:第一,如果须要在一个CTE中引用另一个CTE,不需要像派生表那样嵌套,相反,只要简单地在同一个 ...
- 自定义控件之 Combobox
var ComboboxObj = function (id, url) { this.URL = url; //Ajax url this.ID = id; //combobox id this.m ...
- [css3]圆盘旋转动画
效果:打开只能看到logo,鼠标放上去,圆盘渐显放大旋转展示出来 知识点: [html+css] 1.logo水平垂直居中于圆盘内,用到的样式 position: absolute; left: 0; ...
- DeepLearning之路(一)逻辑回归
逻辑回归 1. 总述 逻辑回归来源于回归分析,用来解决分类问题,即预测值变为较少数量的离散值. 2. 基本概念 回归分析(Regression Analysis):存在一堆观测资料,希望获得数据内 ...
- 【个人使用.Net类库】(4)验证码类
验证码是现在管理系统常用的一种保护用户帐户信息的一种功能. 验证码可以有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登录尝试,虽然这可能是我们登录麻烦一点,但是对用户的密码安全来 ...
- MicroERP主要业务流程示意图
库存(进销存)管理 财务管理 固定资产管理 生产管理
- MVC记录
MVC这三层分别要完成哪些工作呢? 1.M层 模型(更多的是数据库模型) (1)创建数据库.创建相应的表 (2)完成针对数据库各个表的增.删.改.查的操作类 (3)映射数据库各个表的实体类(这个实体类 ...
- Redisson-Parent 2.5.0 和 3.0.0 发布
Redisson-Parent 2.5.0 和 3.0.0 发布了,Redisson 是基于 Redis 服务之上构建的分布式.可伸缩的 Java 数据结构,高级的 Redis 客户端. Rediss ...
- C#实现微信公众号群发消息(解决一天只能发一次的限制)
经过几天研究网上的代码和谢灿大神的帮忙,今天终于用C#实现了微信公众号群发消息,现在整理一下. 总体思路:1.首先必须要在微信公众平台上申请一个公众号. 2.然后进行模拟登陆.(由于我对http传输原 ...