最近一直在學springboot和Cloud,互聯網公司現在也更傾向於微服務這一塊,前景是一篇光明的,特別是在springboot上開發的Cloud的部分,是一套分布式的整體解決方案,學好這一塊至少這幾年都很吃香;
既然學習很久,落地實踐一下為好;
項目git網址:https://github.com/David-BIQI/manage.git(項目使用比較新的springboot2.0 還有jdk8 )
參照的代碼規范:https://github.com/xwjie/PLMCodeTemplate.git (這個是一套能夠落地的代碼規范,跟着風哥學習很多)
項目已經初始化,連接數據庫了,配置mybatis tk框架,加上分頁插件<有空還要連接一下mybatis的原理,還有分頁的實現原理>
application.yml下 mybatis配置:
# mybatis包的掃描,還有就是映射文件設置 mybatis tk插件的使用
mybatis:
type-aliases-package: package com.biqi.model
mapper-locations: classpath:mapper/*.xml
#配置駝峰下划線
configuration:
map-underscore-to-camel-case: true
pom中的架包:
<!--mybatis tk框架--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>1.2.4</version> </dependency> <!---分頁插件--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.3</version> </dependency> <!---mybatis tk框架-->
tk實現的例子:
1、定義一個接口
package com.common.mybatis;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
/**
* Description: 實現增刪改查的基本sql功能
* @Package com.common.mybatis
* @author xiebq @date 2018年6月7日 上午9:53:34
*/
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
//FIXME 特別注意,該接口不能被掃描到,否則會出錯
}
dao繼承接口
package com.biqi.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import com.biqi.model.User;
import com.common.mybatis.MyMapper;
/**
* @Package com.biqi.dao
* @author xiebq @date 2018年6月7日 上午9:55:30
*/
@Mapper
public interface UserDao extends MyMapper<User> {
/**
* 測試數據庫連接
* @return
*/
@Select("SELECT count(*) FROM User ")
Integer countUser();
int countUser2();
}
具體使用
public User getUserByid(Integer id) { User user = userDao.selectByPrimaryKey(id); return user; } public Integer saveUser(User user) { user.setId(null); user.setCreateby(SuperUserId); user.setCreated(new Date()); userDao.insertUseGeneratedKeys(user); return user.getId(); } public Boolean deleteUser(Integer id) { User oldUser = userDao.selectByPrimaryKey(id); notNull(oldUser, "用戶id:"+id+" 不存在"); userDao.deleteByPrimaryKey(id); return true; }
分頁的例子:
public PageDto<User> listPage(Integer page, Integer size) {
//tk mybatis進行查詢
Example example = new Example(User.class);
//分頁查詢
PageHelper.startPage(page, size);
//添加查詢條件
//example.createCriteria().andEqualTo("id",XX);
example.orderBy("created").desc();
List<User> list = userDao.selectByExample(example);
//分頁查詢-->若凡在這里,不能進行分頁 PageHelper.startPage(page, size);
PageInfo<User> pageInfo = new PageInfo<User>(list);
return new PageDto<>(list, pageInfo.getTotal());
}
xml文件<不喜歡在接口中寫sql語句的>
<?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.biqi.dao.UserDao"> <select id="countUser2" resultType="java.lang.Integer"> SELECT count(*) FROM User </select> </mapper>
以上這些步驟做好單表的增刪改查,以及分頁基本完成。以下是tk能夠完成以下的查詢,

