08、Spring 集成MyBatis3.5
今天我们聊一下如何在Spring中集成MyBatis3.5,我们来看看具体的集成步骤。
第一步:数据库表准备
MyMatis是用来操作数据库的ORM框架,所以我们第一步要确定操作哪个库哪些表
CREATE TABLE `t_act` (
`id` bigint NOT NULL AUTO_INCREMENT,
`actno` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT '',
`balance` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
第二步:创建Maven工程
Maven工程中需要添加如下依赖
<dependencies>
<!-- spring context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.9</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.13</version>
</dependency>
<!-- spring jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.1.9</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
第三步:组织项目中的三层包结构
实体包:com.xiaoxie.pojo
mapper:com.xiaoixe.mapper
service:com.xiaoxie.service、com.xiaoxie.service.impl
第四步:编写实体类
实体类是与数据库对应的
public class Account {
private String actno;
private Double balance;
public Account() {
}
public Account(String actno, Double balance) {
this.actno = actno;
this.balance = balance;
}
public String getActno() {
return actno;
}
public void setActno(String actno) {
this.actno = actno;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account{" +
"actno='" + actno + '\'' +
", balance=" + balance +
'}';
}
}
第五步:jdbc.properties配置
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
第六步:mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
</configuration>
第七步:Spring配置文件
<?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: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 https://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.xiaoxie"/>
<!-- 引入外部属性配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- SqlSessoinFactoryBean -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- mybatis 配置文件位置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 别名包 -->
<property name="typeAliasesPackage" value="com.xiaoxie.pojo"/>
<!-- mapper映射文件位置 -->
<property name="mapperLocations" value="classpath:mappers/*Mapper.xml"/>
</bean>
<!-- mapper扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xiaoxie.mapper"/>
</bean>
<!--事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 开启事务注解 -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
第八步:mapper接口
public interface AccountMapper {
/**
* 保存账户
* @param account
* @return
*/
int insert(Account account);
/**
* 删除账户
* @param actno
* @return
*/
int deleteByActno(String actno);
/**
* 修改账户
* @param account
* @return
*/
int update(Account account);
/**
* 根据账户编号查询账户
* @param actno
* @return
*/
Account selectByActno(String actno);
/**
* 获取所有账户
* @return
*/
List<Account> selectAll();
}
第九步:mapper对应的sql映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xiaoxie.mapper.AccountMapper">
<insert id="insert">
insert into t_act(actno,balance) values(#{actno},#{balance})
</insert>
<delete id="deleteByActno">
delete from t_act where actno=#{actno}
</delete>
<update id="update">
update t_act set balance=#{balance} where actno=#{actno}
</update>
<select id="selectAll" resultType="Account">
select antno,balance from t_act
</select>
<select id="selectByActno" resultType="Account">
select actno,balance from t_act where actno=#{actno}
</select>
</mapper>
第十步:service接口及实现类
public interface AccountService {
/**
* 创建账户
* @param account
* @return
*/
int save(Account account);
/**
* 根据账号注销账户
* @param actno
* @return
*/
int deleteByActno(String actno);
/**
* 更新账户
* @param account
* @return
*/
int update(Account account);
/**
* 根据账号查询账户
* @param actno
* @return
*/
Account getByActno(String actno);
/**
* 查询所有账户
* @return
*/
List<Account> getAll();
/**
* 转账
* @param fromActno
* @param toActno
* @param money
*/
void transfer(String fromActno, String toActno, Double money);
}
@Transactional
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
@Override
public int save(Account account) {
return accountMapper.insert(account);
}
@Override
public int deleteByActno(String actno) {
return accountMapper.deleteByActno(actno);
}
@Override
public int update(Account account) {
return accountMapper.update(account);
}
@Override
public Account getByActno(String actno) {
return accountMapper.selectByActno(actno);
}
@Override
public List<Account> getAll() {
return accountMapper.selectAll();
}
@Override
public void transfer(String fromActno, String toActno, Double money) {
Account fromAct = accountMapper.selectByActno(fromActno);
if (fromAct.getBalance() < money) {
throw new RuntimeException("余额不足");
}
Account toAct = accountMapper.selectByActno(toActno);
toAct.setBalance(toAct.getBalance() + money);
fromAct.setBalance(fromAct.getBalance() - money);
int rows = accountMapper.update(fromAct);
rows += accountMapper.update(toAct);
if (rows != 2) {
throw new RuntimeException("转账失败");
}
}
}
基于以上的操作,我们集成就算完成,接下我们进测试,测试类如下:
public class SMTest {
@Test
public void testSM() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
AccountService accountService = context.getBean("accountService", AccountService.class);
List<Account> accounts = accountService.getAll();
for (Account account : accounts) {
System.out.println(account);
}
System.out.println("===========================================================");
Account account = accountService.getByActno("act-001");
System.out.println(account);
System.out.println("===========================================================");
accountService.transfer("act-001", "act-002", 1000d);
}
}