Springboot2.x 使用 MyBatis 链接 Mysql 数据库并开启SQL日志

参考

  1. Windows 外网无法访问mysql之防火墙设置
  2. Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could no
  3. 解决org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)问题
  4. mybatis官方文档
  5. 开启sql日志

引言

早在今年年初的时候实践过一次 springboot 使用 MyBatis 连接 mysql 数据库(2021.01.25),时间过了半年没有使用,忘记了,又复习了一遍。

环境

操作系统:macos
sprongboot版本:2.3.7.RELEASE
mysql版本:8.0.18
mybatis版本:2.1.4
编辑器:idea

正文

  1. pom.xml 引入依赖
<dependencies>
    //pom.xml追加
    <dependencies>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.4</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
		// 8.0.33 以后引入的是 mysql-connector-j (2023/12/15)
        <artifactId>mysql-connector-java</artifactId>
        // mysql 8.+版本需要指定版本号
        <version>8.0.18</version>
    </dependency> 
</dependencies>
  1. pom.xml 配置打包时不忽略 xml映射文件(防止xml文件不打包报错)
    <build>
<!--        防止xml映射文件被忽略-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
     </build>
  1. 配置文件 application.properties 中配置数据库连接信息与MyBatis配置
# 数据库连接地址
spring.datasource.url=jdbc:mysql://你的IP地址:3306/suddenly_online_learning_platform?characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=你的账号
spring.datasource.password=你的密码
# 注意mysql5是com.mysql.jdbc.Driver (2023/12/15)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#下面这些内容是为了让MyBatis映射
#指定Mybatis的Mapper文件 (对应位置是 resources/mappers )
mybatis.mapper-locations=classpath:mappers/*xml
#指定Mybatis的实体目录
mybatis.type-aliases-package=com.xxxxxx.suddenlynlinelearningplatform.mybatis.entity
# 开启日志 https://blog.csdn.net/u014641168/article/details/120947282 (2023/12/16)
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl 
  1. 创建实体 ,对应位置 entity/Student.java
@Data
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer id;
    /**
     * 账号
     */
    private String account;
    /**
     * 密码
     */
    private String password;
    /**
     * 用户名
     */
    private String name;
    /**
     * 头像
     */
    private String avatarUrl;
    /**
     * 性别
     */
    private Byte gender;
    /**
     * 手机号
     */
    private String phoneNumber;
    /**
     * 手机号验证状态
     */
    private byte phoneVerificationStatus;
    /**
     * 账号
     */
    private String bewrite;
    /**
     * 创建时间
     */
    private Date createdAt;
    /**
     * 更新时间
     */
    private Date updatedAt;
}
  1. 创建学生 Maper 接口,对应位置 maper/StudentMaper.java
@Mapper
public interface StudentMaper {
    Student findById(Integer id);
}
  1. 创建 xml 映射文件,对应位置 resources/mappers/StudentMaper.xml,注意这里的xml文件名要与我们的 maper/*.java 文件名相同
<?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">
<!--这里对应Maper接口类的命名空间-->
<mapper namespace="com.xxxx.suddenlynlinelearningplatform.mapper.StudentMaper">
<!--    这里 resultType 对应响应实体类,也可以是其他类型,请参考文档-->
    <select id="findById" parameterType="int" resultType="com.xxxxxx.suddenlynlinelearningplatform.entity.Student">
        select * from `students` where id = #{id}
    </select>
</mapper>
  1. 创建学生 service,对应位置 service/StudentService.java
@Service
public class StudentService {
    @Autowired
    StudentMaper studentMaper;

    public Student findById(Integer id){
        return studentMaper.findById(id);
    }
}
  1. 入口文件增加maper扫描注解

如果Mapper接口类已经设置了@Mapper注解,则会自动发现,无需此步骤

@SpringBootApplication
/**
 * 开启缓存,需要显示的指定
 */
@EnableCaching
/**
 * Maper映射扫描
 */
@MapperScan("com.xxx.xxxx.mapper")
public class SuddenlyNlineLearningPlatformApplication {

    public static void main(String[] args) {
        SpringApplication.run(SuddenlyNlineLearningPlatformApplication.class, args);
    }

}
  1. 测试
@Api(tags = "测试类", value = "测试类")
@RestController
@RequestMapping("v1/test")
public class Test {

    @Autowired
    StudentService studentService;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public Student index(){
        return  studentService.findById(1);
    }
}

总结

  1. 如果mysql位于虚拟机,请记得检测端口是否打开,参考:Windows 外网无法访问mysql之防火墙设置
    2.xml与接口类的名字要一直,xml内的命名空间引入也要一致。
posted @ 2021-08-04 11:55  夏秋初  阅读(166)  评论(0编辑  收藏  举报