【SSM】Spring6(十二.Spring6集成MyBatis3.5)

文章目录

  • 1. 实现步骤
  • 2.具体实现
    • 2.1 准备数据库
    • 2.2 创建模块,引入依赖
    • 2.3 创建包
    • 2.4 创建Pojo类
    • 2.5 编写mapper接口
    • 2.6 编写Mapper配置文件
    • 2.7 编写service接口和service接口实现类
    • 2.8 编写jdbc.properties配置文件
    • 2.9 编写mybatis-config.xml配置文件
    • 2.10编写spring.xml配置文件
    • 2.11 测试
  • 3.Spring配置文件的import

1. 实现步骤

2.具体实现

2.1 准备数据库

使用IDEA的DataBase插件连接数据库。
【SSM】Spring6(十二.Spring6集成MyBatis3.5)_第1张图片
【SSM】Spring6(十二.Spring6集成MyBatis3.5)_第2张图片
【SSM】Spring6(十二.Spring6集成MyBatis3.5)_第3张图片

2.2 创建模块,引入依赖


<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.0modelVersion>

    <groupId>com.sdnugroupId>
    <artifactId>spring6-016-smartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>jarpackaging>

    
    
    <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.37version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.10version>
        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>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.2version>
            <scope>testscope>
        dependency>
    dependencies>

    <properties>
        <maven.compiler.source>17maven.compiler.source>
        <maven.compiler.target>17maven.compiler.target>
    properties>

project>

2.3 创建包

【SSM】Spring6(十二.Spring6集成MyBatis3.5)_第4张图片

2.4 创建Pojo类

package com.sdnu.bank.pojo;

public class Account {
    private String actno;
    public 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 +
                '}';
    }
}

2.5 编写mapper接口

package com.sdnu.bank.mapper;

import com.sdnu.bank.pojo.Account;

import java.util.List;

public interface AccountMapper { //该接口的实现类不用写,mybatis通过动态代理机制生成
    int insert(Account account);
    int deleteByActno(String actno);
    int update(Account account);
    Account selectByActno(String actno);
    List<Account> selectAll();
}

2.6 编写Mapper配置文件


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sdnu.bank.mapper.AccountMapper">

    <select id="insert">
        insert into t_act values (#{actno, #{balance})
    select>

    <delete id="delete">
        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>

2.7 编写service接口和service接口实现类

package com.sdnu.bank;

import com.sdnu.bank.pojo.Account;

import java.util.List;

public interface AccountService {
    /**
     * 开户
     * @param act
     * @return
     */
    int save(Account act);

    /**
     * 销毁
     * @param actno
     * @return
     */
    int deleteByActno(String actno);

    /**
     * 修改账户
     * @param actno
     * @return
     */
    int modify(Account actno);

    /**
     * 查询账户
     * @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);
}

package com.sdnu.bank.service.impl;

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

import java.util.List;

@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 modify(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("转账失败");
        }
    }
}

2.8 编写jdbc.properties配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring6
jdbc.username=root
jdbc.password=root

2.9 编写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="logImpl" value="STDOUT_LOGGING"/>
    settings>
configuration>

2.10编写spring.xml配置文件


<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.sdnu.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>
    
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="configLocation" value="mybatis-config.xml"/>
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="typeAliasesPackage" value="com.sdnu.bank.pojo"/>
    bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.sdnu.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>

2.11 测试

package com.sdnu.spring6.test;

import com.sdnu.bank.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("act001", "act002", 10000.0);
            System.out.println("转账成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("转账失败");
        }
    }

}

3.Spring配置文件的import

引入其它配置文件

<import resource="common.xml"/>

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