[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 ...
随机推荐
- IntelliJ IDEA 设置代码提示或自动补全的快捷键
IntelliJ IDEA 设置代码提示或自动补全的快捷键 点击 文件菜单(File) –> 点击 设置(Settings- Ctrl+Alt+S), –> 打开设置对话框. 在左侧的 ...
- Spring3博客(内含ppt和代码的github地址)
我们的Spring3相当于给我们的项目来了一次大整容!因为上次演示的时候,老师给我们的建议是做得小清新一点,所以我们项目改动挺大的. PPT地址:http://files.cnblogs.com/fi ...
- wpf中UserControl的几种绑定方式
我们经常会抽取一些可重用的控件,某个属性是否需要重用,直接决定了这个属性的绑定方式. 1.完全不可重用的控件 有一些与业务强相关的控件,它们的属性完全来自ViewModel,越是相对复杂的控件,越容易 ...
- Windows 下java环境变量的配置(Windows7 ,8,8.1,10)
Windows 下java环境变量的配置 在“系统”面板的左上角选择“高级系统设置”,在弹出的系统属性中选择”高级“项,然后点击右下角的“环境变量(N)...”,就此进入JAVA环境变量的配置. 如果 ...
- JEECMS v8 发布,java 开源 CMS 系统
JEECMSv8 是国内java开源CMS行业知名度最高.用户量最大的站群管理系统,支持栏目模型.内容模型交叉自定义.以及具备支付和财务结算的内容电商为一体: 对于不懂技术的用户来说,只要通过后台的 ...
- C# winform程序如何打包64位安装程序
故事背景: 原来在客户电脑上工作的很正常的程序,在客户将其操作系统从32位换为64位之后,出现了不能正常使用的问题. --------------------------- 解决办法: 1:将解决方案 ...
- [Python模式]策略模式
策略模式 定义了算法族,分别封装起来,让它们之间可以互相替换.此模式让算法的变化独立于使用算法的客户. 作为动态语言,Python实现策略模式非常容易,只要所有算法提供相同的函数即可. import ...
- ubuntu 14.04 安装docker
常会遇到的问题就是网络的问题,如访问https://get.docker.io/ 遇到403的问题:总结一下最简单的几条命令: $ sudo apt-get install apt-transport ...
- 黑马程序员——【Java基础】——泛型、Utilities工具类、其他对象API
---------- android培训.java培训.期待与您交流! ---------- 一.泛型 (一)泛型概述 1.泛型:JDK1.5版本以后出现的新特性,用于解决安全问题,是一个类型安全机制 ...
- Sublime Text 配置
Sublime Text 配置 1.键盘映射 映射成emacs的键盘方式: Preferences --> Key Bounding - user:然后复制如下配置信息(注意取消前缀“...-- ...