Spring整合MyBatis小实例(转账功能)

实现步骤

一,引入依赖


    <repositories>
        
        <repository>
            <id>repository.spring.milestoneid>
            <name>Spring Milestone Repositoryname>
            <url>https://repo.spring.io/milestoneurl>
        repository>
    repositories>

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>6.0.0-M2version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>6.0.0-M2version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.8version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.11version>
        dependency>


        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.7version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.2.13version>
        dependency>


        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>6.0.0-M2version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.2version>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>jakarta.annotationgroupId>
            <artifactId>jakarta.annotation-apiartifactId>
            <version>2.1.1version>
        dependency>
    dependencies>

二,基于三层架构,准备所有的包和类

bean层(Account类)

package com.hkd.spring6.bean;

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 +
                '}';
    }
}

service层

接口
package com.hkd.spring6.service;

public interface ActService {
    void transfer(String fromAct, String toAct, double money);
}

实现类
package com.hkd.spring6.service.impl;

import com.hkd.spring6.bean.Account;
import com.hkd.spring6.mapper.ActMapper;
import com.hkd.spring6.service.ActService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("actService")
@Transactional
public class ActServiceImpl implements ActService {

//    @Autowired
//    private ActMapper actMapper;

//    MyBatis为mapper接口自动生成的实现类类名是mapper类首字母小写
    @Resource(name = "actMapper")
    private ActMapper actMapper;

    @Override
    public void transfer(String fromAct, String toAct, double money) {
        Account select1 = actMapper.select(fromAct);
        if (select1.getBalance() < money) {
            throw new RuntimeException("余额不足");
        }
        Account select2 = actMapper.select(toAct);
        select1.setBalance(select1.getBalance() -money);
        select2.setBalance(select2.getBalance() + money);

        int update = actMapper.update(select1);
        update += actMapper.update(select2);

        if (update != 2) {
            throw new RuntimeException("转账失败");
        }
    }
}

mapper层

接口
package com.hkd.spring6.mapper;

import com.hkd.spring6.bean.Account;

public interface ActMapper {
    Account select(String actno);

    int update(Account account);
}

sql映射文件

DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.hkd.spring6.mapper.ActMapper">
    <select id="select" resultType="Account">
        select * from t_bank where actno = #{actno}
    select>

    <update id="update">
        update t_bank set balance = #{balance} where actno = #{actno}
    update>
mapper>

三,配置文件的完成

1.jdbc.properties(数据库相关配置文件)

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis
jdbc.user = root
jdbc.password = hsp

2.MyBatis核心配置文件


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>

3.Spring配置文件


<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.hkd.spring6"/>

    <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.user}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"/>
    bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="datasource"/>
    bean>

    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
        <property name="typeAliasesPackage" value="com.hkd.spring6.bean"/>
        <property name="configLocation" value="mybatis-config.xml"/>
    bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.hkd.spring6.mapper"/>
    bean>

beans>

四,测试代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class TestSm {

    @Autowired
    private ActService actService;

    @Test
    public void testSm(){

        try {
            actService.transfer("act-001","act-002",1);
            System.out.println("转账成功");
        } catch (Exception e){
            System.out.println("转账失败");
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(spring,spring,mybatis,java)