Spring Boot Mybatis 整合

一、完整的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.example</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>test</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- mysql连接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>

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


</project>

比较关键的是:mysql-connector-java、mybatis-spring-boot-starter,其它的根据使用引用。

二、启动文件 TestApplication.Java

package com.example;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

@SpringBootApplication
@MapperScan("com.example.mapper")
public class TestApplication {
    private static Logger logger = LoggerFactory.getLogger(TestApplication.class);

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return new org.apache.tomcat.jdbc.pool.DataSource();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));

        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
        logger.info("SpringBoot Start Success");
    }
}

类上边添加两个

  • @Configuration注解(该注解类似于spring的配置文件)
  • @MapperScan注解,指定扫描的mapper接口所在的包

注意3点:

  1. 在类上声明MapperScan,这是mybatis-spring-boot-starter在1.1.1引入的类Mapper,从而在mapper接口上不需要任何声明

  2. 配置dataSource、SqlSessionFactory、PlatformTransactionManager,其实默认的都已经配好,这里主要是为了标明Mapper的xml文件存在位置

  3. src/main/resources下的文件,在打包之后,都在工程的根目录。

这个只需要更改两个地方:

  • MapperScan之后的”com.example.mapper”,改成Mapper接口文件所在的包名

  • sqlSessionFactoryBean方法中”classpath:/mybatis/*.xml”,改成Mapper的xml文件存在位置

三、启动配置文件 application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/mytestdb?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-active=10
spring.datasource.max-idle=5
spring.datasource.min-idle=0

这个根据数据库情况配置

四、创建表,添加数据

 CREATE TABLE `test_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `age` tinyint(4) NOT NULL,
  PRIMARY KEY (`id`)
)

INSERT INTO `test_user` VALUES (1, '张三', 18);

五、model

package com.example.dto;

public class User {

    public Long id;

    public String name;

    private int age;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

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

六、在resoures下创建mybatis文件夹,添加Mapper的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="com.example.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="com.example.dto.User">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="TINYINT"/>
    </resultMap>
    <sql id="Base_Column_List">
    id,  name, age
  </sql>
    <select id="getById" resultMap="BaseResultMap" parameterType="java.lang.Long">
        select
        <include refid="Base_Column_List"/>
        from test_user
        where id = #{id,jdbcType=BIGINT}
    </select>

    <insert id="insert" parameterType="com.example.dto.User" useGeneratedKeys="true"
            keyProperty="id">
    insert into test_user (id,name,age)
    values (#{id,jdbcType=BIGINT},
      #{name,jdbcType=VARCHAR}, #{age,jdbcType=TINYINT})
  </insert>
</mapper>

与普通的mybatis配置一样,只是小心:

  • mapper的命名空间(namespace),一定是所对应的接口的包名+类名

  • parameterType和resultMap,与实际匹配

七、接口文件

package com.example.mapper;

import com.example.dto.User;

public interface TestUserMapper {

    /**
     * getById 正常int主键的
     *
     * @param id
     * @return
     */
    User getById(final Long id);

}

注意:

  • 类上没有任何的声明

  • 方法的名称、输入参数书,与xml定义的一直

八、controller

package com.example.web;

import com.example.mapper.TestUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
public class Example {

    @Autowired
    private TestUserMapper testUserMapper;

    @RequestMapping("/getUser/{id}")
    String getUser(@PathVariable Long id) {
        return testUserMapper.getById(id).toString();
    }
   }

九、访问

运行成功后,打开浏览器,输入http://localhost:8080/getUser/1
页面展示TestUser{id=1, name=’张三’, age=18}

    原文作者:MyBatis
    原文地址: https://www.cnblogs.com/lspz/p/6723603.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞