1、搭建Spring Boot工程
创建名称为springboot-mybatis-01的maven或者springboot项目
2、引入mybatis起步依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
3、编写Mybatis相关配置
#数据源信息
spring:
datasource:
url: jdbc:mysql://localhost:3306/edu_db?serverTimezone=GMT%2B8&useUnicode=true&useSSL=false&characterEncoding=utf8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
4、定义表和实体类
package cn.hxzy.erp.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private int userId;
private String userName;
private String userPhone;
}
5、编写实现代码
5.1 编写数据访问层接口mapper
@Mapper
public interface UserMapper {
List<User> findAll();
}
5.2 创建业务逻辑层service
业务逻辑层接口
package cn.hxzy.erp.service;
import cn.hxzy.erp.domain.User;
public interface UserService {
User getUserById(int userId);
}
业务逻辑层实现类
package cn.hxzy.erp.service.impl;
import cn.hxzy.erp.domain.User;
import cn.hxzy.erp.mapper.UserMapper;
import cn.hxzy.erp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(int userId) {
return userMapper.getUserById(userId);
}
}
5.3 创建控制层controller
package cn.hxzy.erp.controller;
import cn.hxzy.erp.domain.User;
import cn.hxzy.erp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/select/{userId}")
public User getUserById(@PathVariable int userId){
User user = userService.getUserById(userId);
System.out.println(user);
return user;
}
}
5.4 检查启动类
添加@MapperScan(“cn.hxzy.erp.mapper”)注解
package cn.hxzy.erp;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("cn.hxzy.erp.mapper")
public class SpringbootMybatis01Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatis01Application.class, args);
}
}
6、编写mybatis的配置文件
在yml中进行如下配置:
# mybatis别名
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml #如果使用了xml配置mybatis的方式,则需要添加路径
type-aliases-package: cn.hxzy.erp.domain
configuration:
auto-mapping-behavior: full
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
7、配置xml的映射文件
配置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="cn.hxzy.erp.mapper.UserMapper">
</mapper>
8、单元测试
测试数据访问层
@SpringBootTest
class Demo22ApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
User user = userMapper.getUserById(1);
System.out.println(user);
}
}
9、集成druid数据源步骤
9.1 导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
9.2 yml配置
spring:
#数据源配置
datasource:
#1.指定数据源类型
type: com.alibaba.druid.pool.DruidDataSource
#驱动类
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/shop_db?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false
username: root
password: root
druid:
#2.连接池配置
#初始化连接池的连接数量 大小,最小,最大
initial-size: 20 #初始化连接数
min-idle: 20 #最小空闲连接数,一般设置和initial-size一致
max-active: 100 #最大活动连接数
max-wait: 10000 #配置获取连接等待超时的时间
time-between-eviction-runs-millis: 90000 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
min-evictable-idle-time-millis: 1800000 # 配置一个连接在池中最小生存的时间,单位是毫秒
# SQL 心跳指令
validation-query: SELECT 1 FROM DUAL
test-while-idle: true #快速的check其是否过期.当判断是过期的链接进行校验
test-on-borrow: true #如果为true(默认false),当应用向连接池申请连接时,连接池会判断这条连接是否是可用的。
test-on-return: false # 如果为true(默认为false),就是当应用使用完连接,连接池回收连接的时候会判断该连接是否还可用
10、注解开发
//查询
@Results({
@Result(property = "userId",column = "userId",id = true),
@Result(property = "userName",column = "userName"),
@Result(property = "passWord",column = "passWord")
})
@Select("select * from user")
//插入
@Insert("INSERT INTO USER(userName,PASSWORD) VALUES(#{userName},#{passWord})")
@SelectKey(keyProperty = "userId",resultType = Integer.class,before = false,statement ="select last_insert_id()")