SpringBoot+Mybatis+MySQL

開始前的準(zhǔn)備:

  • 編輯器IntelliJ IDEA
  • 可以正常使用的MySQL

進(jìn)入正題

1. 使用IDEA構(gòu)建一個SpringBoot項目,注意創(chuàng)建時添加上mysqlmybatis的相關(guān)依賴,生成的SpringBoot項目結(jié)構(gòu)如下圖所示:

關(guān)于如何創(chuàng)建SpringBoot項目請參見SpringBoot入門系列--快速構(gòu)建SpringBoot應(yīng)用

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數(shù)據(jù)庫信息,此處還可以配置服務(wù)器啟動時執(zhí)行的腳本

spring:
  datasource:
    username: root
    password: password
    url: jdbc:mysql://localhost:3306/allen
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 下面的配置是為了在項目啟動時執(zhí)行初始化sql腳本
    continue-on-error: true
    initialization-mode: always
    platform: mysql
    # 執(zhí)行初始化腳本所在路徑
    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. 編寫相關(guān)的 Dao ,Service 和 Controller,結(jié)構(gòu)如下

業(yè)務(wù)代碼

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. 對應(yīng)的有4個rest接口,springboot啟動后可直接訪問

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

至此,一個簡單的SpringBoot+Mybatis+MySQL的demo就完成了,后面針對異常處理,日志記錄,單元測試等內(nèi)容補(bǔ)充完成后放置GitHUB鏈接.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容