4、集成mybatis

您所在的位置:网站首页 mybatis如何执行批处理 4、集成mybatis

4、集成mybatis

2023-05-30 11:25| 来源: 网络整理| 查看: 265

添加依赖 pom.xml com.mysql mysql-connector-j runtime com.baomidou mybatis-plus-boot-starter 3.5.3.1 org.projectlombok lombok 1.18.24 provided 添加数据库连接配置 src/main/resources/application.yml spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/{数据库名}?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 username: {账号} password: {密码} hikari: connection-init-sql: set names utf8mb4 # 使用utf8mb4字符集 mvc: pathmatch: matching-strategy: ant_path_matcher # 配置这个来防止swagger报错

因为要使用utf8mb4编码,因此配置了connection-init-sql,在characterEncoding直接配置成utf8mb4会报错

创建实体类,用于存储查询出来的数据

src/main/java/com/lazysleep/base/entity/User.java

package com.lazysleep.base.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @Data @TableName("u_user") public class User { @TableId(value = "id", type = IdType.AUTO) private Integer id; private String name; private Integer age; private String email; }

涉及到三个注解

@Data:对类成员变量增加 get set 方法 @TableName:对应数据库表名 @TableId:标记主键

mybatis-plus更多内容见 简介 | MyBatis-Plus (baomidou.com)

创建Mapper src/main/java/com/lazysleep/base/mapper/UserMapper.java package com.lazysleep.base.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.lazysleep.base.entity.User; import org.springframework.stereotype.Repository; @Repository public interface UserMapper extends BaseMapper { } 在入口文件添加MapperScan注解 package com.lazysleep.base; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.lazysleep.base") public class BaseApplication { public static void main(String[] args) { SpringApplication.run(BaseApplication.class, args); } }

此注解需要传入一个包名,作为扫描起点,如过不添加,后续mapper无法注入

改造原来的FooController package com.lazysleep.base.controller; import com.lazysleep.base.entity.User; import com.lazysleep.base.mapper.UserMapper; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; 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; @Api(tags = "Foo控制器") @RestController @RequestMapping("/foo") public class FooController { @Autowired private UserMapper userMapper; @GetMapping("foo") @ApiOperation(value = "Foo接口") public User foo() { return userMapper.selectById(1); } }

使用@Autowired注入UserMapper实例,并在方法中调用selectById方法查询数据库用户表id=1的用户数据并返回。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3