srpingboot整合mybatis 注解版

前期准备

开发环境

  • 开发工具:IDEA
  • JDK:1.8

  • 技术:SpringBoot、Maven、Mybatis

创建项目

 srpingboot整合mybatis 注解版_第1张图片



srpingboot整合mybatis 注解版_第2张图片


Maven依赖

用的druid的数据源 添加上坐标

xml version="1.0" encoding="UTF-8"?>
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">
   4.0.0

   cn.vp
   springbootmybatis
   0.0.1-SNAPSHOT
   jar

   springbootmybatis
   Demo project for Spring Boot

   
      org.springframework.boot
      spring-boot-starter-parent
      2.0.1.RELEASE
       
   

   
      UTF-8
      UTF-8
      1.8
   

   

      
      
         com.alibaba
         druid
         1.1.9
      
      
         org.springframework.boot
         spring-boot-starter-jdbc
      
      
         org.springframework.boot
         spring-boot-starter-web
      
      
         org.mybatis.spring.boot
         mybatis-spring-boot-starter
         1.3.2
      

      
         mysql
         mysql-connector-java
         runtime
      
      
         org.springframework.boot
         spring-boot-starter-test
         test
      
   

   
      
         
            org.springframework.boot
            spring-boot-maven-plugin
         
      
   



SpringBoot配置文件

这里使用yml格式的配置文件,新增application.yml。

srpingboot整合mybatis 注解版_第3张图片


spring:
  datasource:
    druid:
#   数据源基本配置
        username: root
        password: 123
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test
        type: com.alibaba.druid.pool.DruidDataSource
      #   数据源其他配置
        initialSize: 5
        minIdle: 5
        maxActive: 20
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
      #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        filters: stat,wall,slf4j
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    

SpringBoot会自动加载application.yml相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中。

实体类

package cn.vp.entity;

public class Department {

   private Integer id;
   private String departmentName;

   public Department() {
   }
   
   public Department(int i, String string) {
      this.id = i;
      this.departmentName = string;
   }

   public Integer getId() {
      return id;
   }

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

   public String getDepartmentName() {
      return departmentName;
   }

   public void setDepartmentName(String departmentName) {
      this.departmentName = departmentName;
   }

   @Override
   public String toString() {
      return "Department [id=" + id + ", departmentName=" + departmentName + "]";
   }
   
}

dao类

package cn.vp.dao;

import cn.vp.entity.Department;
import org.apache.ibatis.annotations.*;

@Mapper
public interface DepartmentDao {

    @Insert("INSERT INTO `Department` (`departmentName`) VALUES (#{departmentName})")
    public int addDepartment(Department department);

    @Delete("DELETE FROM  department where id=#{id}")
    public int deleteById(Integer id);

    @Update("UPDATE `Department` SET `departmentName`=#{departmentName} WHERE (`id`=#{id})")
    public int updateDepartment(Department department);

    @Select("SELECT  * from department where id=#{id}")
    public Department queryById(@Param("id") Integer id);


}

数据源配置类

package cn.vp.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourcesConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSource getDataSources() {
        return new DruidDataSource();
    }

    /**
     * 配置druid后台管理的servlet
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "admin");
        initParams.put("allow", "");//默认就是允许所有访问
        initParams.put("deny", "192.168.15.21");//禁止访问的ip
        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 配置druid后台管理的filter
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean druidFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map, String> initParams = new HashMap<>();
        //设置不拦截的路径  *.cs *.js    /druid/*
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        //设置filter拦截 那些请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }


}

测试类

package cn.vp.dao;

import cn.vp.entity.Department;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class DepartmentDaoTest {

    @Autowired
    private  DepartmentDao departmentDao;

    @Test
    public void addDepartment() {
    }

    @Test
    public void deleteById() {
    }

    @Test
    public void updateDepartment() {
        Department department=new Department();
        department.setId(1);
        department.setDepartmentName("武汉办事处");
        int i = departmentDao.updateDepartment(department);
        System.out.println("受影响的行数:"+i);
    }

    @Test
    public void queryById() {
    }
}


你可能感兴趣的:(学习笔记)