Table of contents
One: Spring6 integrates MyBatis3.5
Step 1: Prepare the database table
Step 2: Create a module in IDEA and introduce dependencies
Step 3: Realize based on the three-tier architecture, so create all packages in advance
Step 5: Write mapper interface
Step 6: Write mapper configuration file
Step 7: Write service interface and service interface implementation class
Step 8: Write the jdbc.properties configuration file
Step 9: Write the mybatis-config.xml configuration file
Step 10: Write the spring.xml configuration file
Step 11: Write a test program, add transactions, and test
Supplement: import of Spring configuration file
One: Spring6 integrates MyBatis3.5
Step 1: Prepare the database table
- Use the t_act table (account table)
Step 2: Create a module in IDEA and introduce dependencies
- spring-context
- spring-jdbc
- mysql driver
- my shoe
- mybatis-spring: The dependency provided by mybatis to integrate with the spring framework
- druid connection pool
- junit
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bjpowernode</groupId>
<artifactId>spring6-015-sm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<!--仓库-->
<repositories>
<!--spring里程碑版本的仓库-->
<repository>
<id>repository.spring.milestone</id>
<name>Spring Milestone Repository</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<!--spring context依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.0-M2</version>
</dependency>
<!--spring-jdbc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.0-M2</version>
</dependency>
<!--mysql驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!--mybatis提供的与spring框架集成的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--druid连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.13</version>
</dependency>
<!--junit依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
</project>
Step 3: Realize based on the three-tier architecture, so create all packages in advance
- com.powernode.bank.mapper
- com.powernode.bank.service
- com.powernode.bank.service.impl
- com.powernode.bank.pojo
Step 4: Write pojo
- Account, property privatization, provides public setter getter and toString.
package com.powernode.bank.pojo;
public class Account {
private String actno;
private Double balance;
public Account() {
}
public Account(String actno, Double balance) {
this.actno = actno;
this.balance = balance;
}
@Override
public String toString() {
return "Account{" +
"actno='" + actno + '\'' +
", 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;
}
}
Step 5: Write mapper interface
AccountMapper interface, define method
package com.powernode.bank.mapper;
import com.powernode.bank.pojo.Account;
import java.util.List;
// 连接接口的实现类不需要写,采用Mybatis动态代理机制生成实现类
public interface AccountMapper {
// 增
int insert(Account account);
// 删
int deleteByActno(String actno);
// 改
int update(Account account);
// 查一个
Account selectByActno(String actno);
// 查所有
List<Account> selectAll();
}
Step 6: Write mapper configuration file
Configure the namespace and the sql corresponding to each method in the configuration file.
Note 1: Create this directory according to the prompt in the figure below. Note that the slash is not a dot; create a new one under the resources directory, and it must correspond to the Mapper interface package.
Note 2: If the interface is called AccountMapper, the configuration file must be AccountMapper.xml; and the name of the namespace namespace must be the fully qualified name of the interface AccountMapper
<?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.powernode.bank.mapper.AccountMapper">
<insert id="insert">
insert into t_act 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="selectByActno" resultType="Account">
select * from t_act where actno = #{actno}
</select>
<select id="selectAll" resultType="Account">
select * from t_act
</select>
</mapper>
Step 7: Write service interface and service interface implementation class
AccountService interface class
package com.powernode.bank.service;
import com.powernode.bank.pojo.Account;
import java.util.List;
public interface AccountService {
// 开户
int save(Account act);
// 根据账号销户
int deleteByActno(String actno);
// 修改账户
int update(Account act);
// 根据账号获取账户
Account getByActno(String actno);
// 获取所有账户
List<Account> getAll();
// 转账
void transfer(String fromActno, String toActno, double money);
}
AccountServiceImpl implementation class, injected into AccountMapper, and incorporated into Spring container management
package com.powernode.bank.service.impl;
import com.powernode.bank.mapper.AccountMapper;
import com.powernode.bank.pojo.Account;
import com.powernode.bank.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional // 添加事务管理
@Service("accountService") // 纳入Spring容器管理
public class AccountServiceImpl implements AccountService {
@Autowired// 注入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 int update(Account act) {
return accountMapper.update(act);
}
@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 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 count = accountMapper.update(fromAccount);
count += accountMapper.update(toAccount);
// 判断转账是否成功
if (count != 2) {
throw new RuntimeException("转账失败!");
}
}
}
Step 8: Write the jdbc.properties configuration file
Database connection pool related information
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=123
Step 9: Write the mybatis-config.xml configuration file
This file can be omitted, and most of the configuration can be transferred to the spring configuration file!
If you encounter system-level configuration related to mybatis, you still need this file, and only log information is configured here!
<?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>
<!--打印mybatis的日志信息、sql语句等信息-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
</configuration>
Step 10: Write the spring.xml configuration file
- component scan
- import external properties file
- data source
- SqlSessionFactoryBean configuration
- Inject mybatis core configuration file path
- Inject data source
- Specify an alias package
- Mapper scan configurator
- Packages to scan
- Transaction Manager DataSourceTransactionManager
- Inject data source
- Enable transaction annotations
- inject transaction manager
Note: When you directly write tag content in the spring.xml file, IDEA will automatically add a namespace for you
<?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.powernode.bank"/>
<!--引入外部的属性配置文件-->
<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>
<!--配置SqlSessionFactoryBean-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
<!--指定mybatis核心配置文件-->
<property name="configLocation" value="mybatis-config.xml"/>
<!--指定别名-->
<property name="typeAliasesPackage" value="com.powernode.bank.pojo"/>
</bean>
<!--Mapper扫描配置器,主要扫描Mapper接口,生成代理类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.powernode.bank.mapper"/>
</bean>
<!--事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--启用事务注解-->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
Step 11: Write a test program, add transactions, and test
package com.powernode.bank.test;
import com.powernode.bank.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SMTest {
@Test
public void testSM(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
try {
accountService.transfer("act-001","act-002",1000);
System.out.println("转账成功");
}catch (Exception e){
e.printStackTrace();
}
}
}
Supplement: import of Spring configuration file
There are multiple spring configuration files, and import can be used in the spring core configuration file. We can define component scanning separately in a configuration file, as follows:
common.xml: Write a separate configuration file, which defines the information scanned by the component
<?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"
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">
<!--组件扫描-->
<context:component-scan base-package="com.powernode.bank"/>
</beans>
Introduced in the core configuration file spring.xm:
<?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">
<!--引入其他的spring配置文件-->
<import resource="common.xml"/>
</beans>
Note: In actual development, service is configured separately in a file, dao is configured separately in a file, and then introduced in the core configuration file, so develop a good habit!