Spirng boot第六篇 整合Mybatis
配置
导入Mybatis包
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
数据库配置
spring:
datasource:
username: root
password: 123456
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/class?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
配置mybatis参数
#整合mybatis
#pojo 路径
mybatis.type-aliases-package=cn.qileyun.springbootmybatis.pojo
#mybatis Mapper映射文件路径
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
项目搭建
添加JOPO
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer uid;
private String username;
private String password;
private String name;
private String avater;
private String introduction;
}
创建mapper目录以及对应的 Mapper 接口
@Mapper
@Repository
public interface UserMapper {
User getByid(Integer id);
}
创建mapper文件
<?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.qileyun.springbootmybatis.mapper.UserMapper">
<select id="getByid" resultType="User" parameterType="int">
select * from t_user where uid = #{id};
</select>
</mapper>
最后测试看看
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
// 查询全部部门
@GetMapping("/getuser/{id}")
public User getDepartment(@PathVariable("id") Integer id){
return userMapper.getByid(id);
}
}
文件目录
总结
具体mybatis使用教程可以参考mybatis的教程