我们通过账户的增删改查和转账案例来整合Spring和Mybatis
项目文件结构
导入相关jar包坐标
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
账户实体类
package domain;
import java.io.Serializable;
/**
* 账户的实体类
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
DAO接口
package dao;
import domain.Account;
import java.util.List;
/**
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存
* @param account
*/
int saveAccount(Account account);
/**
* 更新
* @param account
*/
int updateAccount(Account account);
/**
* 删除
* @param acccountId
*/
int deleteAccount(Integer acccountId);
/**
* 根据名称查询账户
* @param accountName
* @return
*/
List<Account> findAccountByName(String accountName);
}
Service接口
package service;
import domain.Account;
import java.util.List;
public interface IAccountService {
List<Account> findAllAccount();
Account findAccountById(Integer accountId);
int saveAccount(Account account);
int updateAccount(Account account);
int deleteAccount(Integer acccountId);
Account findAccountByName(String accountName);
// 转账
boolean transformAccount(Account a1, Account a2, int money);
}
Service实现类
package service.impl;
import dao.IAccountDao;
import domain.Account;
import service.IAccountService;
import java.util.List;
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
public int saveAccount(Account account) {
return accountDao.saveAccount(account);
}
public int updateAccount(Account account) {
return accountDao.updateAccount(account);
}
public int deleteAccount(Integer acccountId) {
return accountDao.deleteAccount(acccountId);
}
public Account findAccountByName(String accountName) {
List<Account> accountByName = accountDao.findAccountByName(accountName);
if (accountByName.isEmpty())
{
return null;
}
if (accountByName.size() > 1)
{
throw new RuntimeException("查询的记录不唯一!!");
}
return accountByName.get(0);
}
/**
* 转账
* @param a1 转账方
* @param a2 收款方
* @param money 转账金额
* @return
*/
public boolean transformAccount(Account a1, Account a2, int money) {
a1.setMoney(a1.getMoney()-money);
a2.setMoney(a2.getMoney()+money);
updateAccount(a1);
updateAccount(a2);
return true;
}
}
mysql.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/class_db?useUnicode=true&serverTimezone=GMT&useSSL=false
jdbc.username=root
jdbc.password=qwe123
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">
<!-- mybatis的主配置文件 -->
<configuration>
<typeAliases>
<package name="domain"></package>
</typeAliases>
<!-- 指定映射配置文件的位置 -->
<mappers>
<mapper resource="dao/accountDaoMapper.xml"></mapper>
</mappers>
</configuration>
编写映射Mapper文件
<?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="dao.IAccountDao">
<!--配置查询所有-->
<select id="findAllAccount" resultType="Account">
select * from account
</select>
<select id="findAccountById" resultType="Account" parameterType="java.lang.Integer">
select * from account where id=#{accountId}
</select>
<select id="findAccountByName" resultType="Account" parameterType="string">
select * from account where name=#{accountName}
</select>
<insert id="saveAccount" parameterType="Account">
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
select last_insert_id();
</selectKey>
insert into account values(#{id},#{name},#{money})
</insert>
<update id="updateAccount" parameterType="Account">
update account set id=#{id},name=#{name},money=#{money} where id=#{id}
</update>
<update id="deleteAccount" parameterType="java.lang.Integer">
delete from account where id=#{acccountId}
</update>
</mapper>
spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--配置代理的service-->
<bean id="accountServiceImpl" class="service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--表明引用的参数配置文件是mysql.properties-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>
mysql.properties
</value>
</list>
</property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
destroy-method="close">
<!--连接数据库的必备信息-->
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
<!-- 配置初始化大小、最小、最大 -->
<property name="maxActive" value="20" />
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="20" />
</bean>
<!-- 创建SqlSessionFactory MyBatis会话工厂对象 -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置mybatis-confg.xml主配置文件 -->
<property name="configLocation" value="SqlMapConfig.xml" />
</bean>
<!-- 创建IAccount接口的代理对象,创建单个代理对象 -->
<bean id="accountDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!--注入IAccountDao接口-->
<property name="mapperInterface" value="dao.IAccountDao"/>
<!--注入sqlSessionFactory工厂对象-->
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
</tx:attributes>
</tx:advice>
<!-- 配置aop-->
<aop:config>
<!-- 配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* service.impl.*.*(..))"></aop:pointcut>
<!--建立切入点表达式和事务通知的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
测试代码
import domain.Account;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.IAccountService;
import java.util.List;
public class testdemo {
private ApplicationContext ac;
private IAccountService as;
@Before
public void init()
{
ac = new ClassPathXmlApplicationContext("bean.xml");
as = (IAccountService)ac.getBean("accountServiceImpl");
}
@Test
public void testFindall()
{
List<Account> allAccount = as.findAllAccount();
for (Account account : allAccount) {
System.out.println(account);
}
}
@Test
public void testFindbyid()
{
Account accountById = as.findAccountById(1);
System.out.println(accountById);
}
@Test
public void testFindbyname()
{
Account jack = as.findAccountByName("jack");
System.out.println(jack);
}
@Test
public void testSave()
{
Account test = new Account();
test.setName("test");
test.setMoney(2000f);
as.saveAccount(test);
System.out.println(test);
}
@Test
public void testUpdate()
{
Account account = as.findAccountById(3);
account.setMoney(1000f);
as.updateAccount(account);
}
@Test
public void testDelete()
{
as.deleteAccount(3);
}
@Test
public void testTransformaccount()
{
Account account1 = as.findAccountById(1);
Account account2 = as.findAccountById(2);
as.transformAccount(account1,account2,100);
}
}
关于spring和mybatis基于xml的整合就分享到这了,希望大家能够有所收获,欢迎关注。