Spring整合Mybatis纯注解版

Spring整合Mybatis注解版分析(非事务版)

前言
基础配置
编码
导入依赖
配置Bean类
实体类
DAO层接口
Mapper配置文件
测试类
MybatisConfig配置Bean分析
前言
在与spring整合注解版和配置文件差不多,可谓是换汤不换药,分析在配置文件中需要的配置步骤:连接池-创建SqlSessionFactoryBean工厂-MapperScannerConfigure三个配置。
基础配置分析

1. 连接池
2. SqlSessionFactoryBean
3. MapperScannerConfigure

编码分析

1. 实体类
2. 表
3. DAO接口
4. Mapper文件

根据上述分析先进行基础配置在编码,首先要导入jar包
导入依赖

<dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.1.4.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.4version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.5version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.2.11.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.18version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.0.7version>
        dependency>
    dependencies>

创建配置Bean类

package com.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@ComponentScan(basePackages = "com")
@MapperScan(basePackages = "com.dao")
public class MybatisConfig{

    @Autowired
    private MybatisProperties mybatisProperties;
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(mybatisProperties.getDriver());
        dataSource.setUrl(mybatisProperties.getUrl());
        dataSource.setUsername(mybatisProperties.getUsername());
        dataSource.setPassword(mybatisProperties.getPassword());
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources(mybatisProperties.getMapperLocations());
        sqlSessionFactoryBean.setMapperLocations(resources);
        sqlSessionFactoryBean.setTypeAliasesPackage(mybatisProperties.getTypeAliasesPackage());
        return sqlSessionFactoryBean;
    }
}

@Configuration 声明一个Bean配置类功能上与@Component一样Spring在开发过程中为了区分采用的是MVC架构划分的,这里把源码截图下来了可以看到,@Service @Repository 功能也是和@Component一样的。
Spring整合Mybatis纯注解版_第1张图片

@ComponentScan(basePackages = “”)扫描识别注解
@MapperScan(basePackages = “com.dao”)扫描DAO层接口,这个注解代替了MapperScannerConfigurer
private MybatisProperties mybatisProperties,这里的这个属性是单独写的一个类获取配置文件的值,然后配置Bean MybatisConfig类调用以达到解耦的作用。

properties配置文件db.properties

database.driver= com.mysql.jdbc.Driver
database.url= jdbc:mysql://localhost:3306/xuexiao?useSSL=true&useUnicode=true&characterEncoding=UTF8&ServerTimezone=UTC
database.username= MySQL账号
database.password= 密码

properties配置文件mybatis.properties

Resource=com/dao/*Mapper.xml
TypeAliasesPackage=com.pojo

MybatisProperties类读取配置文件

package com.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource({"classpath:db.properties", "classpath:mybatisConfig.properties"})
public class MybatisProperties {

    @Value("${database.driver}")
    private String Driver;
    @Value("${database.url}")
    private String Url;
    @Value("${database.username}")
    private String Username;
    @Value("${database.password}")
    private String Password;
    @Value("${Resource}")
    private String mapperLocations;
    @Value("${TypeAliasesPackage}")
    private String TypeAliasesPackage;

    public String getDriver() {
        return Driver;
    }

    public void setDriver(String driver) {
        Driver = driver;
    }

    public String getUrl() {
        return Url;
    }

    public void setUrl(String url) {
        Url = url;
    }

    public String getUsername() {
        return Username;
    }

    public void setUsername(String username) {
        Username = username;
    }

    public String getPassword() {
        return Password;
    }

    public void setPassword(String password) {
        Password = password;
    }

    public String getMapperLocations() {
        return mapperLocations;
    }

    public void setMapperLocations(String mapperLocations) {
        this.mapperLocations = mapperLocations;
    }

    public String getTypeAliasesPackage() {
        return TypeAliasesPackage;
    }

    public void setTypeAliasesPackage(String typeAliasesPackage) {
        TypeAliasesPackage = typeAliasesPackage;
    }
}

@Component 创建对象
@PropertySource获取配置文件的内容以Key value ,属性值可以是一个数组
基础配置文件以注解的形式就是以上配置,以下就是业务编码
本次实现的是一个查询操作
实体类

package com.pojo;


public class Student {
//| sid | sname | sex  | age  | cid
    private  int sid;
    private String sname;
    private String sex;
    private int age;
    private int cid;

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getCid() {
        return cid;
    }

    public void setCid(int cid) {
        this.cid = cid;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", cid=" + cid +
                '}';
    }
}

DAO层接口

package com.dao;

import com.pojo.Student;

import java.util.List;

public interface StudentMapper {
    List<Student> Query();
}

Mapper配置文件



<mapper namespace="com.dao.StudentMapper">
    <select id="Query" resultType="Student">
        select * from student;
    select>
mapper>

测试

package com.Test;

import com.dao.StudentMapper;
import com.pojo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.List;

public class StudentTest {

    @Test
    public void QueryStudentAnno(){
       ApplicationContext ctx = new AnnotationConfigApplicationContext("com.config");
        StudentMapper mapper = ctx.getBean("studentMapper", StudentMapper.class);
        List<Student> query = mapper.Query();
        for(Student student : query){
            System.out.println(student);
        }
    }
}

以上就是Spring整合Mybatis纯注解版
MybatisConfig配置Bean分析

 @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
        //创建对象
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources(mybatisProperties.getMapperLocations());
        sqlSessionFactoryBean.setMapperLocations(resources);
        sqlSessionFactoryBean.setTypeAliasesPackage(mybatisProperties.getTypeAliasesPackage());
        return sqlSessionFactoryBean;
    }

MapperLocations编码是通配的写法
sqlSessionFactoryBean.setMapperLocations(Resource);查看源码可以看到这里接收的是一个Resource类型的值并且是可变的。
Spring整合Mybatis纯注解版_第2张图片
通过 PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources(mybatisProperties.getMapperLocations());的getResouces()方法传入一个使用通配类型的写法,然后将所有的匹配的Mapper.xml存到Resource数组中,然后再传给sqlSessionFactoryBean.setMapperLocations(resources);

总结

使用注解开发已经称为主流的开发模式,虽然注解开发大大简化了程序的开发,但是也屏蔽了很多问题,当程序出问题时很难快速准确的找到错误原因,所以在学会注解开发的同时还要知道,由配置文件配置的开发。

其他内容
学习不是即学即用,而是用的时候已经掌握。
Spring整合Mybatis(配置事务两种方式)
Spring整合Mybats及其事务
Java学习之初疑问
Markdown基本语法
MySQL设置级联操作
Spring工厂实现原理

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