您现在的位置是:首页 >其他 >spring Mybatis网站首页其他

spring Mybatis

若云止水 2024-10-06 00:01:05
简介spring Mybatis

DataBase

show create table account


CREATE TABLE `account` (
  `actno` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `balance` int(11) DEFAULT NULL,
  PRIMARY KEY (`actno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

 

 

 pom.xml

<?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.wsd</groupId>
    <artifactId>spring-mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.11</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.13</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

pojo (Plain Old Java Object)

package com.wsd.bank.pojo;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-11 06:41
 **/
public class Account {
    private String actno;
    private Double balance;

    @Override
    public String toString() {
        return "Account{" +
                "actno='" + actno + ''' +
                ", balance=" + 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;
    }
}

mapper interface

package com.wsd.bank.mapper;

import com.wsd.bank.pojo.Account;

import java.util.List;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-11 07:21
 **/
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.xml 与mapper接口同名且同目录下 

 

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="com.wsd.bank.mapper.AccountMapper">
    <insert id="insert">
        insert into account values(#{actno}, #{balance})
    </insert>
    <delete id="deleteByActno">
        delete from account where actno = #{actno}
    </delete>
    <update id="update">
        update account set balance = #{balance} where actno = #{actno}
    </update>
    <select id="selectByActno" resultType="com.wsd.bank.pojo.Account">
        select * from account where actno = #{actno}
    </select>
    <select id="selectAll" resultType="com.wsd.bank.pojo.Account">
        select * from account
    </select>
</mapper>

service接口

package com.wsd.bank.service;

import com.wsd.bank.pojo.Account;

import java.util.List;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-11 10:40
 **/
public interface AccountService {
    /**
     * 开户
     * @param act
     * @return
     */
    int save(Account act);

    /**
     * 根据账号销户
     * @param actno
     * @return
     */
    int deleteByActno(String actno);

    /**
     * 修改账户
     * @param act
     * @return
     */
    int update(Account act);

    /**
     * 根据账号获取账户
     * @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);
}

service接口实现类

package com.wsd.bank.service.impl;

import com.wsd.bank.mapper.AccountMapper;
import com.wsd.bank.pojo.Account;
import com.wsd.bank.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-11 10:46
 **/
@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    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 fromAct = accountMapper.selectByActno(fromActno);
        if (fromAct.getBalance() < money) {
            throw new RuntimeException("余额不足");
        }
        Account toAct = accountMapper.selectByActno(toActno);
        fromAct.setBalance(fromAct.getBalance() - money);
        toAct.setBalance(toAct.getBalance() + money);
        int count = accountMapper.update(fromAct);
        count += accountMapper.update(toAct);
        if (count != 2) {
            throw new RuntimeException("转账失败");
        }
    }
}

 

jdbc.properties配置文件 

放在类的根路径下

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/myspring
jdbc.username=root
jdbc.password=root
mybatis-config.xml配置文件
放在类的根路径下,只开启日志,其他配置到spring.xml中。
<?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配置文件

<?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.wsd.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">
        <!--mybatis核心配置文件路径-->
        <property name="configLocation" value="mybatis-config.xml"/>
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--起别名-->
        <property name="typeAliasesPackage" value="com.wsd.bank.pojo"/>
    </bean>

    <!--Mapper扫描器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wsd.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>

test:

package com.wsd;

import com.wsd.bank.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-11 13:58
 **/
public class springmybatistest {

    @Test
    public void testSM(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        try {
            accountService.transfer("001", "002", 10000.0);
            System.out.println("转账成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("转账失败");
        }
    }

}

Before testing

After testing

 

"C:Program FilesJavajdk-17injava.exe" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=53095 "-Didea.launcher.bin.path=C:MinecloudIDEA_2019IntelliJ IDEA 2019.1in" -Dfile.encoding=UTF-8 -classpath "C:MinecloudIDEA_2019IntelliJ IDEA 2019.1libidea_rt.jar;C:MinecloudIDEA_2019IntelliJ IDEA 2019.1pluginsjunitlibjunit-rt.jar;C:MinecloudIDEA_2019IntelliJ IDEA 2019.1pluginsjunitlibjunit5-rt.jar;C:MinecloudIDEA_workspacespring_learnspringmybatis arget est-classes;C:MinecloudIDEA_workspacespring_learnspringmybatis argetclasses;C:Minecloudmaven_3.9apache-maven-3.9.0 epoorgspringframeworkspring-context6.0.6spring-context-6.0.6.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epoorgspringframeworkspring-aop6.0.6spring-aop-6.0.6.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epoorgspringframeworkspring-beans6.0.6spring-beans-6.0.6.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epoorgspringframeworkspring-core6.0.6spring-core-6.0.6.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epoorgspringframeworkspring-jcl6.0.6spring-jcl-6.0.6.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epoorgspringframeworkspring-expression6.0.6spring-expression-6.0.6.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epoorgspringframeworkspring-jdbc6.0.6spring-jdbc-6.0.6.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epoorgspringframeworkspring-tx6.0.6spring-tx-6.0.6.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epomysqlmysql-connector-java8.0.30mysql-connector-java-8.0.30.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epocomgoogleprotobufprotobuf-java3.19.4protobuf-java-3.19.4.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epoorgmybatismybatis3.5.11mybatis-3.5.11.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epoorgmybatismybatis-spring3.0.1mybatis-spring-3.0.1.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epocomalibabadruid1.2.13druid-1.2.13.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epojunitjunit4.13.2junit-4.13.2.jar;C:Minecloudmaven_3.9apache-maven-3.9.0 epoorghamcresthamcrest-core1.3hamcrest-core-1.3.jar" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.wsd.springmybatistest,testSM
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@45efc20d] was not registered for synchronization because synchronization is not active
6月 11, 2023 2:17:03 下午 com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl info
信息: {dataSource-1} inited
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@32057e6] will not be managed by Spring
==>  Preparing: select * from account where actno = ?
==> Parameters: 001(String)
<==    Columns: actno, balance
<==        Row: 001, 50000
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@45efc20d]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@62f87c44] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@32057e6] will not be managed by Spring
==>  Preparing: select * from account where actno = ?
==> Parameters: 002(String)
<==    Columns: actno, balance
<==        Row: 002, 0
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@62f87c44]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@525d79f0] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@32057e6] will not be managed by Spring
==>  Preparing: update account set balance = ? where actno = ?
==> Parameters: 40000.0(Double), 001(String)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@525d79f0]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@327120c8] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@32057e6] will not be managed by Spring
==>  Preparing: update account set balance = ? where actno = ?
==> Parameters: 10000.0(Double), 002(String)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@327120c8]
转账成功

Process finished with exit code 0
 

 

 

 

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。