springBoot集成MyBatis

Posted qichueng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springBoot集成MyBatis相关的知识,希望对你有一定的参考价值。

Spring Boot 集成MyBatis

1、创建数据库和表,创建对应的domain对象

 

 

2、添加依赖

<!--mybatis spring boot 集成-->

<dependency>

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

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

<!-- 这里的版本要是1.1.1或更高版本, -->

    <version>1.1.1</version>

</dependency>

<!--mybatis spring boot 集成 需要使用mysql驱动做测试-->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>5.1.36</version>

</dependency>

 

3、书写配置 在application.yml添加如下配置

#连接池的配置

spring:

  datasource:

    driver-class-name: com.mysql.jdbc.Driver

    url: jdbc:mysql://localhost:3306/springboot?characterEncoding=utf-8

    username: root

    password: root

#mybatis配置mapper.xml文件位置以及包扫描

mybatis: 

  mapper-locations: classpath*:mapper/*.xml  #mapper文件扫描

  type-aliases-package: com.springboot.domain  #别名扫描

 

4、编写mapper接口,添加注解

 

5、编写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">

<!--客户映射 指定到dao接口 -->

<mapper namespace="com.springboot.mapper.UserMapper">

<insert id="addUser" parameterType="User">

insert into

user(username,password) values(#{username},#{password})

</insert>

<update id="updateUser" parameterType="User">

update user set

username=#{username},password=#{password} where id=#{id}

</update>

<select id="findUserById" parameterType="int" resultType="User">

SELECT id,username,password from user WHERE id=#{id}

</select>

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

SELECT id,username,password from user

</select>

<delete id="deleteUserById" parameterType="int">

delete from user where id=#{id}

</delete>

</mapper>

 

6、测试

http://localhost:8088/addUser?username=zhangsan&password=123456

http://localhost:8088/addUser?username=张三&password=123456789  支持中文

http://localhost:8088/findUserList 

http://localhost:8088/findUserById?id=2 

http://localhost:8088/updateUser?id=2&username=张三&password=admin 

http://localhost:8088/deleteUserById?id=1 

 

以上是关于springBoot集成MyBatis的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot集成mybatis以及自动化测试代码实现

SpringBoot集成mybatis

springboot-简单集成mybatis

01.springboot集成mybatis与jsp

SpringBoot 集成MyBatis-Plus提示反序列化异常:cannot deserialize from Object value (no delegate- or property-bas

Springboot 和 Mybatis集成开发