Spring Boot笔记(整合Mybatis)

前言

我们知道Spring Boot为我们做了大量配置,简化了Spring应用的搭建以开发过程。毫无疑问,Spring Boot对Mybatis配置也做了同样的简化。首先,我们来梳理一下利用Mybatis开发需要准备的主要工作。

(1)Mybatis基础配置文件,来配置proerpties、settings、typeAliases等等;

(2)映射器Mapper接口和XML配置文件;

(3)生成Mybatis组件,其中,我们最关注是SqlSessionFactory这一核心组件。

Mybatis核心组件的讲解,可参考我的另一篇博客https://mp.csdn.net/postedit/83211912,希望对读者有帮助。

如果利用到spring,还需要添加一个spring配置文件,当然这会减少Mybatis基础配置文件需要配置的内容。这样一来我们会发现利用Mybatis开发,需要我们进行配置的内容是挺繁琐的,在Mybatis开发中,Spring Boot为了我们做了一些什么配置?接下来我们将通过一个实例进行介绍Spring Boot 整合Mybatis。

1、环境搭建

1.1、开发环境

(1)开发工具:Eclipse Oxygen

(2)JDK版本:1.8.0_1

(3)数据库:MySQL 5.6.24

(4)主要技术:Spring Boot、Mybatis、Maven

1.2、创建项目

准备好开发环境之后,我们来创建一个Maven项目,名称为springboot-mybatis,这里就不逐一介绍创建Maven项目的过程,创建完成之后开始引入依赖。

然后在pom.xml文件中添加web、mybatis、ojdbc6的Maven依赖,其中,Spring Boot与Mybatis整合的依赖,Spring Boot并没有提供,需要利用Mybatis社区开发的starter(地址为:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure)。Maven 如下:

<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.don</groupId>
  <artifactId>srpingboot-mybatis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
	</parent>

	<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>1.3.0</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
	</dependencies>
</project>

接下来添加配置文件,在src/main/resource目录下添加Spring Boot全局配置文件application.properties,并添加数据连接配置信息,我们会在附录中介绍利用Spring Boot整合Mybatis常用的配置项。配置信息如下:

#数据库连接信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
#用户名,利用XXX代替
spring.datasource.username=XXX
#密码,利用XXX代替
spring.datasource.password=XXX

3、代码

3.1、实体

依据数据库信息创建实体类Employee,代码如下:

public class Employee implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private int id;
	private String code;
	private String name;
	private String deptCode;
	private String deptName;

        // 省略get、set和toString方法

}

3.2、Mapper接口

映射器Mapper接口中我们添加两个方法,其中,findAll()方法使用注解的方式实现,并在service层输出该方法的查询结果:

package com.don.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import com.don.domain.Employee;

/**
 * description: 
 *
 * @createtime 2018年11月26日上午9:32:22
 * 
 */
@Mapper
public interface EmployeeMapper {
	
	/**
	 * description:依据id查询Employee.
	 *
	 * @param id
	 * @return
	 * @createtime 2018年11月26日上午9:33:19
	 */
	public Employee findById(Integer id);
	
	/**
	 * description:使用注解版查询所有Employee.
	 *
	 * @return
	 * @createtime 2018年11月26日上午11:03:03
	 */
	@Select("SELECT E.* FROM EMPLOYEE E")
	public List<Employee> findAll();

}

映射器XML文件,employeeMapper.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.don.mapper.EmployeeMapper">

	<select id="findById" parameterType="int"  resultMap="findByIdResult">
		SELECT E.ID,
			E.CODE,
			E.NAME,
			E.DEPT_CODE,
			E.DEPT_NAME
		FROM EMPLOYEE E
		WHERE E.ID=#{id};
	</select>
	
	<resultMap id="findByIdResult" type="com.don.domain.Employee" >
		<id property="id" column="ID"/>
		<result property="code" column="CODE"/>
		<result property="name" column="NAME"/>
		<result property="deptCode" column="DEPT_CODE"/>
		<result property="deptName" column="DEPT_NAME"/>
	</resultMap>

</mapper>

3.3、EmployeeService和EmployeeServiceImpl

EmployeeService接口定义findById方法,代码如下:

package com.don.service;

import com.don.domain.Employee;

/**
 * description: 
 * @createtime 2018年11月26日上午10:05:09
 * 
 */
public interface EmployeeService {

	/**
	 * description:依据主键查询.
	 *
	 * @param id
	 * @return
	 * @createtime 2018年11月26日上午10:07:01
	 */
	public Employee findById(Integer id);

}

EmployeeServiceImpl类实现findById方法,并输入findAll的查询结果,代码如下:

package com.don.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.don.domain.Employee;
import com.don.mapper.EmployeeMapper;
import com.don.service.EmployeeService;

/**
 * description: 
 *
 * @createtime 2018年11月26日上午10:08:09
 * 
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
	
	@Autowired
	private EmployeeMapper employeeMapper;

	@Override
	public Employee findById(Integer id) {
		System.out.println(employeeMapper.findAll());
		return employeeMapper.findById(id);
	}

}

3.4、控制器EmployeeController

package com.don.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.don.domain.Employee;
import com.don.service.EmployeeService;

/**
 * description: 
 *
 * @createtime 2018年11月26日上午10:09:31
 * 
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {
	
	@Autowired
	private EmployeeService employeeService;
	
	/**
	 * description:
	 * 测试地址:http://localhost:8080/employee/findEmployee/1
	 *
	 * @param id
	 * @return
	 * @createtime 2018年11月26日上午10:17:48
	 */
	@RequestMapping("/findEmployee/{id}")
	@ResponseBody
	public Employee findEmployee(@PathVariable("id")Integer id) {
		return employeeService.findById(id);
	};

}

3.5、启动类

package com.don;

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

/**
 * description: 
 *
 * @createtime 2018年11月26日上午9:53:47
 * 
 */
@MapperScan(basePackages= {"com.don.mapper"})
@SpringBootApplication(scanBasePackages= {"com.don"})
public class StartApplication {

	/**
	 * description:
	 *
	 * @param args
	 * @createtime 2018年11月26日上午9:53:47
	 */
	public static void main(String[] args) {
		SpringApplication.run(StartApplication.class, args);
	}

}

此时项目的完整目录结构如下图:

运行启动类在浏览器输入:http://localhost:8088/employee/findEmployee/1测试,发现浏览器为我们显示如下信息:

然后,再查看控制台findAll方法输出的内容:

由上图我们可以发现使用注解的deptCode和deptName没有映射成功,这是因为没有开启开启自动驼峰命名规则,接下来我们为mybatis开启自动驼峰命名规则。有两种方式可完成,一种是直接application.propertites添加:

mybatis.configuration.map-underscore-to-camel-case=true;

另一种,需要额外添加mybatis的配置文件,并告诉Spring Boot新添加的Mybatis配置文件所在的位置。在src/main/resource目录下新建一个文件夹mybatis存放mybatis的配置文件mybatis-config.xml。然后在application.propertites中指定该配置文件的所在位置。这里我们选择第二种:

mybatis配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="mapUnderscoreToCamelCase" value="true"/>  
	</settings>
</configuration>

application.propertites配置文件中mybatis相关配置截图:

启动项目再测试一次,就可发现正常输出deptCode和deptName的内容了:

到这里,利用Spring Boot整合mybatis的简单例子就成功了。

4、总结

由以上的内容可以发现,我没有配置或者获取SqlSessionFactory组件,实际上,Spring Boot已经自动为我们生成好,了并在IoC容器中管理起来,如果我们需要用到该对象直接注入到目标类中即可。

获取代码链接地址:https://pan.baidu.com/s/11rojb0ix8eeblVKYNj2I0Q  提取码:pw78 

5、附录

5.1、Spring Boot整合Mybatis常用的配置项

序号                   配置项                                                    描述
  1mybatis.config-locationMybatis配置文件的位置
  2mybatis.mapper-locationsMapper映射器配置文件的位置
  3mybatis.type-aliases-package实体别名所在的包名
  4mybatis.type-handlers-package类型处理器的包名
  5mybatis.executor-type执行器类型:SIMPLE、REUSE、BATCH
  6mybatis.configuration-propertiesMybatis的properties配置文件
  7mybatis.configuration生Configuration对象的配置项,不能与config-location中的配置重复,比如:mybatis.configuration.lazy-loading-enabled=true

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值