1. 程式人生 > 其它 >IDEA SpringBoot-Mybatis實現增刪改查(CRUD)

IDEA SpringBoot-Mybatis實現增刪改查(CRUD)

SpringBoot-Mybatis

1.新建一個project

  • 新建專案時選擇Spring Initializer。
  • 也可以選擇maven新建,但是不建議新手,因為要自己匯入依賴,會給自己搞懵
  • 開啟IDEA,選擇New Project >>>

2.建立專案檔案結構、選擇jdk版本

  • 一般選擇Java version8
  • 然後下一步 Next

3.選擇專案需要的依賴

首先點選web選擇spring web,再點選SQL選擇MySQL driver 等,然後再一路Finish到新建完成。

4.檢視專案新建完成後的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 https://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.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--web相關-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mybatis相關-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <!--mysql相關-->
        <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>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.yml</include>
                </includes>
                <filtering>true</filtering>
            </resource>

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

    </build>

</project>

pom檔案為預設生成,只需要在其中的build下新增以下程式碼,改程式碼表示在編譯時囊括src/main/resources檔案下的

  1. .properties
  2. .xml
  3. .yml檔案

防止編譯出錯。

<resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.yml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
 
        </resources>

5.修改相關配置檔案src/main/resources

5.1刪除application.properties檔案

5.2建立application.yml配置檔案,該配置檔案用於載入application-dev(後文建立)

spring:
  profiles:
    active: dev

5.3建立application-dev.yml配置檔案

server:
  port: 8081

spring:
  datasource:
    username: root
    password: 123456
    #url中test
    為對應的資料庫名稱
    url: jdbc:mysql://localhost:3307/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapping/*.xml
  type-aliases-package: com.example.demo.entity

#showSql
logging:
  level:
    com.example.demo.mapper: debug

對以上兩個檔案的解釋:
一個專案有很多環境:開發環境,測試環境,準生產環境,生產環境。

    每個環境的引數不同,我們就可以把每個環境的引數配置到yml檔案中,這樣在想用哪個環境的時候只需要在主配置檔案中將用的配置檔案寫上就行如application.yml

    在Spring Boot中多環境配置檔名需要滿足application-{profile}.yml的格式,其中{profile}對應環境標識,比如:

    application-dev.yml:開發環境
    application-test.yml:測試環境
    application-prod.yml:生產環境
    至於哪個具體的配置檔案會被載入,需要在application.yml檔案中通過spring.profiles.active屬性來設定,其值對應{profile}值

6.該專案的檔案結構

在com.example.demo包下分別建立包controller、entity、mapper、service。在resources下建立mapping資料夾。具體的程式碼結構如下圖所示:

7.開始編碼操作

7.1使用navicat新建資料庫test,並在該資料庫下建表user,包含id(int),userName(varchar),passWord(varchar),realName(varchar),插入幾組資料。
7.2 可以直接新建完資料庫




CREATE TABLE `user` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `userName` varchar(32) NOT NULL,
  `passWord` varchar(50) NOT NULL,
  `realName` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

7.2在entity包中新建User.java,使之與資料庫中的欄位一一對應

不用一個一個敲 可以使用idea的生成功能 在空白處點選右鍵

package com.example.demo.entity;

public class User {
    private Integer id;
    private String userName;
    private String passWord;
    private String realName;

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", realName='" + realName + '\'' +
                '}';
    }
}

7.3在mapper包中新建UserMapper介面

package com.example.demo.mapper;
 
import com.example.demo.entity.User;
import org.springframework.stereotype.Repository;
 
import java.util.List;
 
@Repository
public interface UserMapper {
    /**
     * 根據id查詢使用者資訊
     * @param id
     * @return
     */
    User getUserInfo(int id);
    /**
     * 新增使用者
     * @param user
     * @return
     */
    int save (User user);
 
    /**
     * 更新使用者資訊
     * @param user
     * @return
     */
    int update (User user);
 
    /**
     * 根據id刪除
     * @param id
     * @return
     */
    int deleteById (int id);
 
    /**
     * 查詢所有使用者資訊
     * @return
     */
    List<User> selectAll ();
}

7.4在service包中新建實現類UserService.java

package com.example.demo.service;


import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public User getUserInfo(int id) {
        return userMapper.getUserInfo(id);
    }

    public int deleteById(int id) {
        return userMapper.deleteById(id);
    }

    public int Update(User user) {
        return userMapper.update(user);
    }

    public User save(User user) {
        int save = userMapper.save(user);
        return user;
    }

    public List<User> selectAll() {
        return userMapper.selectAll();
    }

}


7.5在controller包中新建訪問類UserController.java

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/testBoot")
public class UserController {

    @Autowired
    private UserService userService;
    
    //    通過使用者id獲取使用者所有資訊
    //    http://localhost:8080/testBoot/getUser/1(此處1為要獲取的id)
    @RequestMapping(value = "getUser/{id}", method = RequestMethod.GET)
    public String GetUser(@PathVariable int id) {
        return userService.getUserInfo(id).toString();
    }
     //   通過使用者id刪除使用者
    //    http://localhost:8080/testBoot/delete?id=1(此處1為要刪除的id)
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(int id) {
        int result = userService.deleteById(id);
        if (result >= 1) {
            return "刪除成功";
        } else {
            return "刪除失敗";
        }
    }
    //根據使用者id更新使用者資訊
    //http://localhost:8080/testBoot/update?id=2&userName=波波&passWord=123456&realName=lalala
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(User user) {
        int result = userService.Update(user);
        if (result >= 1) {
            return "修改成功";
        } else {
            return "修改失敗";
        }
    }
     //   插入新使用者
    //    http://localhost:8080/testBoot/insert?id=100&userName=波波&passWord=123456&realName=lalala
    @RequestMapping(value = "/insert", method = RequestMethod.GET)
    public User insert(User user) {
        return userService.save(user);
    }

    @RequestMapping("/selectAll")
    @ResponseBody
    public List<User> ListUser() {
        return userService.selectAll();
    }
}

7.6在src/main/resources/mapping資料夾下新建UserMapper的對映檔案UserMapper.xml

<?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" >
<mapper namespace="com.example.demo.mapper.UserMapper">


<!--增加使用者資訊-->
    <insert id="save">
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                id,
            </if>
            <if test="userName != null" >
                userName,
            </if>
            <if test="passWord != null" >
                passWord,
            </if>

            <if test="realName != null" >
                realName,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                #{id,jdbcType=INTEGER},
            </if>
            <if test="userName != null" >
                #{userName,jdbcType=VARCHAR},
            </if>
            <if test="passWord != null" >
                #{passWord,jdbcType=VARCHAR},
            </if>
            <if test="realName != null" >
                #{realName,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>
    
    
<!--根據id更改使用者資訊-->
    <update id="update">
        update user
        <set >
            <if test="userName != null" >
                userName = #{userName,jdbcType=VARCHAR},
            </if>
            <if test="passWord != null" >
                passWord = #{passWord,jdbcType=VARCHAR},
            </if>
            <if test="realName != null" >
                realName = #{realName,jdbcType=VARCHAR},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
    
    
    <!--刪除使用者資訊-->
    <delete id="deleteById">
        delete from user where id=#{id}
    </delete>
   
   
<!--查詢使用者資訊-->
    <select id="getUserInfo" resultType="com.example.demo.entity.User">
        select * from user where id = #{id}
    </select>


<!--返回所有使用者資訊-->
    <select id="selectAll" resultType="com.example.demo.entity.User">
        select * from user
    </select>
</mapper>

7.7修改程式的啟動入口類DemoApplication

package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.example.demo.mapper")
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

8.使用Postman驗證

到這裡就完成了增刪改查操作,接下來我們對上面的程式碼在Postman中進行驗證

8.1通過使用者id獲取使用者資訊:

url:  http://localhost:8081/testBoot/getUser/1
(此處1為要獲取的id)

8.2通過使用者id刪除使用者

url:  http://localhost:8081/testBoot/delete?id=1
(此處1為要刪除的id)

8.3根據使用者id更新使用者資訊

url:  http://localhost:8081/testBoot/update?id=2&userName=收藏&passWord=123456&realName=我收藏了



8.4插入新使用者

url:  http://localhost:8081/testBoot/insert?id=120&userName=點贊&passWord=123456&realName=我點讚了


8.5列印所有使用者資訊

url:  http://localhost:8081/testBoot/selectAll
  1. 好了恭喜你,距離百萬年薪又近了一步
  2. 到此一個簡單的SpringBoot-Mybatis專案的增刪查改就做好了

如何快速匯入依賴元件 File >> Plugins >> Marketplace


!!!!!!!!!!!!!!!!!!!!!!!!!!!轉載請註明出處!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!