美文网首页
整合DRUID数据源+MyBatis

整合DRUID数据源+MyBatis

作者: 雨落川川 | 来源:发表于2020-07-18 11:22 被阅读0次

整合DRUID数据源

实际的开发中,我们很少用上面那种方式的数据源。
引入DruidDataSource:

    <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>

配置:

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,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

基本配置的这些属性是和DataSourceProperties对应的,但这里配置了还不能够用到,还需要一个Configuration,目的是不使用反射的自动创建,自己创建并绑定属性。

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid() {
        return new DruidDataSource();
    }
   //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //初始化参数
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "root");
        initParams.put("loginPassword", "root");
        initParams.put("allow", "");//允许所有
        initParams.put("deny", "36.1.52.144");//拒绝
        bean.setInitParameters(initParams);
        return bean;
    }

    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

整合MyBatis

引入:

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

创建数据库

创建Java Bean

使用MyBatis进行数据操作

使用注解版的使用:

创建mapper

/**
 * @Mapper 指定这是一个操作数据库的mapper
 */
@Mapper
public interface DepartmentMapper {
    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);

创建Controller

@RestController
public class DeptController {
    @Autowired
    DepartmentMapper departmentMapper;

    @GetMapping("/dept/{id}")
    public Department getDept(@PathVariable("id") Integer id) {
        return departmentMapper.getDeptById(id);
    }

    @GetMapping("/dept")
    public Department insert(Department department) {
        departmentMapper.insertDept(department);
        return department;
    }
}

目前,我们的数据库中表的字段名称和javaBean中属性名是一致的,如果改动了,则不能够匹配,者就需要一个配置文件或者配置类来解决这个问题。

创建MyBatisConfig类,使用自定义MyBatis的配置规则

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

可以使用 @MapperScan批量扫描。
配置文件的方式
EmployeeMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.springboot.mapper.EmployeeMapper">
    <select id="getEmpById" resultType="com.atguigu.springboot.bean.Employee">
        SELECT * FROM employee WHERE id=#{id}
    </select>

    <insert id="insertEmp">
        INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

mybatis.config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
       <!--    与上文中一样,解决数据库中是aa_bc形式,javaBean中是aaBc形式查询字段匹配问题-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

当然还是需要mapper的

@Mapper
public interface EmployeeMapper {

    public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);
}

重要的一点,需要在yml文件中配置

mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml       指定映射文件配置位置
  config-location: classpath:mybatis/mybatis-config.xml  指定全局文件配置

运行测试的过程中,又出现了之前的异常

java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time

这次换用另一种方式解决,不使用命令 set global time_zone='+8:00' ;来解决,而是在数据库驱动url后面添加serverTimezone=UTC,也能解决这个问题。

  url: jdbc:mysql://36.1.52.145:3306/jdbc?serverTimezone=UTC

相关文章

网友评论

      本文标题:整合DRUID数据源+MyBatis

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