spring-boot学习:十、spring-boot集成mybatis

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/guangcaiwudong/article/details/100778523

在java代码中写sql,而且还要对结果集手动进行处理,如果是简单的sql还好,复杂一点想想都头皮发麻。为了便于解耦,让代码更整洁、层次更清晰,后期维护更好实施,我们引入mybatis。

一、简单集成,目录结构如下:
在这里插入图片描述

1. pom.xml中增加jar包

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

2.创建mybatis mapper接口, 如UserMapper
@Mapper用来标记mybatis的接口类需要扫描注册。
@Repository 本不需要,但是在IDEA中使用Mapper类时会有一个错误提示,没有实现类,加上后没有该问题;eclipse中不需要加。

package com.kevin.springbootstudy.dao;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface UserMapper {

    @Select("select name from user where id = #{id}")
    String findNameById(String id);
}

3. JdbcController中使用mapper

package com.kevin.springbootstudy.controller;

import com.kevin.springbootstudy.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class JdbcController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "getUser")
    public Object getUser(@RequestParam(value = "id")String id){
        return userMapper.findNameById(id);
    }

    @RequestMapping("/dbtime")
    public Object dbtime(){
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(jdbcTemplate.queryForObject("select now() ", Date.class));
    }

}

4. 测试ok
http://127.0.0.1:8081/getUser?id=1 返回Kevin

二、深入集成

上面简单使用mybatis,有几个问题:
1)虽然sql换了地方,但是还是通过注解写在java中,耦合度还是很高;
2)每一个Mapper都要加上注解@Mapper比较麻烦
3)是否可以配置mybatis的一些参数

1.在application.properties中加入mybatis配置

# mybatis
# 定义Java Bean类型所在目录,在没有注解@Alias("user")的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名
mybatis.type-aliases-package=com.kevin.springbootstudy.dao.model
# 指定 MyBatis 的 XML 映射器文件的位置
mybatis.mapper-locations=classpath*:com/**/mappers/**/*.xml
#自定义类型处理器目录
#mybatis.type-handlers-package=
#是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射
mybatis.configuration.map-underscore-to-camel-case=true
#为驱动的结果集获取数量设置一个提示值
#mybatis.configuration.default-fetch-size=100
#设置超时时间,它决定驱动等待数据库响应的秒数
mybatis.configuration.default-statement-timeout=30

2. 在Application.java中加入mybatis接口扫描目录@MapperScan,这样就不需要每个接口都加上注解@Mapper

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

@SpringBootApplication
@PropertySource(value={"classpath:database.properties"})
@MapperScan("com.kevin.springbootstudy.dao")
public class SpringBootStudyApplication{

    public static void main(String[] args) {

        SpringApplication app = new SpringApplication(SpringBootStudyApplication.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);

    }
}

3. mybatis目录结构
在这里插入图片描述

1)增加User类

package com.kevin.springbootstudy.dao.model;

public class User {

    private String id;

    private String name;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

2)Mapper接口中定义方法

package com.kevin.springbootstudy.dao;

import com.kevin.springbootstudy.dao.model.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper {

    @Select("select name from user where id = #{id}")
    String findNameById(@Param("id") String id);

    User findUserById(@Param("id") String id);
}

3)创建sql映射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="com.kevin.springbootstudy.dao.UserMapper">

    <select id="findUserById" resultType="user" parameterType="java.lang.String">
        select * from user where id = #{id}
    </select>

</mapper>

注意:
1)这里能直接使用resultType=“user”,是因为配置了mybatis.type-aliases-package
2)xml文件与接口文件不在同一目录下,是因为配置了mybatis.mapper-locations,否则必须在同一目录才能被找到

4)还有很重要的一点,pom.xml需要加入java中其他文件格式的依赖

在eclipse中直接运行可以不需要,但是打包时依然需要;IDEA运行的时候就需要,两者编译机制不同,如果没有的话,调用mybatis时会报错:Invalid bound statement (not found),也就是找不到方法对应的sql语句,本质上来说是没有加载到对应的xml文件。
还一种方式是将mapper.xml文件都放在src/main/resources目录下。

<resource>
    <directory>src/main/java</directory>
    <includes>
        <include>**/*.xml</include>
        <include>**/*.properties</include>
        <include>**/*.txt</include>
    </includes>
</resource>

5. 测试

package com.kevin.springbootstudy.controller;

import com.kevin.springbootstudy.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class JdbcController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "getUser")
    public Object getUser(@RequestParam(value = "id")String id){
        return userMapper.findUserById(id);
    }

    @RequestMapping("/dbtime")
    public Object dbtime(){
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(jdbcTemplate.queryForObject("select now() ", Date.class));
    }

}

访问http://127.0.0.1:8081/getUser?id=1,返回{“id”:“1”,“name”:“kevin”}

注:以上测试偷懒没写service层,实际中需要写,并加入事务管理

参考:
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/# springboot集成mybatis
http://www.mybatis.org/spring/zh/index.html spring集成mybatis

猜你喜欢

转载自blog.csdn.net/guangcaiwudong/article/details/100778523