本文主要讲解了SpringBoot继承Mybatis的过程,分为基于xml形式和基于注解的形式来讲解。
MyBatis
MyBatis是一个持久层框架,可以让开发者的主要精力放在sql上,通过Mybaits提供的映射方式,自由灵活的生成满足需要的sql语句,使用简单的XML或注解来配置和映射原生信息,将接口和Java的POJOS映射成数据库中的记录
1.MyBatis的配置
1.1 依赖导入
SpringBoot集成MyBatis,需要导入mybatis-spring-boot-starter和mysql的依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
1.2 application.yml配置
server:
port: 8081
spring:
profiles:
active: dev
---
server:
port: 8082
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.example.springdemo1.dao
configuration:
map-underscore-to-camel-case: true # 驼峰命名规范
# mapper映射文件位置
mapper-locations: classpath:mybatis/*.xml
logging:
config: logback.xml
level:
com.example.springdemo1.dao: trace
---
server:
port: 8083
spring:
profiles: test
这里使用的连接池是SpringBoot自带的hikari。
2.基于xml的整合
使用原始的xml方式,需要新建UserMapper.xml文件,在上面的application.yml配置文件中,我们已经定义了xml文件的路径:classpath:mapper/*.xml
,所以我们在resources目录下新建一个mybatis文件夹,然后创建一个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.example.springdemo1.dao.UserMapper">
<select id="selectUser" resultType="com.example.springdemo1.pojo.User">
select * from mybatis.user
</select>
<select id="selectUserById" resultType="com.example.springdemo1.pojo.User">
select * from mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="com.example.springdemo1.pojo.User">
insert into mybatis.user value(#{id},#{name},#{pwd})
</insert>
</mapper>
接下来我们写一个User实体类:
package com.example.springdemo1.pojo;
public class User {
private int id;
private String name;
private String pwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
}
这里我们再写一个UserMapper.java接口
package com.example.springdemo1.dao;
import com.example.springdemo1.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
List<User> selectUser();
User selectUserById(int id);
}
我们写一个Controller来测试一下:
package com.example.springdemo1.controller;
import com.example.springdemo1.dao.UserMapper;
import com.example.springdemo1.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/test")
public class testController10 {
@Autowired
private UserMapper userMapper;
@GetMapping("/selectUser")
public String selectUser(){
List<User> users = userMapper.selectUser();
for (User user : users) {
System.out.println(user);
}
return "success";
}
@GetMapping("/selectUserById")
public String selectUserById(){
User user = userMapper.selectUserById(1);
System.out.println(user);
return "success";
}
}
启动项目,在浏览器中输http://localhost:8082/test/selectUserById
即可查询到id为1的用户信息
这里需要注意一下:SpringBoot如何知道这个Mapper呢?一种方法是在上面的mapper层对应的类上面添加@Mapper注解
即可,但是这种方法有个弊端,当我们有很多个mapper时,那么每一个类上面都得添加@Mapper注解,另一种比较简便的方法是在SpringBoot启动类上添加@MapperScan注解
,来扫描一个包下的所有mapper
package com.example.springdemo1;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableCaching//开启缓存
@EnableScheduling//开启定时任务
@MapperScan("com.example.springdemo1.dao")
public class Springdemo1Application {
public static void main(String[] args) {
SpringApplication.run(Springdemo1Application.class, args);
}
}
这样的话,com.example.springdemo1.dao
包下的所有mapper都会被扫描到了。
3.基于注解的整合
基于注解的整合就不需要xml配置文件了,MyBatis主要提供了@Select,@Insert,@Update,@Delete四个注解。使用方法是在注解后面跟上对应的sql语句即可
,举个例子:
@Select("select * from user where id = #{id}")
User getUser(int id);
这跟xml文件中写sql语句是一样的,这样就不需要xml文件了,如果是两个参数,我们需要使用@Param注解来指定每一个参数的对应关系
,举个例子
@Select("select * from user where id = #{id} and name = #{name}")
User getUserByIdAndName(@Param("id") int id,@Param("name") String name);
可以看出,@Param指定的参数应该要和sql中{}取得参数名相同,不同则取不到,可以在controller中自行测试一下。
@GetMapping("/getUser")
public String getUser(){
User user = userMapper.getUser(1);
System.out.println(user);
return "success";
}
@GetMapping("/getUserByIdAndName")
public String getUserByIdAndName(){
User user = userMapper.getUserByIdAndName(1,"lyh1");
System.out.println(user);
return "success";
}
有个问题需要注意一下,一般我们在设计表字段后,都会根据自动生成工具生成实体类,这样的话,基本上实体类是能和表字段对应上的,最起码也是驼峰对应的,由于在上面配置文件中开启了驼峰的配置,所以字段都是能对得上的,但是,万一对不上的呢,我们也有解决办法,使用@Results注解来解决
@Select("select * from user where id = #{id}")
@Results({
@Result(property = "username",coloum="user_name"),
@Result(property="password",coloum="pass_word")
})
User getUser(int id);
@Results中的@Result注解是用来指定每一个属性和字段的对应关系,这样的话就可以解决上面说的这个问题了,当然了,我们也可以xml和注解相结合使用,因为有时候xml方便,有时候注解方便,比如就上面这个问题来说,如果我们定义了上面的这个UserMapper.xml,那么我们完全可以使用@ResultMap注解来替代@Results注解,如下:
@Select("select * from user where name=#{name}")
@ResultMap("BaseResultMap")
User getUser(String name);
@ResultMap注解中的值从哪来呢,对应的是UserMapper.xml文件中定义时对应的id值
<resultMap id="BaseResultMap" type="com.example.springdemo1.pojo.User">