2019-11-10 springboot-mybatis 和数据源的整合

配置Druid数据库连接池

先进行 pom 的导包 (我的版本在父pom控制了,这里只贴出了引用)

 
            mysql
            mysql-connector-java
        
        
            com.alibaba
            druid
        

druid 的 yml 配置文件

server:
  port: 8088
  thymeleaf:
    cache: false
    model: HTML5
    prefix: classpath:/templates/**
    suffix: .html
    servlet:
      content-type: text/html
spring:
  messages:
    basename: i18n/Messages,i18n/Pages
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource    #配置当前要使用的数据源的操作类型
    driver-class-name: com.mysql.jdbc.Driver     #配置mysql的驱动程序类
    url: jdbc:mysql://localhost:3306/mldn?useUnicode=true&characterEncoding=UTF-8         #数据库连接地址
    username: root                             #数据库用户名
    password: root                             #数据库连接密码
    dbcp2:                                          #配置数据库连接池的配置
      min-idle: 5                                   #数据库连接池最小维持连接数
      initial-size: 5                               #初始化提供的连接数
      max-total: 20                                  #最大连接数
      max-wait-millis: 20                           #等待连接获取的最大超时时间

对连接进行验证测试

@SpringBootTest(classes = bootBaseController.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class testDataSource{
    @Autowired
    private DataSource dataSource;
    @Test
    public void testConnection()throws SQLException {
        System.out.println("++++++++++++++++++++++"+this.dataSource.getConnection());
    }
}

springboot整合mybatis开发框架

mybatis得yml配置

mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml      # mybatis配置文件所在路径
  type-aliases-package: boot.vo                           # 定义所有操作类的别名所在包
  mapper-locations:                                       # 所有的mapper映射文件
    - classpath:mybatis/mapper/**/*.xml

mybatis得 entity 实体类(省略get/set方法)

 */
@SuppressWarnings("serial")
public class Dept implements Serializable {
    private Long deptno;
    private String dname;

mybatis得 dao 和 xml

//@Repository
@Mapper                     //我平常使用的是Repository ,但是在这里使用测试类必须用@Mapper否则注入不了测试类
public interface IDeptDao {
    public List findAll();
}


    

mybatis得service 和 impl

public interface IDeptService {
    public List findAll();
}


@Service
public class IDeptServiceImpl implements IDeptService {

   @Autowired
   private IDeptDao deptDao;

    @Override
    public List findAll() {
       return this.deptDao.findAll();
    }
}

测试类

@SpringBootTest(classes = bootBaseController.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class testDeptService {
    @Autowired
    private IDeptDao service;
    @Test
    public void testDeptService() {
   System.out.println("+++++++++++++++++++++++++++"+service.findAll());
    }
}}

测试结果

++++++++++++++++++++++++++++++++++++++[boot.vo.Dept@315f09ef, boot.vo.Dept@3a66e67e, boot.vo.Dept@75d4a80f, boot.vo.Dept@4596f8f3, boot.vo.Dept@ccf91df]

事务控制

报错信息(service 设置为只读时进行添加报错)

nested exception is java.sql.SQLException: 
Connection is read-only. Queries leading to data modification are not allowed

dao 和 xml

      public boolean doCreate(Dept dept);

    
        insert into dept(dname) values (#{dname})
    

service 和 impl

注解表示支持事务
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean add(Dept dept);

    @Override
    public boolean add(Dept dept) {
        return this.deptDao.doCreate(dept);
    }

引入logback pom包

   
            ch.qos.logback
            logback-core
        

logback.xml




    
    
    
        
            %d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} %X{ServiceId} - %m%n
        
    
    
        ${LOG_HOME}/${APP}_detail.log
        
            %d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} %X{ServiceId} - %m%n
        
        
            ${LOG_HOME}/${APP}_detail.log.%d{yyyyMMdd}
        
    
    
        ${LOG_HOME}/${APP}_access.log
        
            %d{yy-MM-dd.HH:mm:ss.SSS};%X{ServiceId};%m%n
        
        
            ${LOG_HOME}/${APP}_access.log.%d{yyyyMMdd}
        
    


    
        
    
    

        下面是自己dao接口得全类名包名
    

    
        
        
    

测试类

  @Test
    public void testAdd() throws  Exception{
        Dept dept =new Dept();
        dept.setDname("张三");
        System.out.println("------------------"+service.add(dept));
    }

结果

19-11-13.01:16:47.811 [main            ] TRACE findAll                 - <==    Columns: deptno, dname
19-11-13.01:16:47.811 [main            ] TRACE findAll                 - <==        Row: 1, 开发部
19-11-13.01:16:47.814 [main            ] TRACE findAll                 - <==        Row: 2, 财务部
19-11-13.01:16:47.815 [main            ] TRACE findAll                 - <==        Row: 3, 市场部
19-11-13.01:16:47.815 [main            ] TRACE findAll                 - <==        Row: 4, 后勤部
19-11-13.01:16:47.815 [main            ] TRACE findAll                 - <==        Row: 5, 公关部

druid 监控配置(application 中加一个 spring.datasource.filters=stat,wall,log4j)

@Configuration
public class DruidConfig {
    @Bean
    public ServletRegistrationBean druidStatViewServlet() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new StatViewServlet(),  "/druid/*");
        registrationBean.addInitParameter("allow", "127.0.0.1");// IP白名单 (没有配置或者为空,则允许所有访问)
        registrationBean.addInitParameter("deny", "");// IP黑名单 (存在共同时,deny优先于allow)
        registrationBean.addInitParameter("loginUsername", "root");
        registrationBean.addInitParameter("loginPassword", "1234");
        registrationBean.addInitParameter("resetEnable", "false");
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean() ;
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*"); // 所有请求进行监控处理
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");
        return filterRegistrationBean ;
    }
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
}

你可能感兴趣的:(2019-11-10 springboot-mybatis 和数据源的整合)