1. 程式人生 > >springboot(二)集成mybatis

springboot(二)集成mybatis

stat blog long username user autowire efi can tor

全部內容:
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