前几篇已经简单的学习了mybatis及mbg的简单使用,从此篇文章开始介绍一下mybatis与spring之间的整合及使用,官方的使用文档如下:https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html,本文结合官方文档,进行简单整合使用。
打开idea工具,创建spring initializr项目,pom.xml配置文件如下:
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.7.5version>
<relativePath/>
parent>
<groupId>io.hxjstudygroupId>
<artifactId>java-mybatis2-spring-tinyartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>java-mybatis2-spring-tinyname>
<description>java-mybatis2-spring-tinydescription>
<properties>
<java.version>11java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.2.2version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>com.mysqlgroupId>
<artifactId>mysql-connector-jartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>
project>
直接启动项目,报错如下:
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Process finished with exit code 0
为什么报错,由于我们集成了mybatis项目,但是我们并没有给到他数据源的配置,所以系统就告诉我们,你没配置数据源啊,我启动不了了。虽然可以使用排除启动类的方式:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
来消除错误。
在application.properties文件中添加数据源信息,如下:
# 数据库配置
spring.datasource.url = jdbc:mysql://localhost:3388/db_ddyx?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username = root
spring.datasource.password = root
# 查看查询日志
mybatis.configuration.log-impl = org.apache.ibatis.logging.stdout.StdOutImpl
现在可以正常启动,但是我们还未使用mybatis框架,接下来开始使用框架来查询数据。
我们使用最简单的查询Mapper接口,查询语句直接使用注解的方式实现如下:
package io.hxjstudy.javamybatis2springtiny.mapper;
import io.hxjstudy.javamybatis2springtiny.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM g2_user limit 1")
UserInfo findOne();
}
创建一个返回model类,UserInfo,代码如下:
package io.hxjstudy.javamybatis2springtiny.model;
import lombok.Data;
@Data
public class UserInfo {
//protected String
protected String uid;
protected String unick;
}
代码中我们使用了lombok插件,具体的lombok使用,请参考:https://projectlombok.org/。接下来创建一个最简单的controller来访问:
package io.hxjstudy.javamybatis2springtiny.controller;
import io.hxjstudy.javamybatis2springtiny.mapper.UserMapper;
import io.hxjstudy.javamybatis2springtiny.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping(value = "get_one", method = RequestMethod.GET)
@ResponseBody
public UserInfo getOne(){
UserInfo one = userMapper.findOne();
System.out.println(one);
return one;
}
}
从上面可以看出,我们使用@autowired自动注入userMapper,当然实际生产中一般会有service层来进行更复杂的逻辑处理,此处为了方便使用,简单分层。
点击应用启动:
2022-11-04 18:10:36.087 INFO 15757 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1215 ms
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Property 'mapperLocations' was not specified.
2022-11-04 18:10:36.549 INFO 15757 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2022-11-04 18:10:36.575 INFO 15757 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-11-04 18:10:36.585 INFO 15757 --- [ restartedMain] i.h.j.JavaMybatis2SpringTinyApplication : Started JavaMybatis2SpringTinyApplication in 2.299 seconds (JVM running for 3.075)
访问路径:http://localhost:8080/user/get_one,控制台输出如下:
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@67fea111] was not registered for synchronization because synchronization is not active
2022-11-04 18:19:17.818 INFO 15757 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-11-04 18:19:18.161 INFO 15757 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1542062776 wrapping com.mysql.cj.jdbc.ConnectionImpl@18ed7b11] will not be managed by Spring
==> Preparing: SELECT * FROM g2_user limit 1
==> Parameters:
<== Columns: uid, unick
<== Row: 10010323, 152****2082
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@67fea111]
UserInfo(uid=10010323, unick=152****2082)
界面返回数据:
{"uid":"10010323","unick":"152****2082"}
至此基于org.mybatis.spring.boot整合mybatis的基本使用已实现,实际生产中我们都会使用xml映射文件查询,下面继续学习如何使用映射文件查询。
在官网的配置说明中:https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html,有关于mybatis的详细配置说明:
配置 | 说明 |
---|---|
config-location | Mybatis配置文件的地址 |
check-config-location | 是否检查配置文件地址 true or false |
mapper-locations | mapper映射xml文件地址 |
type-aliases-package | 搜索别名的包,通过,; \t\n”等字符作为分界符 |
type-aliases-super-type | aliases类的父类类型 |
type-handlers-package | 类型转换器的包名 |
executor-type | 执行的模式:SIMPLE(默认), REUSE, BATCH |
default-scripting-language-driver | 默认脚本语言驱动程序类 |
configuration-properties | 配置的外部属性 |
lazy-initialization | 是否启用延迟初始化 |
mapper-default-scope | 被auto-configure扫描的mapper bean的默认范围 |
inject-sql-session-on-mapper-scan | 是否注入一个SqlSessionTemplate或SqlSessionFactorybean |
configuration.* | MyBatis Core配置,与config-location不能同时使用 |
scripting-language-driver.thymeleaf.* | MyBatis Thymeleaf 提供的ThymeleafLanguageDriverConfig bean 的属性键 |
scripting-language-driver.freemarker.* | MyBatis FreeMarker 提供的FreeMarkerLanguageDriverConfig bean 的属性键 |
scripting-language-driver.velocity.* | MyBatis Velocity 提供的VelocityLanguageDriverConfig bean 的属性键 |
更详细的参考,可以查看官方提供各种场景例子:https://github.com/mybatis/spring-boot-starter
同样,放上学习代码地址:https://github.com/redrockfinch/java-mybatis2-spring-tiny