SpringBoot集成Mybatis

Posted cppdy

tags:

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

1、创建配置文件(application.properties),并添加数据库连接信息

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root

2、在pom.xml中引入Mybatis的jar包

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

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

3、创建测试数据库(test),创建用户表(user),并添加一条数据

技术分享图片

4、创建用户实体类(User)

package com.cppdy.entity;

public class User {

    private int id;
    private String username;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

}

5、创建UserMapper

package com.cppdy.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.cppdy.entity.User;

@Mapper
public interface UserMapper {

    @Select("select * from user where id=#{id}")
    User getUserById(@Param("id") int id);

}

6、在HelloWordController中添加getUserById方法

package com.cppdy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cppdy.entity.User;
import com.cppdy.mapper.UserMapper;

@RestController
public class HelloWordController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("hello")
    public String hello() {

        return "HelloWord";
    }

    @RequestMapping("getUserById")
    public User getUserById() {

        return userMapper.getUserById(1);
    }

}

7、测试getUserById方法

技术分享图片

以上是关于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集成开发