Spring框架集成Mybtis
- 为啥学习集成 Mybatis ORM 框架
- 实现步骤
为啥学习集成 Mybatis ORM 框架
虽然Spring中提供了JDBCTemplate模块,已经很大程度了解决了JDBC代码的复杂度,但它仍然是和Java代码写在一起的。反观 Mybatis 将 Sql 语句写在配置文件中,使得SQL语句和程序实现了松耦合。而且提供了些许标签,使得SQL可以是动态的。在ORM基础上想要更好的用Spring的DI、AOP、事务处理、Junit支持等实现成果,学会使用 Spring 框架集成 Mybatis 是大势所趋。
实现步骤
- 第一步:准备数据库表
- 第二步:IDEA中创建一个模块,并引入以下依赖
- spring-context
- spring-jdbc
- mysql驱动
- mybatis
- mybatis-spring:
mybatis提供的
与spring框架集成的依赖 - druid:德鲁伊连接池
- junit
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>
- 第三步:基于三层架构实现,所以提前创建好所有的包
- XXXX.mapper
- XXXX.service
- XXXX.service.impl
- XXXX.bean
- 第四步:编写bean
Account,按bean规范创建
- 第五步:编写Mapper接口
AccountMapper接口,定义与数据库交互的方法
package com.ncpowernode.spring.mappers;
import com.ncpowernode.spring.bean.Account;
import java.util.List;
public interface AccountMapper {
ListAccount> selectAll();
Account selectByActno(String actno);
int insert(Account account);
int deleteByActno(String actno);
int update(Account account);
}
- 第六步:编写mapper配置文件
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接口和service接口的实现类
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);
ListAccount> 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 ListAccount> 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.properties配置文件
数据库连接池相关信息
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/???
jdbc.username=???
jdbc.password=???
- 第九步:编写mybatis-config.xml核心配置文件
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>
- 第十步:编写spring.xml配置文件
组件扫描
引入外部的属性文件
数据源
SqlSessionFactoryBean配置(注入mybatis核心配置文件路径,指明别名包,注入数据源)
Mapper扫描配置器(指定扫描的包)
事务管理器(DataSourceTransactionManager,注入数据源)
启动事务注解(注入事务管理器)
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);
}
测试结果
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net