Spring boot 整合 Mybatis + Thymeleaf開發web(一)

**最近工作上時間有點多,然後自己就學習了一下Spring boot,外加上Mybatis,在實際開發中都是比較常用的,所以這篇寫一下SpringBoot整合Mybatis。
一、數據準備**

CREATE TABLE `bookbean` (
  `name` varchar(255) DEFAULT NULL,
  `author` varchar(255) DEFAULT NULL,
  `price` varchar(255) DEFAULT NULL
) 


INSERT INTO `bookbean` VALUES ('張三', 'ZHANGSAN', '16');
INSERT INTO `bookbean` VALUES ('李四', 'LISI', '34');
INSERT INTO `bookbean` VALUES ('王五', 'WANGWU', '43');

二、引入依賴

<?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>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <mybatis.version>3.4.5</mybatis.version>
        <mybatis-spring.version>1.3.1</mybatis-spring.version>
        <mysql.version>6.0.6</mysql.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 熱部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- mybatis依賴 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>

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

        <!-- mysql驅動包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

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

        <!-- 數據源 -->
        <dependency>  
            <groupId>com.alibaba</groupId>  
            <artifactId>druid</artifactId>  
            <version>1.0.29</version>  
        </dependency>
    </dependencies>

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


</project>

三、數據庫配置文件

  項目application.properties內容如下:

banner.charset=UTF-8
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
#配置設置不同的信息名字獲取不同的配置文件
#application-dev.properties:用於開發環境
#application-test.properties:用於測試環境
#application-prod.properties:用於生產環境
spring.profiles.active=dev

#spring boot 默認會加載 classpath:logback-spring.xml 或者 classpath:logback-spring.groovy。
#如需要自定義文件名稱,在 application.properties 中配置 logging.config 選項即可
logging.config=classpath:logback-spring.xml

######數據庫鏈接配置########
spring.datasource.url=jdbc\:mysql\://127.0.0.1\:3306/aa
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000

mybatis.mapperLocations=classpath:mybatis/mapper/*.xml
mybatis.config-location=classpath:mybatis/mybatis-config.xml

四、代碼

實體類BookBean.java

public class BookBean {
    private String name;
    private String author;
    private String price;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "BookBean [name=" + name + ", author=" + author + ", price="
                + price + "]";
    }
    public BookBean(String name, String author, String price) {
        super();
        this.name = name;
        this.author = author;
        this.price = price;
    }
    public BookBean() {
        // TODO Auto-generated constructor stub
    }

}

BookBeanMapper.java

package com.example.demo.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.example.demo.bean.BookBean;

@Mapper
public interface BookBeanMapper {

    /**
     * 集合
     * @return
     */
    public List<BookBean> findBookBeanInfo();

    /**
     * 添加
     * @param bookBean
     * @return
     */
    public int addBookBeanInfo(BookBean bookBean);

    /**
     * 刪除
     * @param id
     * @return
     */
    public int delBookBeanInfo(String id);
}

BookBeanService.java

package com.example.demo.service;

import java.util.List;


import com.example.demo.bean.BookBean;


public interface BookBeanService {
    /**
     * 集合
     * @return
     */
    public List<BookBean> findBookBeanInfo();

    /**
     * 添加
     * @param bookBean
     * @return
     */
    public int addBookBeanInfo(BookBean bookBean);

    /**
     * 刪除
     * @param id
     * @return
     */
    public int delBookBeanInfo(String id);
}

BookBeanServiceImpl.java

package com.example.demo.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.bean.BookBean;
import com.example.demo.mapper.BookBeanMapper;
import com.example.demo.service.BookBeanService;

@Service
public class BookBeanServiceImpl implements BookBeanService{

    @Autowired
    private BookBeanMapper bookBeanMapper;

    @Override
    public List<BookBean> findBookBeanInfo() {

        return bookBeanMapper.findBookBeanInfo();
    }

    @Override
    public int addBookBeanInfo(BookBean bookBean) {

        return bookBeanMapper.addBookBeanInfo(bookBean);
    }

    @Override
    public int delBookBeanInfo(String id) {

        return bookBeanMapper.delBookBeanInfo(id);
    }

}

TestController.java

package com.example.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.bean.BookBean;
import com.example.demo.service.BookBeanService;
import com.example.demo.util.JsonResult;

@RestController
@RequestMapping(value="/demo")
public class TestController {

    @Autowired
    private BookBean bookBean;

    @Autowired
    private BookBeanService bookBeanService;

    @RequestMapping(value="/helloworld",produces="text/plan;charset=UTF-8")
    public String helloworld() {
        System.out.println(bookBean.toString());
        return "helloworld-"+bookBean.getName()+"----"+bookBean.getAuthor()+"----"+bookBean.getPrice();
    }

    @GetMapping("/helloworld2")
    public String helloworld2() {
        return "helloworld2";
    }


    /**
     * 根據id刪除用戶
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") String id){
        JsonResult r = new JsonResult();
        try {
            int ret = bookBeanService.delBookBeanInfo(id);
            if (ret < 0) {
                r.setResult(ret);
                r.setStatus("fail");
            } else {
                r.setResult(ret);
                r.setStatus("ok");
            }
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");

            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }



    /**
     * 查詢
     * @return
     */
    @RequestMapping(value="/find")
    public ResponseEntity<JsonResult> add(){
        JsonResult r = new JsonResult();
        try {
            System.out.println(1);
            List<BookBean> findBookBeanInfo = bookBeanService.findBookBeanInfo();
            r.setResult(findBookBeanInfo);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");

            e.printStackTrace();
        }

        return ResponseEntity.ok(r);

    }

}

JsonResult類是一個通用轉json的工具類 如下:

package com.example.demo.util;

/**
 * 通用json返回類
 * @author Administrator
 *
 */
public class JsonResult {
    private String status = null;

    private Object result = null;

    public JsonResult status(String status) {
        this.status = status;
        return this;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Object getResult() {
        return result;
    }

    public void setResult(Object result) {
        this.result = result;
    }


}

目錄結構:

這裏寫圖片描述

BookbeanMapper.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.BookBeanMapper" >
    <resultMap id="bookBeanMap" type="bookBean" >
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="author" property="author" jdbcType="VARCHAR" />
        <result column="price" property="price" jdbcType="VARCHAR"/>
    </resultMap>

    <sql id="bookbean" >
        name,author,price
    </sql>

    <select id="findBookBeanInfo" resultMap="bookBeanMap">
        select <include refid="bookbean"/> from BOOKBEAN
    </select>

    <insert id="addBookBeanInfo" parameterType="bookBean">
        insert into BOOKBEAN(name,author,price) values(#{name},#{author},#{price})
    </insert>

    <delete id="delBookBeanInfo" parameterType="string">
        delete from BOOKBEAN where price = #{price} 
    </delete>

</mapper>

然後啓動DemoApplication.java 打開瀏覽器 輸入http://localhost:8081/demo/find 就出現下圖

這裏寫圖片描述

完成到這裏說明springboot整合mybatis就成功了,有什麼不對的地方歡迎朋友們提出建議!

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