Spring Boot(三)——Spring Boot数据访问

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/vae1314chuanchen/article/details/82946569

一、简介

对于数据访问层,无论是SQL还是NOSQL,Spring Boot默认采用整合Spring Data的方式进行统一处理,添加大量自动配置,屏蔽了很多设置。引入各种xxxTemplate,xxxRepository来简化我们对数据访问层的操作。对我们来说只需要进行简单的设置即可。下面来说一下在Spring Boot中如何使用MyBaits与JPA进行数据访问。
数据访问

二、配置自定义数据源

spring-boot-starter-jdbc 默认使用tomcat-jdbc数据源,如果想使用其他的数据源,比使用阿里巴巴的数据池管理。在使用druid数据源时,应该额外添加以下依赖:

        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

1)编写yml文件


spring:
  datasource:
    #   数据源基本配置
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/crud
    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

2)新建druid配置类

@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","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默认就是允许所有访问
        initParams.put("deny","192.168.110.110");

        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;
    }
}

三、Spring Boot中如何集成MyBatis

1)添加依赖

这里需要添加mybatis-spring-boot-starter依赖跟mysql依赖。

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

这里不引入spring-boot-starter-jdbc依赖,是由于mybatis-spring-boot-starter中已经包含了此依赖。

MyBatis-Spring-Boot-Starter依赖将会提供如下:

  • 自动检测现有的DataSource
  • 将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递
  • 将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例。
  • 自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中。

就是说,使用了该Starter之后,只需要定义一个DataSource即可(application.yml中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。

2)配置数据源(同上)

3)Mybatis集成

注解方式

Mybatis注解的方式比较简单,只要定义一个dao接口,然后sql语句通过注解写在接口方法上。最后给这个接口添加 @Mapper注解 或者在启动类上或者配置类上添加 @MapperScan(“要扫描的包名”) 注解即可。

@Component
 @Mapper
 public interface LearnMapper {
     @Insert("insert into learn_resource(author, title,url) values(#{author},#{title},#{url})")
     int add(LearnResouce learnResouce);

    @Update("update learn_resource set author=#{author},title=#{title},url=#{url} where id = #{id}")
     int update(LearnResouce learnResouce);

    @DeleteProvider(type = LearnSqlBuilder.class, method = "deleteByids")
     int deleteByIds(@Param("ids") String[] ids);

    @Select("select * from learn_resource where id = #{id}")
     @Results(id = "learnMap", value = {
             @Result(column = "id", property = "id", javaType = Long.class),
             @Result(property = "author", column = "author", javaType = String.class),
             @Result(property = "title", column = "title", javaType = String.class)
     })
     LearnResouce queryLearnResouceById(@Param("id") Long id);
 @SelectProvider(type = LearnSqlBuilder.class, method = "queryLearnResouceByParams")
     List<LearnResouce> queryLearnResouceList(Map<String, Object> params);

    class LearnSqlBuilder {
         public String queryLearnResouceByParams(final Map<String, Object> params) {
             StringBuffer sql =new StringBuffer();
             sql.append("select * from learn_resource where 1=1");
             if(!StringUtil.isNull((String)params.get("author"))){
                 sql.append(" and author like '%").append((String)params.get("author")).append("%'");
             }
             if(!StringUtil.isNull((String)params.get("title"))){
                 sql.append(" and title like '%").append((String)params.get("title")).append("%'");
             }
             System.out.println("查询sql=="+sql.toString());
             return sql.toString();
         }

        //删除的方法
         public String deleteByids(@Param("ids") final String[] ids){
             StringBuffer sql =new StringBuffer();
             sql.append("DELETE FROM learn_resource WHERE id in(");
             for (int i=0;i<ids.length;i++){
                 if(i==ids.length-1){
                     sql.append(ids[i]);
                 }else{
                     sql.append(ids[i]).append(",");
                 }
             }
             sql.append(")");
             return sql.toString();
         }
     }
 }
@MapperScan(basePackages = {"com.cxxx.guns.modular.*.dao"})
public class SingleDataSourceConfig {

需要注意的是,简单的语句只需要使用@Insert、@Update、@Delete、@Select这4个注解即可,但是有些复杂点需要动态SQL语句,就比如上面方法中根据查询条件是否有值来动态添加sql的,就需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider等注解。

这些可选的 SQL 注解允许你指定一个类名和一个方法在执行时来返回运行 允许创建动态 的 SQL。 基于执行的映射语句, MyBatis 会实例化这个类,然后执行由 provider 指定的方法. 该方法可以有选择地接受参数对象.(In MyBatis 3.4 or later, it’s allow multiple parameters) 属性: type,method。type 属性是类。method 属性是方法名。

注解方式如何配置mybaits全局配置文件,如开启驼峰命名

import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;

@Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){

            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

XML配置方式

xml配置方式保持映射文件的老传统,优化主要体现在不需要实现dao的是实现层,系统会自动根据方法名在映射文件中找对应的sql,具体操作如下:

1)新建mybaits的全局配置文件

<?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>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

2)修改application.yml 配置文件

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

3)编写Dao层的代码
新建LearnMapper接口,无需具体实现类。

@Mapper
 public interface LearnMapper {
     int add(LearnResouce learnResouce);
     int update(LearnResouce learnResouce);
     int deleteByIds(String[] ids);
     LearnResouce queryLearnResouceById(Long id);
     public List<LearnResouce> queryLearnResouceList(Map<String, Object> params);
 }

4)添加LearnMapper的映射文件
在mapper目录下新建LearnMapper.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.dudu.dao.LearnMapper">
   <resultMap id="baseResultMap" type="com.dudu.domain.LearnResouce">
     <id column="id" property="id" jdbcType="BIGINT"  />
     <result column="author" property="author" jdbcType="VARCHAR"/>
     <result column="title" property="title" jdbcType="VARCHAR"/>
     <result column="url" property="url" jdbcType="VARCHAR"/>
   </resultMap>

  <sql id="baseColumnList" >
     id, author, title,url
   </sql>

  <select id="queryLearnResouceList" resultMap="baseResultMap" parameterType="java.util.HashMap">
     select
     <include refid="baseColumnList" />
     from learn_resource
     <where>
       1 = 1
       <if test="author!= null and author !=''">
         AND author like CONCAT(CONCAT('%',#{author,jdbcType=VARCHAR}),'%')
       </if>
       <if test="title != null and title !=''">
         AND title like  CONCAT(CONCAT('%',#{title,jdbcType=VARCHAR}),'%')
       </if>

    </where>
   </select>

  <select id="queryLearnResouceById"  resultMap="baseResultMap" parameterType="java.lang.Long">
     SELECT
     <include refid="baseColumnList" />
     FROM learn_resource
     WHERE id = #{id}
   </select>

  <insert id="add" parameterType="com.dudu.domain.LearnResouce" >
     INSERT INTO learn_resource (author, title,url) VALUES (#{author}, #{title}, #{url})
   </insert>

  <update id="update" parameterType="com.dudu.domain.LearnResouce" >
     UPDATE learn_resource SET author = #{author},title = #{title},url = #{url} WHERE id = #{id}
   </update>

  <delete id="deleteByIds" parameterType="java.lang.String" >
     DELETE FROM learn_resource WHERE id in
     <foreach item="idItem" collection="array" open="(" separator="," close=")">
       #{idItem}
     </foreach>
   </delete>
 </mapper>

参考文章

构建第一个Spring Boot2.0应用之配置Druid数据库连接池
Spring Boot干货系列:(八)数据存储篇-SQL关系型数据库之JdbcTemplate的使用
Spring Boot干货系列:(九)数据存储篇-SQL关系型数据库之MyBatis的使用

猜你喜欢

转载自blog.csdn.net/vae1314chuanchen/article/details/82946569