虽然Spring中提供了JDBCTemplate模块,已经很大程度了解决了JDBC代码的复杂度,但它仍然是和Java代码写在一起的。反观 Mybatis 将 Sql 语句写在配置文件中,使得SQL语句和程序实现了松耦合。而且提供了些许标签,使得SQL可以是动态的。在ORM基础上想要更好的用Spring的DI、AOP、事务处理、Junit支持等实现成果,学会使用 Spring 框架集成 Mybatis 是大势所趋。
mybatis提供的
与spring框架集成的依赖 org.springframework spring-context 6.0.5 org.springframework spring-jdbc 6.0.5 mysql mysql-connector-java 8.0.31 org.mybatis mybatis 3.5.11 org.mybatis mybatis-spring 3.0.1 com.alibaba druid 1.2.16 junit junit 4.13 test
package com.ncpowernode.spring.mappers;import com.ncpowernode.spring.bean.Account;import java.util.List;public interface AccountMapper {List selectAll();Account selectByActno(String actno);int insert(Account account);int deleteByActno(String actno);int update(Account account);
}
insert into t_act values(#{actno},#{balance}) delete from t_act where actno = #{actno}; update t_act set balance = #{balance} where actno = #{actno};
service接口
package com.ncpowernode.spring.service;import com.ncpowernode.spring.bean.Account;import java.util.List;public interface AccountService {int save(Account act);int deleteByActno(String actno);List getAll();void transfer(String fromActno,String toActno,double money);}
service实现
package com.ncpowernode.spring.service.impl;import com.ncpowernode.spring.bean.Account;
import com.ncpowernode.spring.mappers.AccountMapper;
import com.ncpowernode.spring.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;import java.util.List;@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {@Autowired@Qualifier("accountMapper")private AccountMapper accountMapper;@Overridepublic int save(Account act) {return accountMapper.insert(act);}@Overridepublic int deleteByActno(String actno) {return accountMapper.deleteByActno(actno);}@Overridepublic List getAll() {return accountMapper.selectAll();}@Overridepublic void transfer(String fromActno, String toActno, double money) {// 判断余额Account fromAccount = accountMapper.selectByActno(fromActno);if (fromAccount.getBalance()
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/???
jdbc.username=???
jdbc.password=???
@Testpublic void testSM(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");AccountService accountService = applicationContext.getBean("accountService", AccountServiceImpl.class);accountService.getAll().forEach(System.out::println);accountService.transfer("act-001","act-002",10000.0);}
测试结果