SpringBoot入门 整合Mybatis

前言:

上一篇讲了SpringBoot的基本搭建

今天来整合一下mybatis框架,依然是使用Eclipse和Maven

SpringBoot配置mybatis有两种方式,一种为注解方式,一种为传统的用xml文件来存sql语句,今天介绍的是第二种

在开始整合之前,可以参考之前写的一篇博客:简单搭建Mybatis框架实例

这篇博客没有使用Spring等其他框架,就是新建java application然后只搭建了mybatis

在不使用其他框架,单纯搭建mybatis框架时,项目结构是这样的:

SpringBoot入门 整合Mybatis

一个dao接口文件   UserDao.java
一个pojo实体类      User.java
一个映射配置文件  UserMapper.xml,专门配置sql语句的

PS:这三个文件是Mybatis的必备三要素,mybatis-Generator自动生成代码也是生成这三个文件,基本上是一张数据库表对应三个文件

还有两个文件:

一个全局配置文件SqlMapConfig.xml 
一个测试文件

测试文件是程序入口,任何整合了mybatis框架的程序都会有一个入口
而SqlMapConfig.xml 则是配置数据源和映射配置文件 XXXMapper.xml文件的,在不同程序中可以有不同的配置方法

但是不管怎么样,我的粗浅理解是,只要是Mybatis框架,就基本上得有这五个文件,三要素+全局配置文件+程序入口

 

准备:

首先得准备好数据库和表:

数据库为firstdb,表名为Student_t:

SpringBoot入门 整合Mybatis

新增一条记录:

 SpringBoot入门 整合Mybatis

 

开始:

1、创建SpringBoot项目,和上篇一样的步骤 

不同的是在选择项目dependencies的页卡那里,除了勾选Web->Web之外

再勾选Sql->Mysql,和Sql->Mybatis, 因为使用的是mysql数据库

SpringBoot入门 整合Mybatis

 

先看下完成后的最终项目结构图:

SpringBoot入门 整合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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.2.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>cn.kevin</groupId>
	<artifactId>mybatisPro</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot01</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.0.0</version>
		</dependency>

	
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.0</version>
		</dependency>
	</dependencies>

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

</project>

 druid连接池是需要手动加上的,其余的则是通过创建项目时添加的依赖项,springboot自动帮我们生成的,如mybatis这些依赖

接下来我们一步步构建

 

 

2、 先创建三要素

三要素我是通过mybatis-Generator自动生成的代码

如何使用Mybatis-Generator生成代码,参考另一篇博文(点击跳转),这里不再赘述

实体类:Student  

package cn.kevin.entity;

public class Student {
    private Integer id;

    private String StudentName;

    private String password;

    private Integer age;

    //geter  setter 省略....
}

dao接口文件  StudentDao 

package cn.kevin.Dao;

import cn.kevin.entity.Student;

public interface StudentDao {
    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

还有就是Sql配置文件 StudentMaaper.xml ,在src/main/resource目录下

<?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.kevin.Dao.StudentDao" >
    <resultMap id="BaseResultMap" type="cn.kevin.entity.Student" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="Student_name" property="StudentName" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
    </resultMap>
    <sql id="Base_Column_List" >
        id, Student_name, password, age
    </sql>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" />
        from Student_t
        where id = #{id,jdbcType=INTEGER}
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from Student_t
        where id = #{id,jdbcType=INTEGER}
    </delete>
    <insert id="insert" parameterType="cn.kevin.entity.Student" >
        insert into Student_t (id, Student_name, password,
        age)
        values (#{id,jdbcType=INTEGER}, #{StudentName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
        #{age,jdbcType=INTEGER})
    </insert>
    <insert id="insertSelective" parameterType="cn.kevin.entity.Student" >
        insert into Student_t
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                id,
            </if>
            <if test="StudentName != null" >
                Student_name,
            </if>
            <if test="password != null" >
                password,
            </if>
            <if test="age != null" >
                age,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                #{id,jdbcType=INTEGER},
            </if>
            <if test="StudentName != null" >
                #{StudentName,jdbcType=VARCHAR},
            </if>
            <if test="password != null" >
                #{password,jdbcType=VARCHAR},
            </if>
            <if test="age != null" >
                #{age,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="cn.kevin.entity.Student" >
        update Student_t
        <set >
            <if test="StudentName != null" >
                Student_name = #{StudentName,jdbcType=VARCHAR},
            </if>
            <if test="password != null" >
                password = #{password,jdbcType=VARCHAR},
            </if>
            <if test="age != null" >
                age = #{age,jdbcType=INTEGER},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="cn.kevin.entity.Student" >
        update Student_t
        set Student_name = #{StudentName,jdbcType=VARCHAR},
        password = #{password,jdbcType=VARCHAR},
        age = #{age,jdbcType=INTEGER}
        where id = #{id,jdbcType=INTEGER}
    </update>
</mapper>

 

三、创建Controller  -- StudentController.java

package cn.kevin.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.kevin.entity.Student;
import cn.kevin.service.StudentService;

@RestController
@EnableAutoConfiguration
public class StudentController {

	@Resource
	private StudentService studentService;
	
	@RequestMapping("/showStudent")
	public Student showStudent(HttpServletRequest request, Model model) {
		
		int StudentId = Integer.parseInt(request.getParameter("id"));
		Student student = this.studentService.getStudentById(StudentId);
		return student;
	}
}

拦截/showStudent,并且读取参数id,  然后调用service层,根据id查询数据库

 

四、创建Service层

创建接口 StudentService.java

package cn.kevin.service;
import cn.kevin.entity.Student;

public interface StudentService {

    public Student getStudentById(int StudentId);

    boolean addStudent(Student record);
}

创建service实现类----StudentServiceImpl

package cn.kevin.service;

import org.springframework.stereotype.Service;
import cn.kevin.Dao.StudentDao;
import cn.kevin.entity.Student;
import javax.annotation.Resource;

@Service
public class StudentServiceImpl implements  StudentService {

	@Resource
	private StudentDao studentDao;

	public Student getStudentById(int StudentId) {
		return studentDao.selectByPrimaryKey(StudentId);
	}

	public boolean addStudent(Student record) {
		boolean result = false;
		try {
			studentDao.insertSelective(record);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}

 

五.全局配置文件 application.yml

OK,现在mybatis三要素,service层,controller层都有了,还差什么?

还差一个全局配置文件,一般是配置数据源和映射配置文件的,在大多数地方都默认叫SqlMapConfig.xml

但在SpringBoot中,在本文中,我们新建一个application.yml

#默认使用配置
spring:
  profiles:
    active: dev

#mapperLocations指的路径是src/main/resources
mybatis:
  typeAliasesPackage: com.kevin.entity
  mapperLocations: classpath:*.xml


---

#开发配置
spring:
  profiles: dev

  datasource:
    url: jdbc:mysql://localhost:3306/firstdb?characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 使用druid
    type: com.alibaba.druid.pool.DruidDataSource

application.yml主要配置了数据源dataSource,和数据库连接池Druid ,指定mybatis映射文件的地址(mybatisLocation),既XXXMapper.xml的路径,springboot会扫描改路径下的xml

 

六、在程序入口加入mappersacn

好了,程序入口就是cn.kevin.DemoApplication.java里面的main函数,这个文件是系统默认创建的,我们需要为其添加mappersacn,让其扫描Dao层接口

package cn.kevin;

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

@SpringBootApplication
@MapperScan("cn.kevin.Dao")
public class DemoApplication {

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

 

我们启动试一下

SpringBoot入门 整合Mybatis

 

 

遇到的问题:

1.Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

提示我们com.mysql.jdbc.Driver已经不使用了,要使用最新的com.mysql.cj.jdbc.Driver

所以修改yml文件: com.mysql.jdbc.Driver 改成  com.mysql.cj.jdbc.Driver 即可

2.java.sql.SQLException: The server time zone value '?D1ú±ê×?ê±??' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.13.jar:8.0.13]

所以修改yml文件:  url: jdbc:mysql://localhost:3306/firstdb  后面加上 ?characterEncoding=utf-8&serverTimezone=UTC