SpringBoot2.x集成Mybatis

编程

首先, SpringBoot 版本是 2.3.0.RELEASE, 数据库用的是 MariaDB

1. POM.xml 文件中引入相关包

web项目首先肯定得引 spring-boot-starter-web

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

mybatis 的 starter 引入

<dependency>

<groupId>org.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

<version>2.1.2</version>

</dependency>

MariaDB 数据库驱动引入

<dependency>

<groupId>org.mariadb.jdbc</groupId>

<artifactId>mariadb-java-client</artifactId>

</dependency>

2. properties文件中的配置

server.port=8080

server.servlet.context-path=/demo

spring.datasource.username=root

spring.datasource.password=10010

spring.datasource.url=jdbc:mariadb://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai

spring.datasource.driver-class-name=org.mariadb.jdbc.Driver

# 扫描mapper文件夹下的xml文件

mybatis.mapper-locations=classpath:mapper/*Mapper.xml

# 别名映射包(实体类包)

mybatis.type-aliases-package=com.bytedance.springboot.demo.entity

# 开启属性字段的驼峰映射

mybatis.configuration.map-underscore-to-camel-case=true

# controller返回的json数据中日期字段指定时区

spring.jackson.time-zone=Asia/Shanghai

# 开启sql语句的日志显示

logging.level.com.bytedance.springboot.demo.mapper=debug

3. 创建mapper接口所在的包, 创建*Mapper.xml文件所在的文件夹

mapper接口的方法名和*Mapper.xml文件中的各个语句id对应

<?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="com.bytedance.springboot.demo.mapper.UserMapper">

<select id="queryUser" resultType="User">

select id, username, age, create_time from user

</select>

<insert id="saveUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">

insert into user (username,age,create_time) values (#{username}, #{age}, #{createTime})

</insert>

<update id="updateUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">

update user set age=#{age}, create_time=#{createTime} where username=#{username}

</update>

</mapper>

 

以上是 SpringBoot2.x集成Mybatis 的全部内容, 来源链接: utcz.com/z/517213.html

回到顶部