美文网首页
SpringBoot+Mybatis+MySQL

SpringBoot+Mybatis+MySQL

作者: 凌风TM | 来源:发表于2019-07-14 23:50 被阅读0次

开始前的准备:

  • 编辑器IntelliJ IDEA
  • 可以正常使用的MySQL

进入正题

1. 使用IDEA构建一个SpringBoot项目,注意创建时添加上mysqlmybatis的相关依赖,生成的SpringBoot项目结构如下图所示:

关于如何创建SpringBoot项目请参见SpringBoot入门系列--快速构建SpringBoot应用

SpringBoot_Structure
pom.xml如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lingfeng</groupId>
    <artifactId>spring-boot-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-mybatis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <mybatis-spring-boot-starter.version>2.0.1</mybatis-spring-boot-starter.version>
    </properties>

    <dependencies>
        <!-- spring-boot-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- mybatis-spring-boot -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring-boot-starter.version}</version>
        </dependency>

        <!-- mysql driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. 在applicaiton.yml(或者是application.properties)中配置MySQL数据库信息,此处还可以配置服务器启动时执行的脚本

spring:
  datasource:
    username: root
    password: password
    url: jdbc:mysql://localhost:3306/allen
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 下面的配置是为了在项目启动时执行初始化sql脚本
    continue-on-error: true
    initialization-mode: always
    platform: mysql
    # 执行初始化脚本所在路径
    schema: classpath:schema.sql
    schema-username: root
    schema-password: password

3. 编写Mapper

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM USER_TAB WHERE NAME = #{name}")
    User findByName(@Param("name") String name);

    @Insert("INSERT INTO USER_TAB(NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    @Update("UPDATE USER_TAB SET NAME = #{name} ,AGE = #{age} WHERE ID = #{id}")
    int updateUserById(@Param("id") Long id, @Param("name") String name, @Param("age") Integer age);

    @Delete("DELETE FROM USER_TAB WHERE ID = #{id}")
    int deleteUserById(@Param("id") Long id);

}

4. 编写相关的 Dao ,Service 和 Controller,结构如下

业务代码

5. 在Controller层定义的如下几个接口:

package com.lingfeng.contolller.impl;

import com.lingfeng.contolller.IUserController;
import com.lingfeng.entity.User;
import com.lingfeng.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: lingfeng
 * @Date: 2019/7/14 23:28
 */

@RestController
@RequestMapping(path = "/users")
public class UserControllerImpl implements IUserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserControllerImpl.class);

    @Autowired
    private IUserService userService;

    @GetMapping
    @Override
    public User getUserByName(@RequestParam("name") String name) {
        LOGGER.info("Search user by name: {}", name);
        User user = userService.getUserByName(name);
        LOGGER.info("Found user is {}", user.toString());
        return user;
    }

    @PostMapping
    @Override
    public void createUser(@RequestBody User user) {
        userService.insertUserInfo(new User(user.getName(), user.getAge()));
        LOGGER.info("create user is {}", user.toString());
    }

    @PutMapping
    @Override
    public void updateUser(@RequestBody User user) {
        userService.updateUser(user);
    }

    @DeleteMapping
    @Override
    public void deleteUser(@RequestParam("id") Long id) {
        userService.deleteUser(id);
    }

}

6. 对应的有4个rest接口,springboot启动后可直接访问

  • 新增User:
curl -X POST -H 'Content-Type: application/json' -i http://localhost:8003/users --data '{
"name":"wangwu",
"age":14
}'
  • 根据name查询User
curl -X GET -i 'http://localhost:8003/users?name=wangwu'
  • 根据id更新User
curl -X PUT -H 'Content-Type: application/json' -i http://localhost:8003/users --data '{
"id":1,
"name":"wangwu",
"age":15
}'
  • 根据id删除User
curl -X DELETE -i 'http://localhost:8003/users?id=1'

至此,一个简单的SpringBoot+Mybatis+MySQL的demo就完成了,后面针对异常处理,日志记录,单元测试等内容补充完成后放置GitHUB链接.

相关文章

  • Springboot+mybatis的CRUD

    搭建一套框架出来: Springboot+Mybatis+Mysql 用的Restful的风格 增删改查对应的是:...

  • SpringBoot使用Mybatis-PageHelper

    前言 之前一篇文章介绍了《SpringBoot+Mybatis+MySql学习》的整合,这一片扩展一下Mybati...

  • SpringBoot+mybatis+mysql

    1.依赖: 2.配置问题: 大家都知道,springBoot的有点就是解决了各种xml的配置问题 3. 这个问题很...

  • Springboot+mybatis+mysql

    在pom.xml文件内将依赖改成compile就行 11.首先创建实体类在com.example.yvans下建立...

  • SpringBoot+Mybatis+MySQL

    开始前的准备: 编辑器IntelliJ IDEA 可以正常使用的MySQL 进入正题 1. 使用IDEA构建一个...

  • springboot-mybatis-mysql-errorCo

    笔者这两天准备搭建一个基于springboot+mybatis+mysql的微服务作为银行业务的基础服务,过程非常...

  • SpringBoot+Mybatis+MySql学习

    介绍一下SpringBoot整合mybatis,数据库选用的是mysql。 首先创建数据库 建表以及插入初始数据(...

  • springboot+Mybatis+mysql示例

    https://start.spring.io 新建项目 pom.xml 文件增加mysql和mybatis配置 ...

  • springboot+mybatis+mysql整合

    一.通过idea建立工程 二.配置文件1.在resources文件夹下建立config文件夹,并创建mybatis...

  • SpringBoot+MyBatis+MySQL读写分离

    1 在发布模块打包,而不是父模块上打包 比如,以下项目目录: 如果要发布 api 就直接在它的模块上打包,而不是在...

网友评论

      本文标题:SpringBoot+Mybatis+MySQL

      本文链接:https://www.haomeiwen.com/subject/quhwkctx.html