1 事务管理
1.1 回顾事务
事务:一组业务操作,要么全部成功,要么全部不成功。
事务特性:ACID
原子性:整体
一致性:数据(完整)
隔离性:并发(多个事务)
持久性:结果
隔离问题:脏读、不可重复读、幻读(虚读)
隔离级别:4个
readuncommitted 读未提交,存在3个问题。
readcommitted 读已提交,解决:脏读;存在2个。
repeatableread 可重复读,解决:脏读、不可重复读;存在1个
serializable串行化,解决所有问题。
jdbc事务操作
标准版,要求:ABCD一个整体
Connection conn = null;
try{
//1 获得链接
conn = DataSource....
//2 开启事务
conn.setAutoCommit(false);
A
B
C
D
//3 提交事务
conn.commit();
} catch(){
//4 回滚事务
conn.rollback();
} finally{
conn.close();
}
使用保存点,要求:AB整体(必须),CD整体(可选)
Connection conn = null;
Savepoint savepoint = null;
try{
//1 获得链接
conn = DataSource....
//2 开启事务
conn.setAutoCommit(false);
A
B
savepoint = conn.setSavepoint();
C
D
//3 提交事务
conn.commit();
} catch(){
if(savepoint != null){ //CD异常
//回调到C之前
conn.rollback(savepoint);
//提交AB
conn.commit();
} else { //AB异常
conn.rollback();
}
} finally{
conn.close();
}
1.2 spring事务管理介绍
Spring事务管理机制顶层抽象,主要包括三个核心组件
导入jar包:spring-tx-3.2.0.RELEASE.jar
PlatformTransactionManager,平台事务管理器
TransactionDefinition,事务定义(事务详情)
TransactionStatus,事务状态
1.2.1 PlatformTransactionManager
概念介绍:spring没有直接管理事务,而是将管理事务的责任委托给JTA或相应的持久性机制所提供的某个特定平台的事物实现
平台事务管理器:spring管理事务时,必须使用平台事务管理器。不同技术使用的管理器不同。例如:jdbc有jdbc管理器,hibernate有hibernate管理。
导入jar包:
jdbcjar包:spring-jdbc-3.2.0.RELEASE.jar
整合hibernate jar包:spring-orm-3.2.0.RELEASE.jar
JDBC事务管理器:DataSourceTransactionManager
hibernate事务管理器:HibernateTransactionManager
管理器提供操作
TransactionStatusgetTransaction(TransactionDefinition) ,平台事务管理器,为了获得事务并进行操作的。
通过“事务详情”获得“事务状态”
commit(TransactionStatus) 根据状态操作,提交
rollback(TransactionStatus) 根据状态操作,回滚 (事务状态是管理器内部使用的,一般不进行使用)
总结:spring事务编程
1.确定管理器
2.必须配置事务详情(确定:是否只读、隔离级别等)
1.2.2 TransactionStatus
spring使用管理器,通过事务状态对事务进行管理(操作)。
1.2.3 TransactionDefinition
• 事务定义信息和事务管理相关参数
• 隔离级别、传播级别
• 超时 、事务是否只读
spring管理器 必须通过“事务详情”设置,获得相应事务,从而进行事务管理。
传播行为:一个业务A,调用一个业务B,此时AB如何共享事务。不同传播行为共享方案不同。
1.PROPAGATION_REQUIRED ,required ,必须使用事务 (默认值)
A如果使用事务,B 使用同一个事务。(支持当前事务)
A如果没有事务,B将创建一个新事务。
2.PROPAGATION_SUPPORTS,supports ,支持事务
A如果使用事务,B 使用同一个事务。(支持当前事务)
A如果没有事务,B 将以非事务执行。
3.PROPAGATION_MANDATORY,mandatory 强制
A如果使用事务,B 使用同一个事务。(支持当前事务)
A如果没有事务,B 抛异常
4.PROPAGATION_REQUIRES_NEW , requires_new ,必须是新事务
A如果使用事务,B将A的事务挂起,再创建新的(挂起:直到方法执行结束,新事务才算结束,原先的事务才会恢复执行)。
A如果没有事务,B将创建一个新事务
5.PROPAGATION_NOT_SUPPORTED ,not_supported 不支持事务
A如果使用事务,B将A的事务挂起,以非事务执行
A如果没有事务,B 以非事务执行
6.PROPAGATION_NEVER,never 从不使用
A如果使用事务,B 抛异常
A如果没有事务,B 以非事务执行
7.PROPAGATION_NESTED nested 嵌套
A如果使用事务,B将采用嵌套事务。
嵌套事务底层使用Savepoint 设置保存点,将一个事务,相当于拆分多个。
底层使用嵌套try方式
掌握:PROPAGATION_REQUIRED、PROPAGATION_REQUIRES_NEW、PROPAGATION_NESTED
1.3 案例:转账
1.3.1 搭建环境(没有事务)
1.3.1.1 创建数据库和表
create database spring_day03_db;
use spring_day03_db;
create table account(
id int primary key auto_increment,
username varchar(50),
money int
);
insert into account(username,money) values('jack',1000);
insert into account(username,money) values('rose',1000);
1.3.1.2 导入jar包
核心4个 + logging
jdbc2个 (spring.jdbc spring.tx)
aop 4个
c3p0
数据库驱动
1.3.1.3 编写dao
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
@Override
public void in(String inUser, int money) {
this.getJdbcTemplate()
.update("update account set money = money + ? where username = ?", money,inUser);
}
@Override
public void out(String outUser, int money) {
this.getJdbcTemplate()
.update("update account set money = money - ? where username = ?", money,outUser);
}
}
1.3.1.4 编写service
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void transfer(String outUser, String inUser, int money) {
this.accountDao.out(outUser, money);
// 模拟断电
//int i = 1/ 0;
this.accountDao.in(inUser, money);
}
}
1.3.1.5 编写配置文件
配置数据源,配置dao,配置service
<?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"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///spring_day03_db"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>
<!-- 2 配置dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 3 配置service -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
</beans>
1.3.1.6 测试
略
1.3.2 编程式:手动事务(了解)
spring底层使用TransactionTemplate 事务模板进行事务操作。
事务模板在 事务管理器的 平台上进行操作。
spring将创建 模板 注入 service,方便service进行事务操作
1.3.2.1 配置
提供事务管理器、提供事务模板,并将模板注入为service
<!-- 3 配置service -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
<!-- 4.3 给service注入模板 -->
<property name="transactionTemplate" ref="transactionTemplate"></property>
</bean>
<!-- 4.1 提供事务管理器 ,事务是从连接中获得,连接是从练级池中获得-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 4.2 提供事务模板, 模板必须在平台基础上进行事务操作 -->
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="txManager"></property>
</bean>
1.3.2.2 service使用
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
//spring注入 模板
private TransactionTemplate transactionTemplate;
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
@Override
public void transfer(final String outUser, final String inUser, final int money) {
//TransactionCallbackWithoutResult 处理没有结果集操作
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
public void doInTransactionWithoutResult(TransactionStatus arg0) {
accountDao.out(outUser, money);
// 模拟断电
int i = 1/ 0;
accountDao.in(inUser, money);
}
});
}
}
1.3.3 工厂bean(半自动)(了解)
TransactionProxyFactoryBean 一个特殊的工厂bean,用于生成事务代理的工厂bean,可以对目标类进行事务管理。
使用TransactionProxyFactoryBean代理
• 事务管理器 transactionManager
• 目标类 target
• 接口 proxyInterfaces
• 事务定义参数 transactionAttributes
• 参数需要使用<props>进行配置
• 格式:PROPAGATION,ISOLATION,readOnly,-Exception,+Exception
• PROPAGATION传播行为
• ISOLATION隔离级别
• readOnly: 只读事务,不能进行修改操作
• -Exception: 发生这些异常回滚事务
• +Exception: 发生这些异常仍然提交事务
1.3.3.1 service 获得手动代理
@Test
public void demo01(){
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath);
AccountService accountService =
(AccountService) applicationContext.getBean("proxyService");
accountService.transfer("jack", "rose", 100);
}
1.3.3.2 spring 配置创建代理
创建代理需要 目标类和接口,进行事务管理,需要事务管理器,事务管理器管理事务需要详情,配置事务属性。
<!-- 3 配置service(目标类) -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 4 创建service的代理对象,之后使用都是代理对象 -->
<bean id="proxyService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<!-- 4.1 确定事务管理器 -->
<property name="transactionManager" ref="txManager"></property>
<!-- 4.2 接口 -->
<property name="proxyInterfaces" value="com.itheima.service.AccountService"></property>
<!-- 4.3 目标类 -->
<property name="target" ref="accountService"></property>
<!-- 4.4 配置事务属性(事务详情) -->
<property name="transactionAttributes">
<!--
prop.key 表示事务详情的名称,用于确定哪些方法使用设置的详情
transfer ,指定的方法
add* ,add开头的方法
* , 任意方法
prop.text 表示当前方法使用具体详情设置
格式:PROPAGATION,ISOLATION,readOnly,-Exception,+Exception
传播行为 隔离级别 是否只读 异常回滚 异常提交
例如:
PROPAGATION_REQUIRED,ISOLATION_REPEATABLE_READ 表示默认传播行为和隔离级别
PROPAGATION_REQUIRED,ISOLATION_REPEATABLE_READ,readOnly 只读
PROPAGATION_REQUIRED,ISOLATION_REPEATABLE_READ,+java.lang.ArithmeticException 出现异常仍然提交
-->
<props>
<prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_REPEATABLE_READ,+java.lang.ArithmeticException</prop>
</props>
</property>
</bean>
<!-- 5 管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
1.3.4 声明式:spring aop 基于xml(掌握)
目标类ABCD,使用AOP继续筛选 ABC(切入点),需要使用事务详情从ABC进行确定到底如何使用事务,AB读写事务,C只读事务。
步骤:
1 配置事务管理器
2 使用<tx:advice>对事务管理器增强
3 配置aop使切入点与通知关联
修改配置文件
<!-- 4.1 事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 4.2 配置事务详情
<tx:advice> 配置事务详情
id 通知名称
transaction-manager 事务详情最后要应用到平台(管理器)
<tx:method> 配置具体的详情
name 详情名称,类似 <prop key="">
transfer 指定
add* add开头
* 所有
propagation 传播行为
isolation 隔离级别
read-only 是否只读
rollback-for 类似 -Exception 回滚
no-rollback-for 类型 +Exception 提交
例如: 增删改为读写,查询为只读
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="REQUIRED" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="transfer" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 4.3 使用aop确定切入点
advice-ref 通知确定事务详情
-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itheima.service..*.*(..))"/>
</aop:config>
1.3.5 声明式:spring 基于 注解 (掌握)
声明事务管理器
将事务管理器交予spring(注册驱动:<tx:annotation-driven transaction-manager="txManager"/>)
在目标类或方法上 使用注解即可 @Transactional
1.3.5.1 配置xml
将选择的事务管理器,交予spring
<!-- 4.1 事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 4.2 将事务管理器交予spring -->
<tx:annotation-driven transaction-manager="txManager"/>
1.3.5.2 service使用注解
@Transactional可以修饰在类或方法上。
类
@Transactional
public class AccountServiceImpl implementsAccountService {
方法
@Transactional
public void transfer(String outUser, StringinUser, int money) {
设置具体的事务的详情
@Transactional(
propagation=Propagation.REQUIRED,
isolation=Isolation.DEFAULT,
readOnly=false,
rollbackFor=ArithmeticException.class
)
l *propagation=Propagation.REQUIRED 传播行为
l * isolation=Isolation.DEFAULT 隔离级别
l * readOnly=false 是否只读
l *rollbackFor=ArithmeticException.class 发生异常回滚
l * noRollbackFor=xxx.class 发生异常 仍然提交事务
2 整合web项目
在web项目中如何使用spring开发。如果使用 newClassPathXmlApplicationContext 将每一次都加载xml,相当于每一次都创建spring容器。而真实开发中,容器只有一份。之后重复的从spring容器中获取内容。
spring自动加载配置文件,生成spring容器,并将其存放到ServletContext作用域中。Spring提供监听器程序ContextLoaderListener (ServletContextListener实现),tomcat启动时执行。启动时加载配置文件。
tomcat 启动时加载配置文件
1.Filter过滤器 --init(FilterConfig) 只要配置web.xml 启动加载
2.Servlet--init(ServletConfig) 需要web.xml 配置 <load-on-startup>2
3.Listener监听器,ServletContextListener
spring使用监听器加载xml文件:ContextLoaderListener
导入jar包:spring-web-3.2.0.RELEASE.jar
步骤一:web.xml添加监听器【掌握】
<!-- 配置监听器,用于加载spring 配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
问题:tomcat启动时将抛异常,
Caused by:java.io.FileNotFoundException: Could not open ServletContext resource[/WEB-INF/applicationContext.xml]
表示ContextLoaderListener监听器 默认加载xml配置文件位置:/WEB-INF/applicationContext.xml
步骤二:web.xml中配置 applicationContext.xml 位置【掌握】
<!-- 设置web全局初始化参数,设置配置文件位置
* 名称#contextConfigLocation 固定值
* 值# “classpath:”表示类路径(src)
也可以有子包 # classspath:com/itheima/applicationContext.xml
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
步骤三:从ServletContext中获得spring容器(了解)
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//方式1:手动从ServletContext作用域获得内容
//WebApplicationContext applicationContext = (WebApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
//方式2:提供工具类
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
UserService userService = (UserService) applicationContext.getBean("userService");
userService.addUser();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
3 SSH整合
3.1 jar包
3.1.1 struts
版本:2.3.15.3
位置:struts-2.3.15.3\apps\struts2-blank\WEB-INF\lib
其他:
json:struts2-json-plugin-2.3.15.3.jar (struts提供json插件,一般开发不用,采用jsonlib)
struts注解:struts2-convention-plugin-2.3.15.3.jar(如果不使用,不要导入此jar)
3.1.2 hibernate
版本:3.6.10
1核心jar:hibernate3.jar
2必须:lib\required所有
3jpa :lib\jpa 所有
(persistence)
hibernate注解开发使用api @Entity
4.c3p0\lib\optional\c3p0
5.log4j 整合jar ,slf4j-log4j12-1.7.5.jar
6.数据库驱动,mysql-connector-java-5.1.22-bin.jar
7.二级缓存ehcache-1.5.0.jar、backport-util-concurrent-2.1.jar
3.1.3 spring
版本:3.2.0
jar包:
核心4个、 commons-logging...jar (struts2、hibernate二级缓存、spring)
aop4个:aop联盟、spring aop、aspectj、spring-aspect
jdbc:2个:spring-jdbc、spring-tx
web:1个 spring-web
test:1个 spring-test (整合测试)
3.1.4 整合jar
spring3整合hibernate3,spring提供整合jar : spring-orm...jar
struts2整合 spring3 ,struts提供整合jar:struts2-spring-plugin-2.3.15.3.jar
3.1.5 整理jar
总和(40个)
3.2 配置文件
3.2.1 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>
<!-- 1 基本4项
* 如果出现中文乱码需要设置:?useUnicode=true&characterEncoding=UTF-8
* 注意:& 在xml转义之后 &
* 注意:UTF8只在mysql有效,其他都是UTF-8
-->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/s_day03_db?useUnicode=true&characterEncoding=UTF-8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<!-- 2方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 3 sql -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 4 语句ddl -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 5 取消bean校验 -->
<property name="javax.persistence.validation.mode">none</property>
<!-- 6 绑定session -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- 添加映射 -->
<mapping resource="com/itheima/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
*.hbm.xml 映射文件(domain)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.itheima.domain.User" table="t_user">
<id name="id">
<generator class="native"></generator>
</id>
<property name="username"></property>
<property name="password"></property>
</class>
</hibernate-mapping>
3.2.2 spring
applicationContext.xml
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
jdbcInfo.properties
web.xml(ContextLoaderListener)
<!-- 确定xml文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- spring监听器,加载xml文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3.2.3 struts
struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 开发模式 -->
<constant name="struts.devMode" value="true" />
<!-- struts标签模板 -->
<constant name="struts.ui.theme" value="simple"></constant>
<package name="default" namespace="/" extends="struts-default">
</package>
</struts>
web.xml(前端控制器 StrutsPrepareAndExecuteFilter )
<!-- struts 前端控制器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.3 hibernate环境搭建
3.3.1 javabean
public class User {
private Integer id;
private String username;
private String password;
private int age;
3.3.2 hbm.xml映射文件
<hibernate-mapping>
<class name="com.itheima.domain.User" table="t_user">
<id name="id">
<generator class="native"></generator>
</id>
<property name="username" length="50"></property>
<property name="password" length="32"></property>
<property name="age"></property>
</class>
</hibernate-mapping>
3.3.3 hibernate.cfg.xml
<session-factory>
<!-- 1 基本4项 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring_day03_db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<!-- 2 方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 3 sql优化,显示,格式化 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 4 自动创建表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 5 整合c3p0 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- 添加映射文件 -->
<mapping resource="com/itheima/domain/User.hbm.xml"/>
</session-factory>
3.4 spring整合hibernate
3.4.1 hibernate有配置文件(cfg.xml)
dao: 提供 HibernateTemplate 模板用于操作PO类
LocalSessionFactoryBean用于加载hibernate.cfg.xml文件
HibernateTransactionManager hibernate事务管理器
3.4.1.1 dao层
使用模板HibernateTemplate,类似hibernate时 Session,可以直接对 PO进行操作。
public class UserDaoImpl implements UserDao {
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
@Override
public void save(User user) {
this.hibernateTemplate.save(user);
}
}
3.4.1.2 service层
spring在service管理事务
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void register(User user) {
this.userDao.save(user);
}
}
3.4.1.3 spring配置
加载hibernate.cfg.xml 生成SessionFactory
将sessionfactory 注入给HibernateTemplate ,生成模板
需要使用HibernateTransactionManager 进行事务管理
<!-- 1 获得sessionfactory,spring加载hibernate.cfg.xml文件 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- 2 hibernate模板 -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 3 dao -->
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
<!-- 4 service -->
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<!-- 5事务管理 -->
<!-- 5.1事务管理器 , 事务通过session,session通过sessionfactory获得-->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 5.2事务通知 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="register"/>
</tx:attributes>
</tx:advice>
<!-- 5.3aop 事务应用 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itheima.service..*.*(..))"/>
</aop:config>
3.4.2 hibernate没有配置文件
删除hibernate.cfg.xml
删除HibernateTemplate 模板创建
3.4.2.1 删除cfg.xml
将hibernate.cfg.xml 中配置的内容,全部配置到spring中即可。
<!-- 1 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_day03_db"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>
<!-- 2获得sessionfactory
* 不在 加载hibernate.cfg.xml文件
-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 2.1 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 2.2 其他属性设置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 2.3 添加映射文件
mappingResources 加载资源,从src获取,必须确定指定的资源
mappingLocations 建议“classpath:” 可以通配符【】
classpath:com/itheima/*/User.hbm.xml ,目录任意
classpath:com/itheima/domain/*.hbm.xml, 文件名任意
mappingDirectoryLocations 设置目录
classpath:com/itheima/domain/
mappingJarLocations 从jar获得配置文件
-->
<property name="mappingLocations" value="classpath:com/itheima/domain/User.hbm.xml"></property>
</bean>
3.4.2.2 删除模板
提供父类:HibernateDaoSupport ,只需要注入SessionFactory,底层自动创建模板。
dao 继承父类 HibernateDaoSupport
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
@Override
public void save(User user) {
this.getHibernateTemplate().save(user);
}
}
spring 配置dao时,只需要注入sessionfactory
<!-- 3 dao -->
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
3.5 struts整合spring
3.5.1 spring创建action
将action配置到spring中,并注入service
scope=”prototype”注意由于由spring创建action是单例的,必须要手动设置为多例
<!-- 6 配置action -->
<bean id="userAction" class="com.itheima.web.action.UserAction" scope="prototype">
<property name="userService" ref="userService" scope=”prototype”></property>
</bean>
配置struts时,让struts从spring容器获取 action(↓既class=userAction 使用别名)
<package name="hello" namespace="/" extends="struts-default">
<action name="userAction_*" class="userAction" method="{1}">
<result name="success">/message.jsp</result>
</action>
</package>
前提,必须导入jar包:struts2-spring-plugins.jar
优先从spring容器获得内容,如果没有再自己创建。
底层
3.5.2 struts创建action
struts自己创建action(class="com.itheima.web.action.UserAction")
spring不用配置<bean>action
<package name="hello" namespace="/" extends="struts-default">
<action name="userAction_*" class="com.itheima.web.action.UserAction" method="{1}">
<result name="success">/message.jsp</result>
</action>
</package>
注意: action类中 属性名userService 必须与 spring中配置<bean id="userService">名称一样。
struts 创建action,默认情况,使用action属性名称,与spring bean id 匹配,如果名称一致,将自动注入。
原因:
导入的jar包:struts2-spring-plugin-2.3.15.3.jar
提供:<constantname="struts.objectFactory" value="spring" /> 表示struts action对象创建权交予spring
文件加载顺序
default.properties
struts-plugins.xml
两个配置文件结合,对象由spring创建,将默认按照名称进行注入。
4 SSH整合注解
>SSH 注解--hibernate
@Entity 实体类
@Table 生成目标表
@Id 主键
@GeneratedValue 主键生成策略
@Column 定义生成列
@GeneratedValue只支持 IDENTITY SEQUENCE 和 TABLE
如果使用其它类型的生成策略需要自定义
@GenericGenerator用于自定义生成策略
@GeneratedValue的 generator 用于指定自定义生成策略
@Temporal 生成日期类型
@OneToMany 配置一对多
@ManyToOne 配置多对一
@JoinColumn(name="") 在多方配置外键
@ManyToMany配置多对多
@JoinTable(name="中间表",joinColumns=@JoinColumn(name="自己外键"),inverseJoinColumns=@JoinColumn(name="对方外键"))
>SSH 注解--spring
@Controller 表示层 (action)
@Service 业务逻辑层
@Repository dao层
属性注入
@Autowired 按照类型自动注入
按照名称注入
@Qualifier(引用名称)
@Transactional 事务
通过AnnotationSessionFactoryBean解析注解PO类
需要packagesToScan属性设置PO类位置
使用HibernateTransactionManager配置事务
将基本信息使用注解 替换掉xml
hibernate: cfg.xml
spring: 事务管理器,数据源等
struts:常量配置,拦截器等
4.1hibernate
取代 *.hbm.xml 映射文件
其他属性不配置默认使用
@Entity //<class name="com.itheima.domain.User"
@Table(name="t_user") //table="t_user">
public class User {
@Id //<id name="id">
@GeneratedValue(strategy=GenerationType.AUTO) //<generator class="native">
private Integer id;
//@Column(length=10,unique=true,columnDefinition="")
private String username;
private String password;
4.2spring
配置dao和service,需要手动编写 HibernateTemplate,不能继承父类,注解无法给父类添加。
@Repository //<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
public class UserDaoImpl implements UserDao {
// 如果使用注解,不能使用 extends HibernateDaoSupport,必须手动编写模板
@Autowired
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
@Override
public void save(User user) {
hibernateTemplate.save(user);
}
}
@Service //<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
@Transactional
public class UserServiceImpl implements UserService {
@Autowired //<property name="userDao" ref="userDao">
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
xml 配置扫描注解,配置事务管理器
<!-- 2 spring 扫描注解 -->
<context:component-scan base-package="com.itheima"></context:component-scan>
<!-- 5.2 事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
spring 加载 hibernate PO 含有注解类
<!-- 4 session工厂
* AnnotationSessionFactoryBean 特殊bean生成 SessionFactory,可以加载hibernate 含有注解的PO类
packagesToScan 确定PO位置
-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3
.annotation.AnnotationSessionFactoryBean">
<!--中间配置略-->
<!--4.3 加载被注解修饰的po类 -->
<property name="packagesToScan" value="com.itheima.domain"></property>
</bean>
po
@Entity //<class name="com.itheima.domain.User"
@Table(name="t_user") //table="t_user">
public class User {
@Id //<id name="id">
@GeneratedValue(strategy=GenerationType.AUTO) //<generator class="native">
private Integer id;
//@Column(length=10,unique=true,columnDefinition="")
private String username;
private String password;
public Integer getId() {
return id;
}
4.3struts
必须导入jar包
注解开发需要struts2-convention-plugin-2.3.15.3.jar
不能配置通配符
@Namespace("/") //namespace="/"
@ParentPackage("struts-default") //extends="struts-default">
public class UserAction extends ActionSupport implements ModelDriven<User> {
//封装数据
private User user = new User();
@Override
public User getModel() {
return user;
}
@Autowired
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
@Action(value="userAction_add" ,results=@Result(name="add",location="/success.jsp"))
public String add(){
this.userService.addUser(user);
return "add";
}
}
参考:struts-2.3.15.3/docs/WW/docs/annotations.html