springboot之整合mybatis

版本:springboot.2.1.6.RELEASE
1、引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.28</version>
    <scope>runtime</scope>
</dependency>

完整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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.linst</groupId>
    <artifactId>springboot-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mybatis</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.27</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、配置文件
application.properties:

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot-mybatis

# 如果mapper.xml配置在了resource目录下, 需要开启如下配置,用来告诉mybatis去哪里扫描mapper。例如 mapper放在了 resource/mapper。
# 其中,mapper目录是自己创建的,用来存放mapper.xml。
# mybatis.mapper-locations=classpath:/mapper/*.xml

3、按照以下目录结构,分别创建bean,controller,mapper文件夹。并在各文件夹创建对应的文件

在这里插入图片描述

1)创建user bean
User:

package cn.linst.springbootmybatis.bean;


public class User {
    private Integer id;
    private String username;
    private String address;

    public Integer getId() {
        return id;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

 // getter, setter
}

2)controller

package cn.linst.springbootmybatis.controller;


import cn.linst.springbootmybatis.bean.User;
import cn.linst.springbootmybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
public class HelloController {
    @Autowired
    UserMapper userMapper;
    
	@Autowired
    UserMapper2 userMapper2;
	// xml方式查询
    @GetMapping("/test1")
    public void test1() {
        List<User> allUser = userMapper.getAllUser();
        System.out.println(allUser);
    }
    
	// 注解方式查询
    @GetMapping("/test2")
    public void test2() {
        List<User> allUser = userMapper2.getAllUser();
        System.out.println(allUser);
    }
}

3)创建UserMapper
有2种方式,一种是xml,一种是注解方式。二选一即可。下面分别列出。

xml方式:
UserMapper:

package cn.linst.springbootmybatis.mapper;

import cn.linst.springbootmybatis.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;


import java.util.List;


@Mapper
public interface UserMapper {
    List<User> getAllUser();
}

在resource目录下,创建一个mapper文件夹,在mapper文件创建UserMapper.xml。
在这里插入图片描述

UserMapper.xml

<?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="cn.linst.springbootmybatis.mapper.UserMapper">
    <select id="getAllUser" resultType="cn.linst.springbootmybatis.bean.User">
        select * from user ;
    </select>
</mapper>

注:UserMapper的xml有2个位置可以放。
①一个就是如上这样直接放在resource目录下,打包时不会被忽略。但是放在resources目录下,又不能自动被扫描到,需要添加额外配置。如上面在resources目录下创建mapper目录用来放mapper文件。
在application.properties添加如下一段:

mybatis.mapper-locations=classpath:mapper/*.xml

②还有一种是放在UserMapper所在包目录下,如下:放在这里的UserMapper.xml会被自动扫描到。不用在配置文件配置。但是要注意的是Maven打包时,java目录下的xml资源在项目打包时会被忽略掉。
在这里插入图片描述

所以在pom.xml文件上要加如下一段:resource中 include进来xml文件。

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>

    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

注解方式:

这里新创建一个UserMapper2。

UserMapper2:

package cn.linst.springbootmybatis.mapper;

import cn.linst.springbootmybatis.bean.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper2 {

    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "address", column = "address")
    })
    @Select("select username as u,address as a,id as id from user where id=#{id}")
    User getUserById(Long id);

    @Select("select * from user where username like concat('%',#{name},'%')")
    List<User> getUsersByName(String name);

    @Insert({"insert into user(username,address) values(#{username},#{address})"})
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Integer.class)
    Integer addUser(User user);

    @Update("update user set username=#{username},address=#{address} where id=#{id}")
    Integer updateUserById(User user);

    @Delete("delete from user where id=#{id}")
    Integer deleteUserById(Integer id);

    @Select("select * from user")
    List<User> getAllUsers();
}

UserMapper、UserMapper2等Mapper创建之后,还要配置mapper扫描。
有两种方式:(选一种即可)
一种是直接在UserMapper2上面添加@Mapper注解,这种方式有就是所有的Mapper都要手动添加,要是少加一个就会报错。(如上面的UserMapper)
另一种是直接在启动类上添加Mapper扫描。如下:

package cn.linst.springbootmybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan(basePackages = "cn.linst.springbootmybatis.mapper")
@SpringBootApplication
public class SpringbootMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }

}

4、运行
访问地址:

http://localhost:8080/test1

控制台输出:

[User{id=1, username='wangwu', address='地址。。。'}]

访问地址:

http://localhost:8080/test2

控制台输出:

[User{id=1, username='wangwu', address='地址。。。'}]

5、源码分析
在SSM整合中,需要自己提供两个Bean,一个SqlSessionFactoryBean,还有一个是MapperScannerConfigurer。
在Spring Boot中,Springboot为我们提供了这2个bean。

org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration类中,部分源码如下:

@org.springframework.context.annotation.Configuration
// 类上的注解可以看出,当 当前类路径下存在SqlSessionFactory、 SqlSessionFactoryBean以及DataSource时,这里的配置才会生效。
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration implements InitializingBean {

  @Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    return factory.getObject();
  }
  
  @Bean
  @ConditionalOnMissingBean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    ExecutorType executorType = this.properties.getExecutorType();
    if (executorType != null) {
      return new SqlSessionTemplate(sqlSessionFactory, executorType);
    } else {
      return new SqlSessionTemplate(sqlSessionFactory);
    }
  }
  @org.springframework.context.annotation.Configuration
  @Import({ AutoConfiguredMapperScannerRegistrar.class })
  @ConditionalOnMissingBean(MapperFactoryBean.class)
  public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
      logger.debug("No {} found.", MapperFactoryBean.class.getName());
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值