美文网首页
springboot之MyBatis的使用

springboot之MyBatis的使用

作者: 小月半会飞 | 来源:发表于2019-01-22 10:57 被阅读0次

    一、添加依赖

    添加mybatis-spring-boot-starter依赖跟mysql依赖

    <!--最新版本,匹配spring Boot1.5 or higher-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.0</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.21</version>
            </dependency>
    

    二、数据源配置

    在src/main/resources/application.properties中配置数据源信息。

    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
    

    三、自定义数据源

    1、添加依赖

    Spring Boot默认使用tomcat-jdbc数据源,如果你想使用其他的数据源,比如这里使用了阿里巴巴的数据池管理,除了在application.properties配置数据源之外,应该额外添加

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

    2、修改Application.java

    这样就算自己配置了一个DataSource,Spring Boot会智能地选择我们自己配置的这个DataSource实例。

    import com.alibaba.druid.pool.DruidDataSource;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    import org.springframework.core.env.Environment;
    
    import javax.sql.DataSource;
    
    @SpringBootApplication
    @MapperScan("com.example.demo.mapper")
    public class Application {
       public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
       @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"));
            dataSource.setInitialSize(2);//初始化时建立物理连接的个数
            dataSource.setMaxActive(20);//最大连接池数量
            dataSource.setMinIdle(0);//最小连接池数量
            dataSource.setMaxWait(60000);//获取连接时最大等待时间,单位毫秒。
            dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效的sql
            dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效
            dataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。
            dataSource.setPoolPreparedStatements(false);//是否缓存preparedStatement,也就是PSCache
            return dataSource;
        }
    }
    
    

    3、在数据库创建表,提供源数据

    CREATE DATABASE /*!32312 IF NOT EXISTS*/`spring` /*!40100 DEFAULT CHARACTER SET utf8 */;
    USE `spring`;
    DROP TABLE IF EXISTS `learn_resource`;
    
    CREATE TABLE `learn_resource` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
      `author` varchar(20) DEFAULT NULL COMMENT '作者',
      `title` varchar(100) DEFAULT NULL COMMENT '描述',
      `url` varchar(100) DEFAULT NULL COMMENT '地址链接',
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM AUTO_INCREMENT=1029 DEFAULT CHARSET=utf8;
    
    insert into `learn_resource`(`id`,`author`,`title`,`url`) values (999,'官方SpriongBoot例子','官方SpriongBoot例子','https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples');
    insert into `learn_resource`(`id`,`author`,`title`,`url`) values (1000,'后端编程','Spring Boot视频教程','http://www.toutiao.com/m1559096720023553/');
    

    四、创建实体类

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

    五、Controller层

    @Controller
    public class HelloController {
        @Autowired
        LearnMapper learnMapper;
    
        @RequestMapping("hello")
        public ModelAndView hello(HttpServletResponse response) throws IOException {
    //        response.getWriter().println("hello");
            LearnResouce learnResouce = new LearnResouce();
            learnResouce.setAuthor("zhangsan");
            learnMapper.add(learnResouce);
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("hello");
            modelAndView.addObject("username","zhangsan");
            return modelAndView;
        }
    
    }
    

    六、Mybatis集成

    1、编写Dao层

    package com.dudu.dao;
    @Mapper
    @Component
    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);
    }
    

    2、修改application.properties 配置文件

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

    3、添加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.example.demo.mapper.LearnMapper">
        <resultMap id="baseResultMap" type="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="LearnResouce" >
            INSERT INTO learn_resource (author, title,url) VALUES (#{author}, #{title}, #{url})
        </insert>
    
        <update id="update" parameterType="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>
    
    

    相关文章

      网友评论

          本文标题:springboot之MyBatis的使用

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