美文网首页springboot
Springboot2.x整合 druid, Mybatis-p

Springboot2.x整合 druid, Mybatis-p

作者: 骑蚂蚁上高速_jun | 来源:发表于2020-11-09 23:13 被阅读0次
    1. 添加pom 坐标
    <dependency>
    <!-- 在springboot项目中 mybatis依赖 springboot的jdbc进行事物管理 -->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.3.2</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.22</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.13</version>
            </dependency>
    

    2.1 . 数据源application.yml配置

    spring:
      datasource:
        umail:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/zmkm?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Hongkong&autoReconnect=true&failOverReadOnly=false&rewriteBatchedStatements=ture
          username: root
          password: 123456
          type: com.alibaba.druid.pool.DruidDataSource # 配置阿里巴巴的 druid 数据源
          initialSize: 5 # 初始化5个链接
          minIdle: 5
          maxWait: 6000
          maxActive: 30
          name: umail
          timeBetweenEvictionRunsMillis: 6000 # 时间应少于 数据库配置文件  wait_timeout选项
          minEvictableIdleTimeMillis: 30000
          validationQuery: SELECT 1 FROM DUAL
          testWhileIdle: true # 空闲时检测
          testOnBorrow: true # 获取连接时检测
          testOnReturn: false #  连接放回连接池时检测
          poolPreparedStatements: true
    
          #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
          filters: stat,wall,log4j
          maxPoolPreparedStatementPerConnectionSize: 20
          useGlobalDataSourceStat: true
          connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    

    2.2 注册配置 configuration

    package com.configuration;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import com.alibaba.druid.support.http.WebStatFilter;
    import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Qualifier;
    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 org.springframework.context.annotation.Primary;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    import org.springframework.transaction.PlatformTransactionManager;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    import javax.servlet.Filter;
    import javax.sql.DataSource;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;
    
    @Configuration
    // 配置 mapper包所在目录
    @MapperScan(basePackages = {"com.repository.mapper"},sqlSessionTemplateRef = "umailTemplate")
    @EnableTransactionManagement
    public class MybatisPlusConfiguration
    {
        // 配置使用 umail 数据源
        @Bean(name="umail")
        @ConfigurationProperties(prefix = "spring.datasource.umail")
        @Primary
        public DataSource dataSource(){
            return new DruidDataSource();
        }
    
        /**
         * 创建 SqlSessionFactory
         */
        @Bean(name = "umailFactory")
        @Primary
        public SqlSessionFactory sqlSessionFactory(
            @Qualifier("umail") DataSource dataSource
        ) throws Exception {
            //  SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 这是mybatis带的 SqlSession
            // 此处必须使用 mybatisplus 带的 sqlSession
            // 1. 设置数据源
            MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
            bean.setDataSource(dataSource); // 绑定数据源
            // 2. 加载分页插件
            PaginationInterceptor interceptor = new PaginationInterceptor();
            Properties properties = new Properties();
            properties.setProperty("helperDialect", "mysql");//分页数据库为mysql
            properties.setProperty("reasonable", "false");//是否分页合理化
            interceptor.setProperties(properties);
            bean.setPlugins(interceptor);
            // 3.可以加载 xml文件的目录,由于本人喜欢纯mapper注解操作,故不需要复杂的xml文件
            //   bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/db1/*.xml"));
            return bean.getObject();
        }
       
        /**
         * 配置事务管理
         */
        @Bean(name = "umailTransaction")
        @Primary
        public PlatformTransactionManager transactionManager(
            @Qualifier("umail") DataSource dataSource
        ) {
            return new DataSourceTransactionManager(dataSource);
        }
    
        /**
         * 配置对外操作的 bean
         * @param sqlSessionFactory
         * @return
         * @throws Exception
         */
        @Bean(name = "umailTemplate")
        @Primary
        public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("umailFactory") SqlSessionFactory sqlSessionFactory
        ) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    
        @Bean
        public ServletRegistrationBean staViewServlet(){
            ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
            Map<String,String> initParams = new HashMap<>();
            //设置servlet初始化参数
            initParams.put("loginUsername","admin");// druid登陆名
            initParams.put("loginPassword","123456");// druid密码
            initParams.put("allow","");//默认就是允许所有访问
            initParams.put("deny","192.168.15.21");//拒绝相对应的id访问
            bean.setInitParameters(initParams);
            //加载到容器中
            return bean;
        }
    
        //2.配置一个web监控的filter
        @Bean
        public FilterRegistrationBean webStatFilter(){
            FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
            bean.setFilter(new WebStatFilter());
            Map<String,String> initParams = new HashMap<>();
            //设置filter初始化参数、
            initParams.put("exclusions","*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");//排除静态资源和请求
            bean.setInitParameters(initParams);
            //拦截所有请求
            bean.setUrlPatterns(Arrays.asList("/*"));
            //加载到容器中
            return bean;
        }
    
    }
    
    
    1. 创建 数据库实体Entity 和操作的 Mapper
    // 创建实体
    package com.repository.entity;
    
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.annotation.TableField;
    import com.baomidou.mybatisplus.annotation.TableId;
    import com.baomidou.mybatisplus.annotation.TableName;
    import lombok.Builder;
    import lombok.Data;
    
    import java.sql.Date;
    
    @Data
    @TableName("sys_department")
    public class SysDepartment {
        // 注明该键是主键,并设置递增
        @TableId(value = "id",type = IdType.AUTO)
        private int departmentId;
    
        private String name;
    
        private String remark;
    
        private Date createtime;
    
        @TableField(exist = false)
        private SysUser sysUser;
    
        @TableField(exist = false)
        private String username;
    }
    // 创建操作数据库的Mapper.
    // 注意,该实体操作的 Mapper一定是在配置类中的 @MapperScan 中进行扫描
    package com.repository.mapper;
    
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.repository.entity.SysDepartment;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Options;
    import org.apache.ibatis.annotations.Select;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    @Repository
    // @Qualifier("umailTemplate") 可以不配置,因为我配置中该Bean 为主Bean
    public interface SysDepartmentMapper extends BaseMapper<SysDepartment> {
    
    
       /* @Insert("insert into sys_department(name,remark) values(#{name},#{remark})")
        @Options(useGeneratedKeys = true,keyProperty = "departmentId",keyColumn = "id") // 将自增主键返给 实体类的 id 属性
        int insert(SysDepartment sysDepartment);
    
        @Select("select * from sys_department")
        List<SysDepartment> selectDepartment();
        @Select("select d.id departmentId,d.name name,d.remark,d.createtime,u.name username from sys_department d left join sys_user u on d.id=u.department_id ")
        List<SysDepartment> selectAll();*/
    
    }
    
    
    1. 创建Services 操作Mapper
    @Autowired
        SysDepartmentMapper sysDepartmentMapper;
        
        // 由于 umailTransaction事务Bean在配置中声明了 Primary,故可以不需要加上
        @Transactional(value = "umailTransaction") //
        public int storeDepartment(){
            SysDepartment sysDepartment = new SysDepartment();
            sysDepartment.setName("技术一部");
            sysDepartment.setRemark("这是备注"+new Date());
            int s=sysDepartmentMapper.insert(sysDepartment);
    
            
            // 抛出的异常是 RuntimeException及子类异常的时候事务会回滚
            if(s > 0) throw new RuntimeException("");
            // 重点, 如果 抛出的异常被手工捕获,那么事物将不会回滚。
            // 但是 仍然可以在 捕获异常的 catch中 设置手动回滚
           //  设置手动回滚 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    
            return sysDepartment.getDepartmentId();
        }
    

    相关文章

      网友评论

        本文标题:Springboot2.x整合 druid, Mybatis-p

        本文链接:https://www.haomeiwen.com/subject/srzrbktx.html