1. 程式人生 > >SpringBoot 操作資料庫實戰

SpringBoot 操作資料庫實戰

簡介:本部落格建立在已經搭好SpringBoot框架的基礎上,開發一個新增郵件使用者、查詢使用者的介面。其中,新增和查詢使用者都要進行資料庫的操作

首先,在資料庫中建立一個數據庫表

這裡以新建emails表為例,包括id、email、phoneNum三個欄位:

CREATE TABLE `emails` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(255) NOT NULL,
  `phoneNum` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

開啟SpringBoot專案,新增pom.xml依賴

<!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
            <!-- 請不要使用1.0.0版本,因為還不支援攔截器外掛 -->
</dependency> <!-- druid阿里巴巴資料庫連線池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.15</version> <!-- 請不要使用1.0.20版本,會報java.sql.SQLException: validateConnection false -->
</dependency> <!-- MySql資料庫驅動 --> <dependency> <groupId> mysql</groupId> <artifactId> mysql-connector-java</artifactId> <version> 5.0.5</version> </dependency>

這裡加入了一個阿里的druid驅動,druid是一個可監控的驅動,可以說是一個為監控而生的資料庫驅動

配置資料庫

在application.properties中新增資料庫的相關配置,如下:

# 驅動配置資訊
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://localhost:3306/eunomia
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver

# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.chinawayltd.bean

程式碼

1、在bean目錄下,新建一個實體類User.class,

/**
 * Created by pc on 2018/6/30.
 */
public class User {
    private int id;
    private String email;
    private String phoneNum;

    public int getId() {
        return id;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhoneNum() {
        return phoneNum;
    }

    public void setPhoneNum(String phoneNum) {
        this.phoneNum = phoneNum;
    }
}

2、在專案的resources目錄下新建一個mapper資料夾,在mapper資料夾裡新建一個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.chinawayltd.mapper.UserMapper">
    <!--目的:為Dao介面方法提供SQL語句-->

    <!--對映實體物件-->
    <resultMap id="UserResultMap" type="com.chinawayltd.bean.User">
        <id property="id" column="id" />
        <result property="email" column="email" />
        <result property="phoneNum" column="phoneNum" />
    </resultMap>

    <insert id="insertUser" >
        INSERT INTO emails(email, phoneNum)
        VALUES (#{user.email}, #{user.phoneNum})
    </insert>

    <select id="findByEmail" resultType="User">
        SELECT * FROM emails WHERE email = #{email}
    </select>

    <select id="findPhoneByEmail" resultType="java.lang.String">
        SELECT phoneNum FROM emails WHERE email = #{email}
    </select>

</mapper>

3、新建一個操作資料庫介面類,UserMapper.class:

package com.chinawayltd.mapper;
import com.chinawayltd.bean.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Mapper;
/**
 * Created by zggdczfr on 2017/1/22.
 */
@Mapper
public interface UserMapper {

    /**
     * 插入使用者
     * @param user
     * @return
     */
    int insertUser(@Param("user") User user);

    /**
     * 查詢某個使用者
     * @param email
     * @return
     */
    User findByEmail(String email);

    //通過郵件查詢使用者的手機號
    String findPhoneByEmail(String email);
}

4、新建一個數據服務類,UserService.class:

import com.chinawayltd.bean.User;
import com.chinawayltd.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by pc on 2018/6/30.
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public int add(User user) {
        return userMapper.insertUser(user);
    }

    public User findByEmail(String email){
        return userMapper.findByEmail(email);
    }

    public String findPhoneByEmail(String email){
        return userMapper.findPhoneByEmail(email);
    }

}

5、新建一個Controller類,TestController.class:

import com.chinawayltd.bean.User;
import com.chinawayltd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created by pc on 2018/6/30.
 */
@RestController
@RequestMapping("/test")
public class TestController {

    //引入userService
    @Autowired
    private UserService userService;  

    //新增使用者
    @RequestMapping(value="/add",method= RequestMethod.POST)
    public String add(@RequestBody User user){
        userService.add(user);
        return "新增成功!";
    }

    //通過郵件查詢使用者
    @RequestMapping("/findUserByEmail")
    public User findUserByEmail(@RequestParam(value="email") String email){
        User user = userService.findByEmail(email);
        return user;
    }

    //通過郵件查詢使用者的手機號
    @RequestMapping("/findPhoneByEmail")
    public String findPhoneByEmail(@RequestParam(value="email") String email){
        return userService.findPhoneByEmail(email);
    }

}

介面測試

1、執行Application.class,啟動服務
2、在postman裡進行介面測試:
(1)傳送post請求新增郵件使用者,如下圖:
這裡寫圖片描述

(2)通過郵件查詢使用者,如下圖:
這裡寫圖片描述

(3)通過郵件查詢使用者的手機號,如下圖:
這裡寫圖片描述

完…