虽然Spring中提供了JDBCTemplate模块,已经很大程度了解决了JDBC代码的复杂度,但它仍然是和Java代码写在一起的。反观 Mybatis 将 Sql 语句写在配置文件中,使得SQL语句和程序实现了松耦合。而且提供了些许标签,使得SQL可以是动态的。在ORM基础上想要更好的用Spring的DI、AOP、事务处理、Junit支持等实现成果,学会使用 Spring 框架集成 Mybatis 是大势所趋。
mybatis提供的
与spring框架集成的依赖 <dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>6.0.5version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>6.0.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.31version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.11version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>3.0.1version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.16version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
<scope>testscope>
dependency>
dependencies>
package com.ncpowernode.spring.mappers;
import com.ncpowernode.spring.bean.Account;
import java.util.List;
public interface AccountMapper {
List<Account> selectAll();
Account selectByActno(String actno);
int insert(Account account);
int deleteByActno(String actno);
int update(Account account);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ncpowernode.spring.mappers.AccountMapper">
<select id="selectAll" resultType="account">
select * from t_act;
select>
<insert id="insert">
insert into t_act values(#{actno},#{balance})
insert>
<delete id="deleteByActno">
delete from t_act where actno = #{actno};
delete>
<select id="selectByActno" resultType="account">
select * from t_act where actno = #{actno};
select>
<update id="update">
update t_act set balance = #{balance} where actno = #{actno};
update>
mapper>
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<Account> 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;
@Override
public int save(Account act) {
return accountMapper.insert(act);
}
@Override
public int deleteByActno(String actno) {
return accountMapper.deleteByActno(actno);
}
@Override
public List<Account> getAll() {
return accountMapper.selectAll();
}
@Override
public void transfer(String fromActno, String toActno, double money) {
// 判断余额
Account fromAccount = accountMapper.selectByActno(fromActno);
if (fromAccount.getBalance()<money) throw new RuntimeException("余额不足");
// 更新数据库
Account toAccount = accountMapper.selectByActno(toActno);
fromAccount.setBalance(fromAccount.getBalance()-money);
toAccount.setBalance(toAccount.getBalance()+money);
int cnt = accountMapper.update(fromAccount);
cnt += accountMapper.update(toAccount);
// 判断业务是否实现成功
if(cnt!=2) throw new RuntimeException("转账失败");
}
}
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/???
jdbc.username=???
jdbc.password=???
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
configuration>
<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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.ncpowernode.spring.service"/>
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.ncpowernode.spring.bean"/>
<property name="configLocation" value="mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ncpowernode.spring.mappers"/>
bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:annotation-driven transaction-manager="txManager"/>
beans>
@Test
public 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);
}
测试结果