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 
原文地址:https://www.cnblogs.com/alexzhang92/p/10405633.html