Spring boot 与mybatis简单整合

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

接下来我们就来整合整合

          Spring boot

           mybatis

          druid

简单整合

接上 简单用Spring boot druid 搭建SQL监控

上文:http://www.javashuo.com/article/p-pvplcmsv-rc.html   (这里针对这一块只贴代码,不详细讲解)

demo结构

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 http://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.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.10</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.0.1</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

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

</project>

把需要的jar引入之后就开始搭建了

 

package com.example.demo.config;
/**
 * @Author Justice
 * @Date 2019/4/8 16:17
 * @Version 1.0
 */
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;


@Configuration
public class DruidConfiguration {




    /**
	 * 注册一个StatViewServlet
	 * @return
	 */
    @Bean
    public ServletRegistrationBean druidStatView(){

       //org.springframework.boot.web.servlet.FilterRegistrationBean提供类的进行注册.
       ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");

       //添加初始化参数:initParams

       //白名单:
       servletRegistrationBean.addInitParameter("allow","127.0.0.1");

       //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
       servletRegistrationBean.addInitParameter("deny","192.168.1.110");

       //登录查看信息的账号密码.
       servletRegistrationBean.addInitParameter("loginUsername","admin");
       servletRegistrationBean.addInitParameter("loginPassword","root");

       //是否能够重置数据.
       servletRegistrationBean.addInitParameter("resetEnable","false");
       return servletRegistrationBean;
    }

    /**
     * 注册一个:filterRegistrationBean
     * @return
     */
    @Bean
    public FilterRegistrationBean druidStatFilter(){
       FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());

       //添加过滤规则.
       filterRegistrationBean.addUrlPatterns("/*");

       //添加不需要忽略的格式信息.
       filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

       return filterRegistrationBean;
    }
}

这里是druid连接池Sql监控部分

package com.example.demo.entity;

import lombok.Data;

/**
 * @Author Justice
 * @Date 2019/4/8 17:22
 * @Version 1.0
 */
@Data
public class User {
    private Integer id;
    private String userName;
    private String password;
    private Integer age;
}

这里为实体类,由于有用lombok插件,get,set方法就不用我们自己来维护了

 

package com.example.demo.dao;
/**
 * @Author Justice
 * @Date 2019/4/8 17:22
 * @Version 1.0
 */

import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserDao {

    final String SQL_CUM ="id,user_name as userName,password,age";

    @Delete(value = "delete from user_t  where id = #{id,jdbcType=INTEGER}")
    int deleteByPrimaryKey(Integer id);

    @Insert("insert into user_t (id, user_name, password,age) values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR},#{password,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
    int insert(User record);

    @Insert("<script>insert into user_t\n" +
            "        <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\" >\n" +
            "            <if test=\"id != null\" >\n" +
            "                id,\n" +
            "            </if>\n" +
            "            <if test=\"userName != null\" >\n" +
            "                user_name,\n" +
            "            </if>\n" +
            "            <if test=\"password != null\" >\n" +
            "                password,\n" +
            "            </if>\n" +
            "            <if test=\"age != null\" >\n" +
            "                age,\n" +
            "            </if>\n" +
            "        </trim>\n" +
            "        <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\" >\n" +
            "            <if test=\"id != null\" >\n" +
            "                #{id,jdbcType=INTEGER},\n" +
            "            </if>\n" +
            "            <if test=\"userName != null\" >\n" +
            "                #{userName,jdbcType=VARCHAR},\n" +
            "            </if>\n" +
            "            <if test=\"password != null\" >\n" +
            "                #{password,jdbcType=VARCHAR},\n" +
            "            </if>\n" +
            "            <if test=\"age != null\" >\n" +
            "                #{age,jdbcType=INTEGER},\n" +
            "            </if>\n" +
            "        </trim></script>")
    int insertSelective(User record);

    @Select(value="select "+SQL_CUM+" from user_t where 1=1 and id = #{id,jdbcType=INTEGER}")
    User selectByPrimaryKey(Integer id);

}

随意发挥一个查询,一个固定添加,一个动态添加

package com.example.demo.service;

/**
 * @Author Justice
 * @Date 2019/4/8 17:22
 * @Version 1.0
 */
import com.example.demo.entity.User;

public interface UserService {

    /***
     * @author Justice
     * Description  根据userid查询返回用户详细信息
     * @param userId
     * @return User
     */
    User getUserById(int userId);

    /****
     * @author Justice
     * Description 传入用户信息保存,并且返回是否成功判断
     * @param record
     * @return boolean
     */
    boolean addUser(User record);

}
package com.example.demo.service.impl;

/**
 * @Author Justice
 * @Date 2019/4/8 17:22
 * @Version 1.0
 */
import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Override
    public User getUserById(int userId) {
        return userDao.selectByPrimaryKey(userId);
    }

    @Override
    public boolean addUser(User record){
        boolean result = false;
        try {
            userDao.insertSelective(record);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

}
package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
 * @Author Justice
 * @Date 2019/4/8 17:22
 * @Version 1.0
 */

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("/showUser")
    @ResponseBody
    public User showUser(HttpServletRequest request){
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = this.userService.getUserById(userId);
        return user;
    }

    @RequestMapping("/addUser")
    @ResponseBody
    public boolean addUser(User us){
        return this.userService.addUser(us);
    }

}
package com.example.demo;
/**
 * @Author Justice
 * @Date 2019/4/8 17:22
 * @Version 1.0
 */
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;


@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class DemoApplication extends SpringBootServletInitializer {

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

}
@MapperScan("com.example.demo.dao")   这个要扫描到你Dao层的包路径
server:
  port: 8012
  session:
    timeout: 10
  tomcat:
    uri-encoding: UTF-8
spring:
  datasource:
    # 配置数据源类型
    type:
      com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
    # 初始化,最小,最大连接数
    initialSize: 3
    minidle: 3
    maxActive: 18
    # 获取数据库连接等待的超时时间
    maxWait: 60000
    # 配置多久进行一次检测,检测需要关闭的空闲连接 单位毫秒
    timeBetweenEvictionRunsMillis: 60000
    validationQuery: SELECT 1 FROM dual
    # 配置监控统计拦截的filters,去掉后,监控界面的sql无法统计
    filters: stat,wall,log4j

就可以启动项目了

http://127.0.0.1:8012/user/showUser?id=1   查询

http://127.0.0.1:8012/user/addUser?id=6&userName=%E5%BC%A0%E4%B8%89&password=123456&age=1009    添加效果如下

数据库数据及结构如下

链接:https://pan.baidu.com/s/1gWcbIUBSRsguLnAF88XRYA  提取码:ge3d