Springboot 集成 Mybatis

314 阅读1分钟

「这是我参与11月更文挑战的第7天,活动详情查看:2021最后一次更文挑战」。

首先添加 MybatisMysql 依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

创建 dao 层文件

@Mapper
@Repository
public interface LearnMapper {
    Long insert(Learn learn);
    List<Learn> queryList(Learn learn);
}

然后在 resources/mapper/ 下创建 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="top.younote.learn.Mapper.LearnMapper">
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        insert into
            learn_mybatis (user_name,nick_name,age)
        values (#{userName},#{nickName},#{age})
    </insert>
    <select id="queryList" parameterType="top.younote.learn.pojo.Learn" resultType="top.younote.learn.pojo.Learn">
        select
            id,
            user_name,
            nick_name,
            age
        from
            learn_mybatis
        where
            user_name = #{userName}
    </select>
</mapper>

application.yml 下新增

server:
  port: 8089
spring:
  #数据库连接配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&useSSL=false
    username: root
    password: dly3230

#mybatis的相关配置
mybatis:
  #mapper配置文件
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: top.younote.learn.pojo
  #开启驼峰命名
  configuration:
    map-underscore-to-camel-case: true
# mybatis 显示 sql 语句,便于调试,top.younote.learn.Mapper 是 dao 层包名,修改成自己的路径
logging:
  level:
    top.younote.learn.Mapper: debug

Mybatis 插入数据返回插入的那条数据的 id

只需要增加 useGeneratedKeyskeyProperty 属性即可,其中 keyProperty 对应自增序列对应的字段,这里是 id。 这个操作实际上是把插入到数据库的 id 属性赋值到入参里面的,所以这个需要从入参里面获取,而不是 insert 返回值(插入成功结果始终是 1 ),这里是通过 learn.getId() 获取 id

<insert id="insert" useGeneratedKeys="true" keyProperty="id">
    insert into
        learn_mybatis (user_name,nick_name,age)
    values (#{userName},#{nickName},#{age})
</insert>

日志打印 Sql 语句

logging:
  level:
    top.younote.learn.Mapper: debug