使用Mybatis實現簡單和複雜查詢----通用工具類
阿新 • • 發佈:2018-12-14
最近學著使用Mybatis和SpringBoot進行整合,涉及到多種資料型別時,要分別寫入每個對映類,覺得過於繁瑣。尋思著想了個簡單的方式,利用map完成,具體如何實現呢。
下面給大家分享個簡單的例子,我自認為複雜的可以借鑑。
<select id="getDeptMap" parameterType="pd" resultType="pd"> select d.deptno,d.dname from dept d <where> 1 = 1 <if test="deptno != null and deptno != '' "> and d.deptno = #{deptno} </if> </where> </select>
mybatis的配置項
<?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> <!-- 進行Mybatis的相應的環境的屬性定義 --> <settings> <!-- 在本專案之中開啟二級快取 --> <setting name="cacheEnabled" value="true"/> </settings> <!-- 實體對映 --> <typeAliases> <typeAlias type="cn.linkpower.util.PageData" alias="pd"/> </typeAliases> </configuration>
springboot資料庫連線池以及配置項匯入的配置 application.yml
server: port: 80 mybatis: config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置檔案所在路徑 type-aliases-package: cn.linkpower.vo # 定義所有操作類的別名所在包 mapper-locations: # 所有的mapper對映檔案 - classpath:mybatis/mapper/**/*.xml spring: datasource: type: com.alibaba.druid.pool.DruidDataSource # 配置當前要使用的資料來源的操作型別 driver-class-name: org.gjt.mm.mysql.Driver # 配置MySQL的驅動程式類 url: jdbc:mysql://127.0.0.1:3306/javademo # 資料庫連線地址 username: root # 資料庫使用者名稱 password: root # 資料庫連線密碼 filters: stat,wall,log4j # 開啟druid監控還需要進行一項過濾配置 dbcp2: # 進行資料庫連線池的配置 min-idle: 5 # 資料庫連線池的最小維持連線數 initial-size: 5 # 初始化提供的連線數 max-total: 10 # 最大的連線數 max-wait-millis: 200 # 等待連接獲取的最大超時時間
下面的這個工具類才是重點
package cn.linkpower.util;
import java.io.BufferedReader;
import java.io.Reader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.druid.proxy.jdbc.ClobProxyImpl;
/**
* 引數封裝Map
* @author 香蕉不拿拿先生
*
*/
@SuppressWarnings("rawtypes")
public class PageData extends HashMap implements Map{
private static final long serialVersionUID = 1L;
Map map = null;
HttpServletRequest request;
@SuppressWarnings("unchecked")
public PageData(HttpServletRequest request){
this.request = request;
Map properties = request.getParameterMap();
Map returnMap = new HashMap();
//將map的key和value組成的資料包裝成一個Map.Entry物件
Iterator entries = properties.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
while (entries.hasNext()) {
//獲取單個物件
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
//值的型別是String型別的陣列
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
value = values[i] + ",";
}
//value.length()-1 去掉最後一個 ","
value = value.substring(0, value.length()-1);
}else{
value = valueObj.toString();
}
//將每個解析出來的資料儲存在map集合中
returnMap.put(name, value);
}
map = returnMap;
}
public PageData() {
map = new HashMap();
}
@Override
public Object get(Object key) {
Object obj = null;
if(map.get(key) instanceof Object[]) {
Object[] arr = (Object[])map.get(key);
obj = request == null ? arr:(request.getParameter((String)key) == null ? arr:arr[0]);
} else {
obj = map.get(key);
}
return obj;
}
public String getString(Object key) {
return (String)get(key);
}
@SuppressWarnings("unchecked")
@Override
public Object put(Object key, Object value) {
if(value instanceof ClobProxyImpl){ //讀取oracle Clob型別資料
try {
ClobProxyImpl cpi = (ClobProxyImpl)value;
Reader is = cpi.getCharacterStream(); //獲取流
BufferedReader br = new BufferedReader(is);
String str = br.readLine();
StringBuffer sb = new StringBuffer();
while(str != null){ //迴圈讀取資料拼接到字串
sb.append(str);
sb.append("\n");
str = br.readLine();
}
value = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return map.put(key, value);
}
@Override
public Object remove(Object key) {
return map.remove(key);
}
public void clear() {
map.clear();
}
public boolean containsKey(Object key) {
return map.containsKey(key);
}
public boolean containsValue(Object value) {
return map.containsValue(value);
}
public Set entrySet() {
return map.entrySet();
}
public boolean isEmpty() {
return map.isEmpty();
}
public Set keySet() {
return map.keySet();
}
@SuppressWarnings("unchecked")
public void putAll(Map t) {
map.putAll(t);
}
public int size() {
return map.size();
}
public Collection values() {
return map.values();
}
}
三層架構的程式碼
dao層
package cn.linkpower.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import cn.linkpower.util.PageData;
import cn.linkpower.vo.Dept;
@Mapper //必須新增此項註解 不然介面和xml檔案無法整合
public interface IDeptDAO {
//測試map傳入傳出
public List<Dept> getDeptMap(PageData pd)throws Exception;
}
service層
package cn.linkpower.service;
import java.util.List;
import java.util.Map;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.linkpower.util.PageData;
import cn.linkpower.vo.Dept;
public interface IDeptService {
//採用傳入map型別進行資料的新增操作
@Transactional(readOnly = true)
public List<Dept> getDeptMap(PageData pd) throws Exception;
}
實現層
package cn.linkpower.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.linkpower.dao.IDeptDAO;
import cn.linkpower.service.IDeptService;
import cn.linkpower.util.PageData;
import cn.linkpower.vo.Dept;
@Service
public class DeptService implements IDeptService {
@Resource
private IDeptDAO deptDao;
//測試map方式傳入和傳出
@Override
public List<Dept> getDeptMap(PageData pd) throws Exception {
return this.deptDao.getDeptMap(pd);
}
}
基礎控制層
package cn.linkpower.util;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
public class BaseController {
protected Logger logger = Logger.getLogger(this.getClass());
private static final long serialVersionUID = 6357869213649815390L;
/**
* new PageData物件
*
* @return
*/
public PageData getPageData() {
return new PageData(this.getRequest());
}
/**
* 得到ModelAndView
*
* @return
*/
public ModelAndView getModelAndView() {
return new ModelAndView();
}
/**
* 得到request物件
*
* @return
*/
public HttpServletRequest getRequest() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
return request;
}
/**
* 得到32位的uuid
*
* @return
*/
public String get32UUID() {
return UuidUtil.get32UUID();
}
public static void logBefore(Logger logger, String interfaceName) {
logger.info("");
logger.info("start");
logger.info(interfaceName);
}
public static void logAfter(Logger logger) {
logger.info("end");
logger.info("");
}
}
實現程式碼的控制層
package cn.linkpower.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.linkpower.service.IDeptService;
import cn.linkpower.util.BaseController;
import cn.linkpower.util.JsonUtils;
import cn.linkpower.util.PageData;
import cn.linkpower.vo.Dept;
/**
* 測試改進的控制器效果(驗證mybatis傳入map型別)
*
* @author 香蕉不拿拿先生
*
*/
@Controller
public class TestController extends BaseController {
Logger log = LoggerFactory.getLogger(this.getClass());
@Resource
private IDeptService deptService;
@RequestMapping(value = "/getDeptMap", method = RequestMethod.GET)
@ResponseBody
public Object getDeptMap() throws Exception {
log.info("進入控制器");
// 建立map集合物件 儲存引數資訊
PageData pd = new PageData();
// 呼叫父類的定義方法 通過請求建立指定的PageData物件
pd = this.getPageData();
// 和request.getParameter一樣 deptnum
String deptno = pd.getString("deptnum");
log.info("獲取到的資料:" + deptno);
// 儲存資料
pd.put("deptno", deptno);
List<Dept> deptList = this.deptService.getDeptMap(pd);
JsonUtils jsonUtils = new JsonUtils();
jsonUtils.setCode("200");
jsonUtils.setMsg("ok");
jsonUtils.setData(deptList);
return jsonUtils;
// http://localhost/getDeptMap?deptnum=1
}
}
json工具類
package cn.linkpower.util;
public class JsonUtils {
private String code;
private String msg;
private Object data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "JsonUtils [code=" + code + ", msg=" + msg + ", data=" + data + "]";
}
}
資料庫的結構
drop database if exists javademo;
create database mldn character set utf8;
use javademo;
create table dept(
deptno bigint Auto_increment,
dname varchar(50),
constraint pk_deptno primary key(deptno)
);
insert into dept(dname) values("開發部");
insert into dept(dname) values("財務部");
insert into dept(dname) values("市場部");
insert into dept(dname) values("後勤部");
insert into dept(dname) values("公關部");
他的主要思想是使用map進行資料的儲存操作,在mapper.xml檔案中寫的sql語句,是根據PageData類中儲存的鍵值對進行引數的獲取判斷!