码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot集成Mybatis

时间:2018-11-27 01:19:03      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:classname   request   tco   创建用户   tor   用户   文件   star   version   

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

标签:classname   request   tco   创建用户   tor   用户   文件   star   version   

原文地址:https://www.cnblogs.com/cppdy/p/10023494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!