spring整合Mybatis详细剖析版

文章目录

  • spring整合Mybatis详细剖析版
    • 一.MyBatis注解方式实现增删改查
        • 1.简介Mybatis
          • 1.1 何为Mybatis?
          • 1.2 Mybatis对应的坐标
        • 2.数据库设计
          • 2.1.新建tbl_account
          • 2.2.添加基本数据
        • 3.实体类设计
          • 3.1 建立与之相映射的实体类
        • 4.dao层设计
          • 4.1创建AccounntDao接口
          • 4.2 建立jdbc配置文件
          • 4.3 编写xml读取jdbc配置文件
        • 5.启动类
    • 二.spring整合mybtatis进行数据操作
        • 1.maven坐标导入
        • 2.添加Spring的配置类
        • 3.注解方式开发Dao
        • 4.业务层调用Dao
          • 1.AccountService
          • 2.AccountServiceImpl
        • 5.启动类

spring整合Mybatis详细剖析版

一.MyBatis注解方式实现增删改查

1.简介Mybatis

1.1 何为Mybatis?

Mybatis是一个半ORM(对象关系映射)框架,内部封装JDBC,开发时只需关注SQL语句本身,无需额外关注加载驱动,建立连接,创建statement等繁琐过程,基于SQL语句编程,支持动态SQL语句

1.2 Mybatis对应的坐标

<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.ttcgroupId>
    <artifactId>springdemo2artifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>jarpackaging>

    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.2.10.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.28version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.7version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.12version>
        dependency>
project>

2.数据库设计

2.1.新建tbl_account
CREATE TABLE `tbl_account` (
  `id` int NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `money` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
2.2.添加基本数据
INSERT INTO `boot`.`tbl_account` (`id`, `name`, `money`) VALUES ('1', 'Tom', '1000');
INSERT INTO `boot`.`tbl_account` (`id`, `name`, `money`) VALUES ('2', 'Jerry', '500');

3.实体类设计

3.1 建立与之相映射的实体类
package com.ttc.entity;

public class Account {
    private Integer id;
    private String name;
    private Integer money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + 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 Integer getMoney() {
        return money;
    }

    public void setMoney(Integer money) {
        this.money = money;
    }
}

4.dao层设计

4.1创建AccounntDao接口

用注解方法编写简易SQL语句

package com.ttc.dao;

import com.ttc.entity.Account;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface AccountDao {

    /**
     * 1.查询单个数据
     */
    @Select("select id,name,money from tbl_account where id = #{id}")
    Account getById(Integer id);

    /**
     * 2.添加单个数据
     */
    @Insert("insert into tbl_account(id,name,money) values(#{id},#{name},#{money})")
    void save(Account account);

    /**
     * 3.修改单个数据
     */
    @Update("update tbl_account set name = #{name},money = #{money} where id = #{id}")
    void modify(@Param("name") String name, @Param("money") Integer money, @Param("id") Integer id);

    /**
     * 4.删除单个数据
     */
    @Delete("delete from tbl_account where id = #{id}")
    void remove(Integer id);

    /**
     * 5.查询所有数据
     */
    @Select("select id,name,money from tbl_account")
    List<Account> getAll();

}
4.2 建立jdbc配置文件

在src/main/resources目录下新建jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/boot
jdbc.username=root
jdbc.password=root
4.3 编写xml读取jdbc配置文件

在src/main/resources目录下新建SqlMapConfig.xml

  1. 加载数据库对应的外部配置信息 jdbc.properties
  2. 初始化类型别名 typeAliases
  3. 配置 dataSource
  4. mapper映射

DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <properties resource="jdbc.properties">properties>
    
    <typeAliases>
        
        <package name="com.ttc.entity">package>
    typeAliases>
    
    <environments default="mysql">
        
        <environment id="mysql">
            
            <transactionManager type="JDBC">transactionManager>
            
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            dataSource>
        environment>
    environments>
    
  	<mappers>
        <package name="com.ttc.dao">package>
    mappers>
configuration>

5.启动类

  1. 初始化SqlSessionFactoryBuilder SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder()
  2. 读取xml配置文件 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml")
  3. 获得SqlSessionFactory SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream)
  4. 获取SqlSession SqlSeesion sqlSession = sqlSessionFactory.openSession()
  5. 得到Mapper AccountDao accountDao = sqlSession.getMapper(AccountDao.class)
  6. 关闭SqlSession sqlSession.close()
  • sqlSession才是核心对象
  • 增删改操作需要提交事务
  • sqlSession用完记得关闭
package com.ttc;


import com.ttc.dao.AccountDao;
import com.ttc.entity.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class App {
    public static void main(String[] args) throws IOException {
        //  1.加载SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //  2.获取xml配置文件
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 3.获取SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        // 4.获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 5.用SqlSession获取Dao对象
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        // 6.执行Dao里面的方法
        // 6.1 查询单个数据
        Account ac = accountDao.getById(1);
        System.out.println("1.查询单个数据结果:" + ac);
        // 6.2 添加单个数据
        Account account = new Account();
        account.setId(2);
        account.setName("jerry");
        account.setMoney(3000);
        accountDao.save(account);
        System.out.println("2.添加单个数据成功");
        sqlSession.commit();
        // 6.3 修改单个数据
        accountDao.modify("小猪佩奇", 6666, 3);
        System.out.println("3.修改单个数据成功");
        sqlSession.commit();
        // 6.4 删除单个数据
        accountDao.remove(4);
        System.out.println("4.删除单个数据成功");
        sqlSession.commit();
        // 6.5 查询所有数据
        List<Account> accounts = accountDao.getAll();
        for (Account k : accounts) {
            System.out.println("5.查询所有数据结果:" + k);
        }
        // 7.释放SqlSession资源
        sqlSession.close();
    }
}

结果如下:

1.查询单个数据结果:Account{id=1, name='Tom', money=1000}
2.添加单个数据成功
3.修改单个数据成功
4.删除单个数据成功
5.查询所有数据结果:Account{id=1, name='Tom', money=1000}
5.查询所有数据结果:Account{id=3, name='小猪佩奇', money=6666}
5.查询所有数据结果:Account{id=4, name='青青草原一只羊', money=2000}
5.查询所有数据结果:Account{id=5, name='懒羊羊与灰太狼', money=2000}

Process finished with exit code 0

二.spring整合mybtatis进行数据操作

1.maven坐标导入

配置pom.xml


<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.ttcgroupId>
    <artifactId>springdemo2artifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>jarpackaging>

    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.2.10.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.28version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.7version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.12version>
        dependency>
          
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.2.10.RELEASEversion>
        dependency>
          
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.6version>
        dependency>       
project>

2.添加Spring的配置类

  • SpringConfig
    • @Import
      • @Import({JdbcConfig.class,MybatisConfig.class})
    • @ComponentScan("com.ttc")
    • @PropertySource("classpath:jdbcConfig.properties")
package com.ttc.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Import;

@Configuration
@ComponentScan("com.ttc")
@Import({JdbcConfig.class,MybatisConfig.class})
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
}

  • JdbcConfig
    • 如果给JdbcConfig加上@Configuration,则可被SpringConfig扫描
    • 如果不给其加上@Configuration,则要在SpringConfig添加@Import(JdbcConfig.class)
package com.ttc.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class JdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;


    @Bean
    public DataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}

  • MybatisConfig
    • SqlSessionFactoryBean
    • MappperScannerConfigurer
package com.ttc.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class MybatisConfig {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setTypeAliasesPackage("com.ttc.dao");
        ssfb.setDataSource(dataSource);
        return ssfb;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.ttc.dao");
        return msc;
    }
}

  • jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/boot
jdbc.username=root
jdbc.password=root

3.注解方式开发Dao

  • 这里的@Repository 注解也可以不加
package com.ttc.dao;

import com.ttc.entity.Account;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface AccountDao {

    /**
     * 1.查询单个数据
     */
    @Select("select id,name,money from tbl_account where id = #{id}")
    Account getById(Integer id);

    /**
     * 2.添加单个数据
     */
    @Insert("insert into tbl_account(id,name,money) values(#{id},#{name},#{money})")
    void save(Account account);

    /**
     * 3.修改单个数据
     */
    @Update("update tbl_account set name = #{name},money = #{money} where id = #{id}")
    void modify(@Param("name") String name, @Param("money") Integer money, @Param("id") Integer id);

    /**
     * 4.删除单个数据
     */
    @Delete("delete from tbl_account where id = #{id}")
    void remove(Integer id);

    /**
     * 5.查询所有数据
     */
    @Select("select id,name,money from tbl_account")
    List<Account> getAll();

}

4.业务层调用Dao

1.AccountService
package com.ttc.service;

import com.ttc.entity.Account;

import java.util.List;

public interface AccountService {

    Account getById(Integer id);

    void save(Account account);

    void modify(String name, Integer money, Integer id);

    void remove(Integer id);

    List<Account> getAll();
}
2.AccountServiceImpl
  • 添加@Service
  • 添加@Autowired
package com.ttc.service.impl;

import com.ttc.dao.AccountDao;
import com.ttc.entity.Account;
import com.ttc.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    public Account getById(Integer id) {
        return accountDao.getById(id);
    }

    public void save(Account account) {
        accountDao.save(account);
    }

    public void modify(String name, Integer money, Integer id) {
        accountDao.modify(name, money, id);
    }

    public void remove(Integer id) {
        accountDao.remove(id);
    }

    public List<Account> getAll() {
        return accountDao.getAll();
    }

}

5.启动类

package com.ttc;

import com.ttc.config.SpringConfig;
import com.ttc.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class App {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        AccountService accountService = ctx.getBean(AccountService.class);
        System.out.println(accountService.getById(2));
    }
}

结果如下:

四月 06, 2023 5:06:11 下午 com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl info
信息: {dataSource-1} inited
Account{id=2, name='jerry', money=3000}

Process finished with exit code 0

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