Spirng boot第六篇 整合Mybatis

10 篇文章 0 订阅
9 篇文章 0 订阅

配置

导入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的教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值