第十三章spring应用spring管理hibernate.docx
《第十三章spring应用spring管理hibernate.docx》由会员分享,可在线阅读,更多相关《第十三章spring应用spring管理hibernate.docx(26页珍藏版)》请在冰豆网上搜索。
![第十三章spring应用spring管理hibernate.docx](https://file1.bdocx.com/fileroot1/2022-11/24/85da7b9e-04ce-469c-8d68-a7afbda10935/85da7b9e-04ce-469c-8d68-a7afbda109351.gif)
第十三章spring应用spring管理hibernate
第十三章spring管理hibernate
Ø学习目标
Ø学习内容
在使用hibernate的过程中,我们体验到了把数据当成对象来处理的方便,但是仍然没有脱离从前使用jdbc时,打开连接关闭连接之类的重复操作。
我们还是需要不停的打开session然后关闭,偶而在过程中还要处理一下事务。
而在有了spring 之后,我们这些复杂的重复劳动,终于可以解脱了。
Spring提供了对orm框架的支持,这其中当然也包括了hibernate,我们可以通过spring为hibernate提供数据源,管理映射对象,管理事务等。
先来做一个干扰性最小的集成方式,在本例中,hibernate的配置完全由自己完成,不依赖spring,只由spring管理session对象与事务处理。
创建实体对象User.java
packagech04.entity;
importjava.io.Serializable;
publicclassUserimplementsSerializable{
privateIntegeruid;
privateStringusername;
privateStringpassword;
publicIntegergetUid(){
returnuid;
}
publicvoidsetUid(Integeruid){
this.uid=uid;
}
publicStringgetUsername(){
returnusername;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
}
映射文件:
User.hbm.xml
xmlversion="1.0"encoding="utf-8"?
>
DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"
"
hibernate.cfg.xml
xmlversion='1.0'encoding='UTF-8'?
>
DOCTYPEhibernate-configurationPUBLIC
"-//Hibernate/HibernateConfigurationDTD3.0//EN"
"
--GeneratedbyMyEclipseHibernateTools.-->
root
jdbc:
mysql:
//127.0.0.1:
3306/test?
&useUnicode=true&characterEncoding=gb2312
org.hibernate.dialect.MySQLDialect
mysql
root
com.mysql.jdbc.Driver
true
true
UserDao.java
packagech04.dao;
importch04.entity.User;
publicinterfaceUserDao{
booleanadd(Useru);
booleandel(Useru);
UsergetUserByName(Useru);
}
实现类,需要继承自org.springframework.orm.hibernate3.support.HibernateDaoSupport类,以便于spring可以为本类对象注入sessionfactory对象。
UserDaoImpl.java
packagech04.dao.impl;
importjava.util.List;
importorg.springframework.dao.DataAccessException;
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
importch04.dao.UserDao;
importch04.entity.User;
publicclassUserDaoImplextendsHibernateDaoSupportimplementsUserDao{
publicbooleanadd(Useru){
try{//得到操作模板
this.getHibernateTemplate().save(u);
returntrue;
}catch(DataAccessExceptione){
logger.error(e);
returnfalse;
}
}
publicbooleandel(Useru){
getSession().delete(u);
returnfalse;
}
publicUsergetUserByName(Useru){
Listulist=(List)
getHibernateTemplate().findByExample(u);
if(ulist.size()!
=0)
returnulist.get(0);
else{
returnnull;
}
}
@Override
publicStringtoString(){
return"测试";
}
}
配置文件:
spring-hibernate.xml
xmlversion="1.0"encoding="UTF-8"?
>
xsi="http:
//www.w3.org/2001/XMLSchema-instance"
xmlns="http:
//www.springframework.org/schema/beans"
xmlns:
aop="http:
//www.springframework.org/schema/aop"
xmlns:
tx="http:
//www.springframework.org/schema/tx"
xsi:
schemaLocation="
http:
//www.springframework.org/schema/beanshttp:
//www.springframework.org/schema/beans/spring-beans-2.0.xsd
http:
//www.springframework.org/schema/aophttp:
//www.springframework.org/schema/aop/spring-aop-2.0.xsd
http:
//www.springframework.org/schema/txhttp:
//www.springframework.org/schema/tx/spring-tx-2.0.xsd">
--得到sessionfactory对象-->
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
value="classpath:
ch04/hibernate.cfg.xml">
--为dao注入sessionfactory-->
--管理事务-->
--通知(增强)-->
adviceid="txadvice"transaction-manager="transactionManager">
attributes>
methodname="*"propagation="REQUIRED"/>
--详细见readme.txt
methodname="add*"propagation="SUPPORTS"rollback-for="java.lang.Exception"/>
-->
attributes>
advice>
--接入点-->
config>
pointcutexpression="execution(*ch04.dao..*.*(..))"id="cut"/>
advisoradvice-ref="txadvice"pointcut-ref="cut"/>
config>
在配置中,用…>标签管理了事务的关注点,这在上次学习中已经给大家做过介绍,重点讲解一下execution的表达方式,要注意,这个方法签名定义切点的方式,支持的是方法:
execution(public**(..))
所有公有的方法,第一个*表示返回值第二个表示方法名
execution(**User(..))这里第一个星表示返回值类型
上面定义了关注所有以User结尾的方法
如:
getUser()addUser()deleteUser()
execution(*ch04.dao.UserDao.*(..))
关注userdao接口定义的方法
execution(*ch04.dao.UserDao+.*(..))
关注userdao接口和子类的方法,注意,这里包括了UserDaoImpl中定义的方法
execution(*com..*.*Dao.find*(..))
关注所有com包中子包内后缀为Dao的类里,以find开头的方法
关于参数的定义execution(*add(..))
..表示的任意多个任意类型的参数
也可以用*来表示任意类型参数
如:
execution(*add(*,int))
execution(*add(String,..))第一个参数为String其它不限
除了上面对于相应的hibernate事务处理进行aop管理之外,还可以为事务进行更详细的配置,比如:
--管理事务-->
--通知(增强)-->
adviceid="txadvice"transaction-manager="transactionManager">
attributes>
methodname="*"propagation="REQUIRED"/>
--
这里可以指定方法名称的定义
如
methodname="add*"propagation="SUPPORTS"rollback-for="java.lang.Exception"/>
propagation事务的传播行为:
required必需的
supports支持
never从不
....
read-only事务是否是只读的
no-rollback-for不回滚的异常
rollback-for回滚的异常,可以用,分开
-->
attributes>
advice>
测试类:
Test.java
packagech04.util;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importch04.dao.UserDao;
importch04.entity.User;
publicclassTest{
publicstaticvoidmain(String[]args){
ApplicationContextac=newClassPathXmlApplicationContext("ch04/spring-hibernate.xml");
UserDaoud=(UserDao)ac.getBean("userDao");
//加用户
Useru=newUser();
u.setUsername("admin");
//u.setPassword("aaa");
ud.add(u);
u=ud.getUserByName(u);
System.out.println(u.getUid()+":
"+u.getUsername()+":
"+u.getPassword());
}
}
运行结果:
Hibernate:
insert
into
usertable
(username,password)
values
(?
?
)
Hibernate:
select
this_.uidasuid0_0_,
this_.usernameasusername0_0_,
this_.passwordaspassword0_0_
from
usertablethis_
where
(
this_.username=?
)
1:
admin:
null
在上面的例子中,hibernate本身配置由自己完成,spring只起到辅助作用,帮助使用者完成了相应的sessionfactory、session及事务的管理。
当然还有更深入的一些方式,比如我们可以省掉hibernate的配置文件,sessionfactory完全由spring提供。
其它部分基本一置,去掉hibernate.cfg.xml就行了,所以这里只给出配置文件写法:
xmlversion="1.0"encoding="UTF-8"?
>
xsi="http:
//www.w3.org/2001/XMLSchema-instance"
xmlns="http:
//www.springframework.org/schema/beans"
xmlns:
aop="http:
//www.springframework.org/schema/aop"
xmlns:
tx="http:
//www.springframework.org/schema/tx"
xmlns:
jee="http:
//www.springframework.org/schema/jee"
xsi:
schemaLocation="
http:
//www.springframework.org/schema/beanshttp:
//www.springframework.org/schema/beans/spring-beans-2.0.xsd
http:
//www.springframework.org/schema/aophttp:
//www.springframework.org/schema/aop/spring-aop-2.0.xsd
http:
//www.springframework.org/schema/txhttp:
//www.springframework.org/schema/tx/spring-tx-2.0.xsd
http:
//www.springframework.org/schema/jeehttp:
//www.springframework.org/schema/jee/spring-jee-2.0.xsd">
--为dao注入sessionfactory-->
--管理事务-->
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
--通知(增强)-->
adviceid="txadvice"transaction-manager="transactionManager">
attributes>
methodname="*"propagation="REQUIRED"/>
attributes>
advice>
--接入点-->
config>
pointcutexpression="execution(*ch05.dao..*.*(..))"
id="cut"/>
advisoradvice-ref="txadvice"pointcut-ref="cut"/>
config>
class="mons.dbcp.BasicDataSource">
value="com.mysql.jdbc.Driver">
value="jdbc:
mysql:
//127.0.0.1:
3306/test?
&useUnicode=true&characterEncoding=gb2312">
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">