springmvc学习笔记三:整合JDBC,简单案例==数据…
2019-08-16 10:37:58来源:博客园 阅读 ()
springmvc学习笔记三:整合JDBC,简单案例==数据库事务配置(切面)
package cn.itcast.bean; import org.springframework.jdbc.core.PreparedStatementSetter; public class User { private int Id; private String Name; public int getId() { return Id; } public void setId(int id) { Id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } @Override public String toString() { return "User [Id=" + Id + ", Name=" + Name + "]"; } }View Code
package cn.itcast.a_jdbctemplate; import java.util.List; import cn.itcast.bean.User; public interface UserDao { //增 void save(User u); //删 void delete(Integer id); //改 void update(User u); //查 User getById(Integer id); //查 int getTotalCount(); //查 List<User> getAll(); }View Code
package cn.itcast.a_jdbctemplate; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; import cn.itcast.bean.User; //使用JDBC模板实现增删改查 public class UserDaoImpl extends JdbcDaoSupport implements UserDao { //方式一:springJdbcTemplate的时候不需要继承JdbcDaoSupport //方式二:继承JdbcDaoSupport。可以不要配置JdbcTemplate的bean。 private JdbcTemplate jt; @Override public void save(User u) { String sql = "insert into t_user values(null,?) "; jt.update(sql, u.getName()); System.out.println(""); } @Override public void delete(Integer id) { String sql = "delete from t_user where id = ? "; jt.update(sql,id); } @Override public void update(User u) { String sql = "update t_user set name = ? where id=? "; jt.update(sql, u.getName(),u.getId()); } @Override public User getById(Integer id) { String sql = "select * from taccount_1 where AreaID = ? "; System.out.println("---执行到"); return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){ @Override public User mapRow(ResultSet rs, int arg1) throws SQLException { User u = new User(); u.setId(rs.getInt("AreaID")); u.setName(rs.getString("Name")); return u; }}, id); } @Override public int getTotalCount() { String sql = "select count(*) from t_user "; Integer count = jt.queryForObject(sql, Integer.class); return count; } @Override public List<User> getAll() { String sql = "select * from t_user "; List<User> list = jt.query(sql, new RowMapper<User>(){ @Override public User mapRow(ResultSet rs, int arg1) throws SQLException { User u = new User(); u.setId(rs.getInt("id")); u.setName(rs.getString("name")); return u; }}); return list; } public void setJt(JdbcTemplate jt) { this.jt = jt; } }
ApplicationContext.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd "> <!-- 指定spring读取db.properties配置 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 1.将连接池放入spring容器 --> <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" > <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property> <property name="driverClass" value="${jdbc.driverClass}" ></property> <property name="user" value="${jdbc.user}" ></property> <property name="password" value="${jdbc.password}" ></property> </bean> <!--<!– 2.将JDBCTemplate放入spring容器 –>--> <!--<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >--> <!--<property name="dataSource" ref="dataSource" ></property>--> <!--</bean>--> <!-- 3.将UserDao放入spring容器 --> <bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" > <!-- <property name="jt" ref="jdbcTemplate" ></property> --> <!-- 如果 UserDaoImpl继承了JdbcDaoSupport,就不需要在生产一个dataSource的bean--> <property name="dataSource" ref="dataSource" ></property> </bean> </beans>
jdbc.jdbcUrl=jdbc:mysql://192.168.1.20:3306/zy_test
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root123
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <mvc:annotation-driven /> <!-- 配置controller扫描包 --> <context:component-scan base-package="com.yyb.controller"/> <!-- 配置controller扫描包,多个包之间用,分隔 --> <context:component-scan base-package="cn.itcast.springmvc.controller" /> <!-- 配置SpringMVC的视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="cn.itcast.ssm.interceptor.HandlerInterceptor1" /> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="cn.itcast.ssm.interceptor.HandlerInterceptor2" /> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/item/**" /> <bean class="cn.itcast.ssm.interceptor.HandlerInterceptor2" /> </mvc:interceptor> </mvc:interceptors> </beans>View Code 测试类:
package cn.itcast.a_jdbctemplate; import java.beans.PropertyVetoException; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.itcast.bean.User; //演示JDBC模板 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:ApplicationContext.xml") public class test { @Resource(name="userDao") private UserDao ud; @Test public void fun2() throws Exception{ System.out.println("开始执行--"); User u = new User(); User user = ud.getById(67); System.out.println("返回user="+user); } }
2.spring管理事务配置案例:
测试环境搭建
package com.yyb.dao; public interface AccountDao { //加钱 void increaseMoney(Integer id, Double money); //减钱 void decreaseMoney(Integer id, Double money); }
package com.yyb.dao; import org.springframework.jdbc.core.support.JdbcDaoSupport; public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao { @Override public void increaseMoney(Integer id, Double money) { getJdbcTemplate().update("update t_account set money = money+? where id = ? ", money,id); } @Override public void decreaseMoney(Integer id, Double money) { getJdbcTemplate().update("update t_account set money = money-? where id = ? ", money,id); } }
package com.yyb.service; public interface AccountService { //转账方法 void transfer(Integer from, Integer to, Double money); }
package com.yyb.service; import com.yyb.dao.AccountDao; public class AccountServiceImpl implements AccountService { private AccountDao ad; @Override public void transfer(Integer from, Integer to, Double money) { //减钱 ad.decreaseMoney(from,money); //加钱 ad.increaseMoney(to,money); } public void setAd(AccountDao ad) { this.ad = ad; } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "> <!-- 指定spring读取db.properties配置 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 1.连接池 --> <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 2.Dao--> <bean name="accountDao" class="com.yyb.dao.AccountDaoImpl"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 3.Service--> <bean name="accountService" class="com.yyb.service.AccountServiceImpl"> <property name="ad" ref="accountDao"></property> </bean> </beans>
jdbc.jdbcUrl=jdbc:mysql:///hibernate_crm jdbc.driverClass=com.mysql.jdbc.Driver jdbc.user=root jdbc.password=123456
package com.yyb.app; import com.yyb.service.AccountService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Created by Administrator on 2017/8/17. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class TransactionTest { @Autowired private AccountService accountService; @Test public void func1(){ accountService.transfer(1,2,100d); } }
方式1:编码式(了解)
1.将核心事务管理器配置到spring容器,在applicationContext中配置如下代码:
<!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean>
2.配置TransactionTemplate模板,在applicationContext中配置如下代码:
<!--事务模板对象--> <bean class="org.springframework.transaction.support.TransactionTemplate"> <property name="transactionManager" ref="transactionManager"></property> </bean>
3.将事务模板注入Service
<!-- 3.Service--> <bean name="accountService" class="com.yyb.service.AccountServiceImpl"> <property name="ad" ref="accountDao"></property> <property name="tt" ref="transactionTemplate"></property> </bean>
4.在Service中调用模板
package com.yyb.service; import com.yyb.dao.AccountDao; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; public class AccountServiceImpl implements AccountService { private AccountDao ad; private TransactionTemplate tt; //匿名内部类访问外部变量得加final @Override public void transfer(final Integer from,final Integer to, Double money) { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { //减钱 ad.decreaseMoney(from,money); //int i=1/0; //加钱 ad.increaseMoney(to,money); } }); } public void setAd(AccountDao ad) { this.ad = ad; } public void setTt(TransactionTemplate tt) { this.tt = tt; } }
方式2:xml配置(aop)
简单理解就是把通知织入到目标对象中,形成一个代理对象。比如通知要进行事务管理,目标对象要进行业务处理。那么代理对象则把事务管理和业务处理合到了一起。SpringAOP给我们准备了一个事务通知,目标对象即我们的service。所以只需要配置一下就可以了。
1、需要导包aop、aspect、aop联盟、weaving织入包
2.导入新的约束(tx)
beans: 最基本约束;context:读取properties配置约束;aop:配置aop约束;tx:配置事务通知约束
3.配置通知和配置将通知织入目标
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" 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/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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 1.将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
<property name="driverClass" value="${jdbc.driverClass}" ></property>
<property name="user" value="${jdbc.user}" ></property>
<property name="password" value="${jdbc.password}" ></property>
</bean>
<!--2.将JDBCTemplate放入spring容器-->
<!--<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >-->
<!--<property name="dataSource" ref="dataSource" ></property>-->
<!--</bean>-->
<!-- 3.将UserDao放入spring容器 -->
<bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
<!-- <property name="jt" ref="jdbcTemplate" ></property> --> <!-- 如果 UserDaoImpl继承了JdbcDaoSupport,就不需要在生产一个dataSource的bean-->
<property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 2.Dao-->
<bean name="accountDao" class="com.yyb.dao.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 3.Service-->
<bean name="accountService" class="com.yyb.service.AccountServiceImpl">
<property name="ad" ref="accountDao"></property>
</bean>
<!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<!-- 以方法为单位,指定方法应用什么事务属性:isolation:隔离级别 propagation:传播行为 read-only:是否只读-->
<tx:method name="transfer" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<!--上面的方式只适用单个方法,当我们业务有很多个方法都要操作事务时,则要配置很多个,可以使用下面的通配符配置方式-->
<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<!--配置织入-->
<aop:config>
<aop:pointcut id="txPc" expression="execution(* com.yyb.service..*(..))"/>
<!--配置切面-->
<aop:advisor pointcut-ref="txPc" advice-ref="txAdvice" />
</aop:config>
<!-- 开启事务注解驱动-->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
方式3:注解配置(aop)
1.导包(同上)
2.导入新的约束(tx),同上
3.开启注解管理事务
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "> <!-- 指定spring读取db.properties配置 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--开启使用注解管理aop事务--> <tx:annotation-driven/> <!-- 1.连接池 --> <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 2.Dao--> <bean name="accountDao" class="com.yyb.dao.AccountDaoImpl"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 3.Service--> <bean name="accountService" class="com.yyb.service.AccountServiceImpl"> <property name="ad" ref="accountDao"></property> </bean> </beans>
4.使用注解
@Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED,readOnly = false) public void transfer(Integer from,Integer to, Double money) {
在方法上加注解,如果方法太多,嫌麻烦的话,可以在类上加,如果某个方法不适应,再在方法上写一份即可。
package com.yyb.service; import com.yyb.dao.AccountDao; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED,readOnly = false) public class AccountServiceImpl implements AccountService { private AccountDao ad; @Override @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false) public void transfer(Integer from,Integer to, Double money) { //减钱 ad.decreaseMoney(from,money); //int i=1/0; //加钱 ad.increaseMoney(to,money); } public void setAd(AccountDao ad) { this.ad = ad; } }
原文链接:https://www.cnblogs.com/2019lgg/p/11206383.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- springboot2配置JavaMelody与springMVC配置JavaMelody 2020-06-11
- 学习Java 8 Stream Api (4) - Stream 终端操作之 collect 2020-06-11
- java学习之第一天 2020-06-11
- Java学习之第二天 2020-06-11
- Spring WebFlux 学习笔记 - (一) 前传:学习Java 8 Stream Ap 2020-06-11
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash