首页 > 代码库 > springboot(二)集成mybatis

springboot(二)集成mybatis

全部内容:
1,集成mybatis
2,分页查询使用分页插件pagehelper
工程代码:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo

 

1.添加集成mybatis的依赖

<!--最新版本,匹配spring Boot1.5及以上的版本-->
<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>
</dependency>

2.数据源的配置

技术分享

2.1 applacation.properties的配置

#主配置开发环境
spring.profiles.active=dev
#主配置生产环境
#spring.profiles.active=prod

#配置启动的接口
server.port=8090
#配置springboot默认的context-path
server.context-path=/kawa

#时间格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#时区设置
spring.jackson.time-zone=Asia/Chongqing
#日志设置
logging.config=classpath:log4j2-dev.xml

2.1 application-dev.properties的配置

#数据库配置
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/baba?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = kawa2016
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
#指定bean所在包
mybatis.type-aliases-package=com.kawa.pojo
#指定映射文件
mybatis.mapper-locations=classpath:mapper/*.xml

 3.添加数据源此处使用阿里的德鲁克来管理

3.1 添加依赖

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

3.2 在启动工程的入口文件加添数据库连接池配置(SpbDemoApplication.java)

技术分享

package com.kawa;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import com.alibaba.druid.pool.DruidDataSource;

@SpringBootApplication
public class SpbDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpbDemoApplication.class, args);
    }
    
     @Autowired
        private Environment env;
         /**
          *destroy-method="close"的作用是当数据库连接不使用的时候,
          *                就把该连接重新放到数据池中,方便下次使用调用.     
          * @return
          */
        @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);
            //用来检测连接是否有效的sql
            dataSource.setValidationQuery("SELECT 1");
            //申请连接时执行validationQuery检测连接是否有效
            dataSource.setTestOnBorrow(false);
            //建议配置为true,不影响性能,并且保证安全性。
            dataSource.setTestWhileIdle(true);
            //是否缓存preparedStatement,也就是PSCache
            dataSource.setPoolPreparedStatements(false);
            return dataSource;
        }        
}

 4.集成mabatis

4.1 初始化sql脚本

技术分享

4.2 创建实体类

public class User {
    private Long id;
    private String username; 
    private String password; 
    private String phone;  
    private String email;  
    private Date created;  
    private Date updated;
  //getter&setter      
}

4.3 Dao层和mapper

application-dev.properties配置文件

#指定bean所在包
mybatis.type-aliases-package=com.kawa.pojo
#指定映射文件
mybatis.mapper-locations=classpath:mapper/*.xml

4.3.1 Dao

@Mapper
public interface UserDao {
    List<User> queryUserList(Map<String,Object> params);
}

4.3.2 mapper 

<?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.kawa.dao.UserDao">
    
    <sql id="columnList">
        id,username,password,phone,email,created,updated
    </sql>
    <!-- 模糊查询 -->
    <sql id="userList">
        <where>
            <if test=" username != null and username != ‘‘">
                and username like "%"#{username}"%"
            </if>
            <if test="phone != null and phone != ‘‘">
                and phone like "%"#{phone}"%"
            </if>
            <if test="email != null and email != ‘‘">
                and email like "%"#{email}"%"
            </if>
        </where>
    </sql>
    <select id="queryUserList" resultType="User">
        SELECT 
        <include refid="columnList"/>
         FROM tb_user
         <include refid="userList"/>
    </select>

</mapper>

5.Service和controller

5.1 service 

package com.kawa.sercice;

import java.util.List;
import java.util.Map;

import com.kawa.pojo.User;

public interface UserService {
    List<User> queryUserList(Map<String,Object> params);

}



/********实现seivice接口********/
package com.kawa.sercice.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.kawa.dao.UserDao;
import com.kawa.pojo.User;
import com.kawa.sercice.UserService;


@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    UserDao userDao;

    @Override
    public List<User> queryUserList(Map<String, Object> params) {
        PageHelper.startPage(Integer.parseInt(params.get("page").toString()) , Integer.parseInt(params.get("rows").toString()));
        return userDao.queryUserList(params);
    }
}

5.2 controller

package com.kawa.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.kawa.pojo.User;
import com.kawa.pojo.UserQuery;
import com.kawa.pojo.UserQueryList;
import com.kawa.sercice.UserService;

/**
 * 
 * @author Administrator
 *
 */
@RestController
public class UserController {
    
    @Autowired
    UserService userService;
    
    @RequestMapping(path="/getAll",method=RequestMethod.POST)
    public ResponseEntity<UserQueryList> queryUsers(HttpServletRequest request,@RequestBody UserQuery userQuery){
        if(userQuery.getPage() == null){
            //第一页从1开始而不是0
            userQuery.setPage(1);
        }
        if(userQuery.getRows() == null){
            userQuery.setRows(10);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("page", userQuery.getPage());
        map.put("rows", userQuery.getRows());
        map.put("username", userQuery.getUsername());
        map.put("phone", userQuery.getPhone());
        map.put("email", userQuery.getEmail());
        List<User> queryAllUsers = userService.queryUserList(map);
        PageInfo<User> pageInfo = new PageInfo<>(queryAllUsers);
        UserQueryList queryList = new UserQueryList();
        queryList.setUsers(queryAllUsers);
        queryList.setTotlePage(pageInfo.getPages());
        Integer total = new Long(pageInfo.getTotal()).intValue();
        queryList.setTotleRecords(total);
        return new ResponseEntity<UserQueryList>(queryList,HttpStatus.OK);
    }

}

6.演示结果

技术分享

 

springboot(二)集成mybatis