一、Spring整合Mybatis框架加入事务操作数据库
1、创建项目,导入依赖包:spring基本包、aop相关包、c3p0连接池包、事务包、数据库驱动包、mybatis-3.4.5、mybatis-spring-1.3.2
2、创建基本包:bean、mapper、service、test
3、创建数据库信息文件db.properties、mybatis配置文件sqlMapConfig.xml、spring配置文件:applicationContext.xml
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_spring
jdbc.user=root
jdbc.password=123
4、还是老套路,写一个测试的小例子 用Account作为bean对象,写入AccountService接口以及实现类,AccountMapper接口以及实现类
public class Account {
private Integer id;
private String name;
private Double money;
//转账金额
private Double transMoney;
}
其中转账金额是用于操作,并不真实存在于数据库;
/**
* 转账接口
* @author Dunka
*
*/
public interface AccountService {
void transferAccount();
}
public class AccountServiceImpl implements AccountService {
@Resource(type=AccountMapper.class)
private AccountMapper am;
@Override
public void transferAccount() {
Account pay = new Account();
pay.setId(1);
pay.setTransMoney(100d);
//扣款
am.subMoney(pay);
// int i=1/0;
Account collect = new Account();
collect.setId(2);
collect.setTransMoney(100d);
//加款
am.addMoney(collect);
}
}
里面Resource(type=AccountMapper.class)是由于spring容器在设置时并没有往accountService中注入任何信息,所以手动未AccountMapper注入对象;
public interface AccountMapper {
//先扣款再转账
//扣款
void subMoney(Account pay);
//转账
void addMoney(Account collect);
}
update account set money = money - #{transMoney} where id = #{id}
update account set money = money + #{transMoney} where id = #{id}
在applicationContext.xml中注入AccountService对象
加入测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class MapperTest {
@Resource(name="accountService")
private AccountService as;
@Test
public void test1() {
as.transferAccount();
}
}
同样,由于没有加入事务,所以数据库操作停留在正常不能抛出异常的状况下。
在加入事务说明之前,我想记录下过程中遇到的两个错误,都是因为不细心犯下的。
(1)、java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElements.getAttributes
原因是,我在写测试类的时候发现引用不到SpringJUnit4ClassRunner.class,所以我查看我引用的jar包发现没有test包,所以我在我的盘里找到了一个spring-test-4.1.4的版本,就这么用了,然后报错之后发现,我的其他包用的都是spring-xx-5.0猜测是这个错误,所以改用了spring-test-5.0,然后,果然不出我所料,终于不报这个错误了,报出了下一个错误
(2)、Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchmethod
原因更好笑,是因为我在写的时候,不小心把动态扫描mapper的bean给删掉了
所以他无法扫描到accountMapper.class,这个Resource(type=AccountMapper.class)无法注入成功,导致accountService这个方法注入不成功。
被自己气笑了哈哈哈哈哈哈哈哈。
5、加入事务配置
6、再次测试。