Spring boot 整合 Mybatis + Thymeleaf开发web(…

2018-06-18 02:02:55来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

  最近工作上时间有点多,然后自己就学习了一下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就成功了,有什么不对的地方欢迎朋友们提出建议!

版权声明:本文为博主原创文章,未经博主允许不得转载。 

 http://www.cnblogs.com/tangyin/p/8862687.html

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:git总结

下一篇:线程看一看