SpringBoot整合mybatis基礎配置Demo

前言:

Spring-boot的入門配置,節約了大量配置的過程,使配置流程變的非常簡潔。

  • Spring-boot 基於Idea 2019.2.4環境搭建
  • MyBatis 整合
  • 簡單增刪改查接口測試

第一步,創建Spring-boot項目

本文基於idea提供的模板創建Spring-boot項目,。而且Spring-boot內置了Tomcat,也不需要配置Spring那一套,所以特別的方便簡潔,特別適合用來建立微站。

創建的步驟:
(1)打開idea -> 選擇菜單File -> New -> Project,打開項目創建面板,選擇Spring Initializr。
在這裏插入圖片描述

(2)點擊Next,進入Project Metadata面板,填寫Group、Artifact、Package等信息。基本上都會給默認配置,除了個別的遵從默認配置就好。
在這裏插入圖片描述
(3) 再次點擊Next,進入Dependencies選擇面板,選擇我們所需要的包,首先Web -> 選擇Spring Web ,SQL -> 選擇 JDBC API ,MYSQL Drivar , Mybatis Framework。

在這裏插入圖片描述
(3)接着點擊Next,進入最後一個面板,填寫Project name,Project Location等相關信息,直接Finish。
在這裏插入圖片描述
(4)等待idea加載模板,等進度條全部加載完畢,說明我們的項目也創建完畢。文件結構如下:
在這裏插入圖片描述
(5)測試我們的項目,在DemoApplication中增加一個@RestController註解,這個註解的意思是@Controller和@RequestBody的結合,意義如下:

  • @Controller 將當前修飾的類注入SpringBoot IOC容器,使得從該類所在的項目跑起來的過程中,這個類就被實例化。當然也有語義化的作用,即代表該類是充當Controller的作用
  • @ResponseBody 它的作用簡短截說就是指該類中所有的API接口返回的數據,甭管你對應的方法返回Map或是其他Object,它會以Json字符串的形式返回給客戶端,本人嘗試了一下,如果返回的是String類型,則仍然是String。
  • @SpringBootApplication相當於@SpringBootConfiguration、@EnableAutoConfiguration和@ComponentScan三個註解合在器的作用,目的是開啓自動配置。

在這裏插入圖片描述
點擊運行,輸入http://localhost:8080/出現如下頁面,代表項目創建成功:
在這裏插入圖片描述

第二步,整合Mabits框架

MyBatis是一款優秀的持久層框架,它支持定製化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 可以使用簡單的 XML 或註解來配置和映射原生類型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 對象)爲數據庫中的記錄。簡單的說MyBatis就是類似Hibernate的ORM框架,相比之下要輕便、靈活的多,更易保證DB訪問的性能。

(1)首先,在pom.xml中添加Matits所需要的dependency,idea會自動去網上集成相應的jar包。

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <!-- 數據庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.0</version>
        </dependency>

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

(2)之後,填寫application.yml文件的相關配置項,設置數據庫相關的配置以及Mabits配置信息,配置文件如下:

#訪問端口號
server:
  port: 8080
#編碼格式
  tomcat.uri-encoding: utf-8
  servlet:
    session:
      timeout: 30m

#數據庫相關配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&serverTimezone=GMT
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
  #應用名稱
  application:
    name: demo
    http:
      encoding:
        charset: UTF-8
        force: true
    jackson:
      default-property-inclusion: non_null

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

(3)接下來,創建一個entity.User實體類,用來映射我們存儲到數據庫中的結構化數據信息;再創建mapper.UserMapper接口類,存儲對應接口;以及service.UserService類;最後在resources下創建一個mapper/UserMapper.xml文件,具體代碼如下:

entity.User

package com.example.demo.entity;
public class User {
    private int id;
    private String username;
    private String password;

    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;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

mapper.UserMapper

package com.example.demo.mapper;

import com.example.demo.entity.User;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Select;

import java.util.List;
public interface UserMapper {

    Integer insertUser(User user);

    Integer batchInsertUser(List<User> users);

    User deleteUser(Integer id);

    User updateUser(User user);

    User selectUser(Integer id);

    List<User> selectAllUser();

}

service.UserService

package com.example.demo.service;


import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

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

    public Integer insertUser(List<User> users) {
        return userMapper.batchInsertUser(users);
    }

    public User deleteUser(Integer id) {
        return userMapper.deleteUser(id);
    }

    public User updateUser(User user) {
        return userMapper.updateUser(user);
    }

    public User selectUser(Integer id) {
        return userMapper.selectUser(id);
    }

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


}

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.example.demo.mapper.UserMapper">

    <resultMap id="userMap" type="com.example.demo.entity.User">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="username" property="username" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
    </resultMap>

    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.example.demo.entity.User">
        insert into t_user (username, password)
        values(#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR})
    </insert>

    <insert id="batchInsertUser" useGeneratedKeys="true" keyProperty="id">
        insert into t_user (username, password) values
        <foreach item="item" collection="list" separator=",">
            (#{item.username}, #{item.password})
        </foreach>
    </insert>

    <delete id="deleteUser" parameterType="java.lang.Integer">
        delete from t_user
        where id = #id
    </delete>

    <update id="updateUser" parameterType="com.example.demo.entity.User">
        update t_user
        set username = #{username, jdbcType=VARCHAR}, password = #{password, jdbcType=VARCHAR}
    </update>

    <select id="selectUser" parameterType="java.lang.Integer" resultMap="userMap">
        select * from t_user
        where id = #{id,jdbcType=INTEGER}
    </select>

    <select id="selectAllUser" resultMap="userMap">
        select * from t_user
    </select>

</mapper>

(4) 最後,創建一個Controller,在Controller中,添加registerfindAllUser接口,用來測試我們的項目對數據庫的連接。代碼如下:

package com.example.demo.web;

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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

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

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register  (HttpServletRequest request) {
        try {
            String userName = request.getParameter("username");
            String password = request.getParameter("password");

            User user = new User();
            user.setUsername(userName);
            user.setPassword(password);
            return userService.insertUser(user)+"";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @RequestMapping("/findAllUser")
    public List<User> findAllUser() {
        return userService.selectUser();
    }
}

(5) 點擊,運行,調用idea集成的REST Client接口測試工具(打開方式:菜單欄 > tools > HTTP Client > Test RESTfull Web Service),對兩個接口進行測試,首先給註冊接口添加username=aaapassword=111兩個參數,然後點擊運行。最後訪問 findAllUser 接口,查看response返回,調用POST訪問方式。
在這裏插入圖片描述
代碼以分享到本人Github倉庫

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章