springboot集成mybatisplus和log4j2

版权声明:如果喜欢,欢迎转载,转载请标明出处。 https://blog.csdn.net/qq_34677946/article/details/82983122

目录

 

一、引入项目需要的依赖

二、配置druid和mybatisplus

三、配置jdbc数据源

四、如何使用mybatisplus

五、测试CustomerDao对Customer实体进行持久化操作

六、mybatisplus的一些配置

七、配置log4j2并打印执行的sql语句


一、引入项目需要的依赖


		<!-- springboot -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- log4j2集成 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>


		<!-- lombok集成 -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.18</version>
			<scope>provided</scope>
		</dependency>

		<!-- mybatis plus -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.0.1</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.46</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>

	    <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

二、配置druid和mybatisplus

用DruidProperties接收yml中的数据源属性,mybatisplus是在mybatis上面进行功能扩展,关于mybatis的使用仍然不变

下面是druid和mybatisplus的配置文件 application.yml

  #druid
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://118.24.50.160:3306/demo?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
    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
    maxPoolPreparedStatementPerConnectionSize: 20
    filters: stat, wall, log4j
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    loginUsername: druid
    loginPassword: druid
    allow:
    deny:

#mybatisplus
mybatis-plus:
  mapper-locations: classpath*:mybatis/*.xml
  type-aliases-package: redis.demo.entity
  global-config:
    refresh: true
    db-config:
      id-type: input
      field-strategy: not_empty
  configuration:
    lazy-loading-enabled: true
    aggressive-lazy-loading: true
    call-setters-on-nulls: true
    map-underscore-to-camel-case: true
    multiple-result-sets-enabled: true

三、配置jdbc数据源

DruidProps接收相关属性


import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidProps {

    private String type;

    private String driverClassName;

    private String url;

    private String username;

    private String password;

    private int initialSize;

    private int minIdle;

    private int maxActive;

    private int maxWait;

    private int timeBetweenEvictionRunsMillis;

    private int minEvictableIdleTimeMillis;

    private String validationQuery;

    private boolean testWhileIdle;

    private boolean testOnBorrow;

    private boolean testOnReturn;

    private boolean poolPreparedStatements;

    private int maxPoolPreparedStatementPerConnectionSize;

    private String filters;

    private String connectionProperties;

    private String allow;

    private String deny;

    private String loginUsername;

    private String loginPassword;
}

jdbc数据源配置DruidConfig


import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.sql.SQLException;

@Configuration
public class DruidConfig {
    private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class);

    @Autowired
    private DruidProps properties;

    public DataSource dataSource() throws SQLException {
        String url = properties.getUrl();
        logger.info("===> DataSource Connection Url {}", url.substring(13, url.indexOf("?")));
        DruidDataSource datasource = new DruidDataSource();
        datasource.setDriverClassName(properties.getDriverClassName());
        datasource.setUrl(url);
        datasource.setUsername(properties.getUsername());
        datasource.setPassword(properties.getPassword());
        datasource.setFilters(properties.getFilters());
        datasource.setConnectionProperties(properties.getConnectionProperties());
        datasource.setInitialSize(properties.getInitialSize());
        datasource.setMinIdle(properties.getMinIdle());
        datasource.setMaxActive(properties.getMaxActive());
        datasource.setMaxWait(properties.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
        datasource.setValidationQuery(properties.getValidationQuery());
        datasource.setTestWhileIdle(properties.isTestWhileIdle());
        datasource.setTestOnBorrow(properties.isTestOnBorrow());
        datasource.setTestOnReturn(properties.isTestOnReturn());
        datasource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
        datasource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());
        return datasource;
    }

    @Bean
    public ServletRegistrationBean druidServlet(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        /**
         *  白名单:
         */
        servletRegistrationBean.addInitParameter("allow", "");
        /**
         *  黑名单:
         *   存在共同时,deny优先于allow
         */
        servletRegistrationBean.addInitParameter("deny", "");
        servletRegistrationBean.addInitParameter("loginUsername", properties.getLoginUsername());
        servletRegistrationBean.addInitParameter("loginPassword", properties.getLoginPassword());
        /**
         * 是否能够重置数据.  强制为不允许
         */
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean druidFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/druid/*");
        return filterRegistrationBean;
    }
}

四、如何使用mybatisplus

Dao层只需要集成mybatisplus提供的BaseMapper<T>即可。同时也可以自定义方法,并在mybatis/*Mapper.xml文件中写具体的sql实现。下面是BaseMapper<T>为我们提供的常用方法模板

package com.baomidou.mybatisplus.core.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;

public interface BaseMapper<T> {
    int insert(T var1);

    int deleteById(Serializable var1);

    int deleteByMap(@Param("cm") Map<String, Object> var1);

    int delete(@Param("ew") Wrapper<T> var1);

    int deleteBatchIds(@Param("coll") Collection<? extends Serializable> var1);

    int updateById(@Param("et") T var1);

    int update(@Param("et") T var1, @Param("ew") Wrapper<T> var2);

    T selectById(Serializable var1);

    List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> var1);

    List<T> selectByMap(@Param("cm") Map<String, Object> var1);

    T selectOne(@Param("ew") Wrapper<T> var1);

    Integer selectCount(@Param("ew") Wrapper<T> var1);

    List<T> selectList(@Param("ew") Wrapper<T> var1);

    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> var1);

    List<Object> selectObjs(@Param("ew") Wrapper<T> var1);

    IPage<T> selectPage(IPage<T> var1, @Param("ew") Wrapper<T> var2);

    IPage<Map<String, Object>> selectMapsPage(IPage<T> var1, @Param("ew") Wrapper<T> var2);
}

比如CustomerDao层使用、需要实现BaseMapper<T>

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import redis.demo.entity.Customer;
import java.util.List;

public interface CustomerDao extends BaseMapper<Customer> {

    int insertCustomerList(List<Customer> customers);
}

五、测试CustomerDao对Customer实体进行持久化操作

Customer实体类

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <br/>
 *
 * @author: PJJ
 * @date: 2018/9/14
 */
@Getter
@Setter
@TableName("t_customer")
public class Customer implements Serializable {
    private static final long serialVersionUID = -2939608830492687435L;

    private String name;
    private Integer id;
    private String mail;
    private Integer age;
    private String lastName;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Customer customer = (Customer) o;
        return Objects.equals(name, customer.name) &&
                Objects.equals(id, customer.id) &&
                Objects.equals(mail, customer.mail) &&
                Objects.equals(age, customer.age) &&
                Objects.equals(lastName, customer.lastName);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, id, mail, age, lastName);
    }

    @Override
    public String toString() {
        return "Customer{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", mail='" + mail + '\'' +
                ", age=" + age +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}

建表sql语句

CREATE TABLE `t_customer` (
  `id` int(11) NOT NULL,
  `mail` varchar(30) DEFAULT NULL,
  `age` tinyint(4) DEFAULT NULL,
  `name` varchar(30) DEFAULT NULL,
  `last_name` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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;
import redis.demo.entity.Customer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Autowired
    private CustomerDao customerDao;

    @Test
    public void testCommonInsert() {
        Customer customer = new Customer();
        customer.setId(9);
        customer.setAge(28);
        customer.setMail("");
//        customer.setName("zs");
        customer.setLastName("张三");
//        customerDao.insert(customer);

        Customer customer1 = new Customer();
        customer1.setId(10);
        customer1.setAge(28);
        customer1.setMail("ff");
//        customer.setName("zs");
        customer1.setLastName("张三");
        List<Customer> customers = new ArrayList<>();
        customers.add(customer);
        customers.add(customer1);
        customerDao.insertCustomerList(customers);
    }

    @Test
    public void testCommonUpdate() {
        Customer customer = new Customer();
        customer.setAge(7);
        customer.setMail("[email protected]");
        customer.setName("宙斯");
        customer.setLastName("si");
//        非空判断更新数据last_name没有 UPDATE t_customer SET name=?, mail=?, age=? WHERE id=?
//        customerDao.updateById(customer);

        UpdateWrapper<Customer> wrapper = new UpdateWrapper<>();
//        where id = 7
        wrapper.eq("id", "7");
        customerDao.update(customer, wrapper);
    }

    @Test
    public void testSelectWrapper() {
        Map<String, Object> map = new HashMap<>();
        // where id = 1 and age = 28
        map.put("id", "1");
        map.put("age", "28");
        List<Customer> customers = customerDao.selectByMap(map);
        System.out.println(customers);

        IPage iPage = new Page(1,2);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(true, "age", 28).or(true).like("mail", "22");
        IPage page = customerDao.selectPage(iPage, queryWrapper);
        System.out.println(page.getRecords());
    }
}

六、mybatisplus的一些配置

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

/**
 * <br/>
 *
 * @author: PJJ
 * @date: 2018/9/14
 */
@ConditionalOnMissingBean(MybatisPlusConfig.class)
public class MybatisPlusConfig {

    //	baomidou分页查询
    @Bean
    public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }

    /**
     * SQL执行效率插件、开发测试环境开启
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor interceptor = new PerformanceInterceptor();
        //超过100的sql不让他执行
        interceptor.setMaxTime(100);
        //开启sql格式化
        interceptor.setFormat(true);
        return interceptor;
    }
}

七、配置log4j2并打印执行的sql语句

只需要在resource目录下面加入log4j2.xml为名称的log4j2配置文件.文件类容如下

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="OFF">
    <properties>
        <!--设置日志在硬盘上输出的目录-->
        <property name="LOG_HOME">c:/log</property>
        <property name="SQL_PACKAGE">redis.demo.dao</property>
    </properties>

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
            <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5level %class{36} %M() @%L - %msg%n"/>
        </Console>

        <!-- 按天记录追加日志 -->
        <RollingFile name="RollingFile" fileName="${LOG_HOME}/error.log" filePattern="${LOG_HOME}/error-%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5level - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy modulate="true" interval="1"/>
            </Policies>
        </RollingFile>

    </Appenders>
    <Loggers>
        <!-- 只配置这里 开启mybatis sql打印 trace级别可以显示结果集 -->
        <logger name="${SQL_PACKAGE}" level="trace" additivity="false">
            <appender-ref ref="Console"/>
        </logger>

        <Root level="info">
            <appender-ref ref="RollingFile"/>
            <appender-ref ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

猜你喜欢

转载自blog.csdn.net/qq_34677946/article/details/82983122
今日推荐