zoukankan      html  css  js  c++  java
  • spring-boot-mybatis

    添加依赖

    spring boot 与 mybatis版本对应关系
    http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

                <!--最新版本,匹配spring Boot1.5 or higher-->
    		<dependency>
    			<groupId>org.mybatis.spring.boot</groupId>
    			<artifactId>mybatis-spring-boot-starter</artifactId>
    			<version>1.3.0</version>
    		</dependency>
    
    		<!--pagehelper 分页插件-->
    		<dependency>
    			<groupId>com.github.pagehelper</groupId>
    			<artifactId>pagehelper-spring-boot-starter</artifactId>
    			<version>1.1.0</version>
    		</dependency>
    
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>com.alibaba</groupId>
    			<artifactId>druid</artifactId>
    			<version>1.0.19</version>
    		</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.properties中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。

    数据源配置

    spring.datasource.url = jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
    spring.datasource.username = root
    spring.datasource.password = root
    spring.datasource.driver-class-name = com.mysql.jdbc.Driver
    

    数据源定义

        @Autowired
        private Environment env;
    
        //destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.
        @Bean(destroyMethod = "close")
        public DataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(env.getProperty("spring.datasource.url"));
            //用户名
            dataSource.setUsername(env.getProperty("spring.datasource.username"));
            //密码
            dataSource.setPassword(env.getProperty("spring.datasource.password"));
            dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
            //初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
            dataSource.setInitialSize(2);
            //最大连接池数量
            dataSource.setMaxActive(20);
            //最小连接池数量
            dataSource.setMinIdle(0);
            //获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,
            //如果需要可以通过配置 useUnfairLock属性为true使用非公平锁。
            dataSource.setMaxWait(60000);
            //用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。
            //如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。
            dataSource.setValidationQuery("SELECT 1");
            //申请连接时执行 validationQuery检测连接是否有效,做了这个配置会降低性能。
            dataSource.setTestOnBorrow(false);
            //建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,
            // 如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
            dataSource.setTestWhileIdle(true);
            //是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,
            // 比如说oracle。在mysql下建议关闭。
            dataSource.setPoolPreparedStatements(false);
            return dataSource;
        }
    

    实体对象

    public class LearnResouce {
        private Long id;
        private String author;
        private String title;
        private String url;
        // SET和GET方法
    }
    

    Mybatis集成 方案一:注解方式

    Mybatis注解的方式好简单,只要定义一个dao接口,然后sql语句通过注解写在接口方法上。最后给这个接口添加@Mapper注解或者在启动类上添加@MapperScan(“com.dudu.dao”)注解都行。

    @Mapper //声明为一个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);
    
    
        /**
         * @param id
         * @return
         * @Results是结果映射列表,
         * @Result中property是domain类的属性名, colomn 是数据库表的字段名
         */
        @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注解用于生成查询用的sql语句,type 参数指定的Class类,必须要能够通过无参的构造函数来初始化。
         * 有别于@Select注解,@SelectProvide指定一个Class及其方法,并且通过调用Class上的这个方法来获得sql语句。
         *
         *
         * 在超过一个参数的情况下,@SelectProvide方法必须接受Map<String, Object>做为参数,
         * 如果参数使用了@Param注解,那么参数在Map中以@Param的值为key,也可以方法中使用 @Param 获取key 的值
         * 如果参数没有使用@Param注解,那么参数在Map中以参数的顺序为key,
         *
         * @param params
         * @return
         */
        @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();
            }
        }
    }
    
    

    有些复杂点需要动态SQL语句,就比如上面方法中根据查询条件是否有值来动态添加sql的,就需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider等注解。

    Mybatis集成 方案二:XML配置方式

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

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

    修改application.properties 配置文件

    #指定domain bean所在包
    mybatis.type-aliases-package=com.dudu.domain
    #指定 mapper的xml 映射文件
    mybatis.mapperLocations=classpath:mapper/*.xml
    

    添加LearnMapper的映射文件

    在src/main/resources目录下新建一个mapper目录,在mapper目录下新建LearnMapper.xml文件。

    通过mapper标签中的namespace属性指定对应的dao映射,这里指向LearnMapper。

    <?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>
    

    mybatis官方中文参考文档

    http://www.mybatis.org/mybatis-3/zh/java-api.html

    物理分页插件pagehelper,配置

    需在查询list之前使用PageHelper.startPage(int pageNum, int pageSize)方法即可。pageNum是第几页,pageSize是每页多少条。

    @Service
    public class LearnServiceImpl implements LearnService {
    
        @Autowired
        LearnMapper learnMapper;
    
        @Override
        public int add(LearnResouce learnResouce) {
            return this.learnMapper.add(learnResouce);
        }
    
        @Override
        public int update(LearnResouce learnResouce) {
            return this.learnMapper.update(learnResouce);
        }
    
        @Override
        public int deleteByIds(String[] ids) {
            return this.learnMapper.deleteByIds(ids);
        }
    
        @Override
        public LearnResouce queryLearnResouceById(Long id) {
            return this.learnMapper.queryLearnResouceById(id);
        }
    
        /**
         * 分页插件使用
         *
         * @param params
         * @return
         */
        @Override
        public List<LearnResouce> queryLearnResouceList(Map<String, Object> params) {
            PageHelper.startPage(Integer.parseInt(params.get("page").toString()),
                    Integer.parseInt(params.get("rows").toString()));
            return this.learnMapper.queryLearnResouceList(params);
        }
    }
    
    

    分页插件PageHelper项目地址: https://github.com/pagehelper/Mybatis-PageHelper

  • 相关阅读:
    GROUP BY及GROUP BY的高阶用法
    触发器基本语法
    按标识符截取字符串 管道型函数
    delphi try except语句 和 try finally语句用法
    Qt 文件的操作
    c++ string 转double
    结构体变量的 extern 使用方法,转--
    c++ 生成dll文件并调用-转
    基2时域抽取FFT、IFFT的C++实现代码,另附DFT与IDFT的原始实现--转1
    c++ 生成dll文件并调用
  • 原文地址:https://www.cnblogs.com/zhangjianbin/p/10078434.html
Copyright © 2011-2022 走看看