本文參考了:
https://www.cnblogs.com/zkm1992/p/10939730.html
https://www.jianshu.com/p/336c71c68a52
引入依賴
使用的版本取決於SpringBoot的版本,因為存在兼容性的問題,版本需要提前確認好。
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.0.4</version>
</dependency>
增加mapper組件掃描配置
/** * @author zkm * @date 2019/5/19 18:29 */ @Configuration @tk.mybatis.spring.annotation.MapperScan("top.zhangsanwan.eat.repository") @EnableTransactionManagement public class DalConfig { }
創建dao層的base接口
注意:這個Base接口一定不要放在repository包下面,換言之就是不要被上面的Mapper組件掃描配置給掃描到!
創建BaseRepository<T>繼承3個tk.mybatis.mapper下的接口:
- Mapper<T>
- IdsMapper<T>
- InsertListMapper<T>
當然如果數據庫是用的mysql,也可以繼承如下幾個接口:
- Mapper<T>
- MysqlMapper<T>
public interface BaseMapper<T> extends Mapper<T>, MySqlMapper<T> { }
public interface MySqlMapper<T> extends InsertListMapper<T>, InsertUseGeneratedKeysMapper<T> { }
創建dao層查詢接口
創建Dao查詢接口MenuRepository,繼承Dao層的Base接口BaseRepository,泛型為數據庫表對應的映射類。
/** * @author zkm * @date 2019/5/19 18:24 */
public interface MenuRepository extends BaseRepository<Menu> { }
service調用dao層進行查詢
/** * @author zkm * @date 2019/5/19 18:23 */ @Service public class MenuServiceImpl implements IMenuService { @Resource private MenuRepository menuRepository; @Override public List<MenuVO> getMenu(String date) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String today = StringUtils.isEmpty(date) ? format.format(new Date()) : date; Example example = new Example(Menu.class); example.createCriteria().andGreaterThanOrEqualTo("createAt", today + " 00:00:00") .andLessThanOrEqualTo("createAt", today + " 23:59:59"); example.setOrderByClause("sort asc"); List<Menu> menuList = menuRepository.selectByExample(example); List<MenuVO> menuVOList = Lists.newArrayList(); menuList.forEach(menu -> { MenuVO menuVO = new MenuVO(); BeanUtils.copyProperties(menu, menuVO); menuVOList.add(menuVO); }); return menuVOList; } }
實體類
Menu類
public class Menu { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") protected Long id; @Column(name = "menu_name") private String menuName; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "create_time") protected Date createTime; @Column(name = "create_user") protected String createUser; }
基礎接口
Insert
1.InsertMapper<T>
接口:InsertMapper<T>
方法:int insert(T record);
說明:保存一個實體,null的屬性也會保存,不會使用數據庫默認值
public int insertTestUser(TestUser testUser) { return testUserMapper.insert(testUser); }
結果:
2.InsertSelectiveMapper<T>
接口:InsertSelectiveMapper<T>
方法:int insertSelective(T record);
說明:保存一個實體,null的屬性不會保存,會使用數據庫默認值
Update
1.UpdateByPrimaryKeyMapper<T>
接口:UpdateByPrimaryKeyMapper<T>
方法:int updateByPrimaryKey(T record);
說明:根據主鍵更新實體全部字段,null值會被更新
結果:
會把沒有值的屬性變成空請自行實驗
2.UpdateByPrimaryKeySelectiveMapper<T>
接口:UpdateByPrimaryKeySelectiveMapper<T>
方法:int updateByPrimaryKeySelective(T record);
說明:根據主鍵更新屬性不為null的值
public int updateTestUser() { TestUser testUser=new TestUser(); testUser.setId("5f7139ef295d42a3b964c082e0dd838f"); testUser.setName("李四四"); return testUserMapper.updateByPrimaryKeySelective(testUser); }
結果:
Delete
1.DeleteMapper<T>
接口:DeleteMapper<T>
方法:int delete(T record);
說明:根據實體屬性作為條件進行刪除,查詢條件使用等號
public int deleteTestUser() { TestUser testUser=new TestUser(); //根據屬性刪除會把所有密碼是123456的數據刪除
testUser.setPassword("123456"); return testUserMapper.delete(testUser); }
結果:
四個已經全部刪除
2.DeleteByPrimaryKeyMapper<T>
接口:DeleteByPrimaryKeyMapper<T>
方法:int deleteByPrimaryKey(Object key);
說明:根據主鍵字段進行刪除,方法參數必須包含完整的主鍵屬性
public int deleteKeyTestUser() { //根據主鍵ID刪除
return testUserMapper.deleteByPrimaryKey("5f7139ef295d42a3b964c082e0dd838f"); }
結果:

Select
1.SelectMapper<T>
接口:SelectMapper<T>
方法:List<T> select(T record);
說明:根據實體中的屬性值進行查詢,查詢條件使用等號
public List<TestUser> selectTestUser() { TestUser testUser=new TestUser(); testUser.setPassword("123456"); testUser.setUsername("lisi"); return testUserMapper.select(testUser); }
結果:
2.SelectByPrimaryKeyMapper<T>
接口:SelectByPrimaryKeyMapper<T>
方法:T selectByPrimaryKey(Object key);
說明:根據主鍵字段進行查詢,方法參數必須包含完整的主鍵屬性,查詢條件使用等號
結果:
根據主鍵查詢請自行實驗
3.SelectAllMapper<T>
接口:SelectAllMapper<T>
方法:List<T> selectAll();
說明:查詢全部結果,select(null)方法能達到同樣的效果
結果:
查詢所有請自行實驗
4.SelectOneMapper<T>
接口:SelectOneMapper<T>
方法:T selectOne(T record);
說明:根據實體中的屬性進行查詢,只能有一個返回值,有多個結果是拋出異常,查詢條件使用等號
public TestUser selectOneTestUser() { TestUser testUser=new TestUser(); testUser.setUsername("wangwu"); //結果只能返回一條數據否則會拋出異常
return testUserMapper.selectOne(testUser); }
結果:

5.SelectCountMapper<T>
接口:SelectCountMapper<T>
方法:int selectCount(T record);
說明:根據實體中的屬性查詢總數,查詢條件使用等號
結果:
返回查詢個數請自行實驗
Example 方法
Select 方法
1.SelectByExampleMapper<T>
接口:SelectByExampleMapper<T>
方法:List<T> selectByExample(Object example);
說明:根據Example條件進行查詢
重點:這個查詢支持通過Example類指定查詢列,通過selectProperties方法指定查詢列
public List<TestUser> selectExample() { Example example = new Example(TestUser.class); //排序方法setOrderByClause("字段名 ASC")DESC降序
example.setOrderByClause("name ASC"); example.createCriteria() //添加xxx字段等於value條件
.andEqualTo("password","123456") //模糊查詢xxx字段like value條件
.andLike("name","%四%") //可以自由拼接SQL //.andCondition("ID = '5f7139ef295d42a3b964c082e0dd838f' ") //或者可以這么寫
.andCondition("ID =","5f7139ef295d42a3b964c082e0dd838f") ; return testUserMapper.selectByExample(example); }
實例解析:
mybatis的逆向工程中會生成實例及實例對應的example,example用於添加條件,相當where后面的部分
Example example = new Example();
Criteria criteria = example.createCriteria();

還有criteria.orxxxx的方法跟上面一樣這里不做解釋
2. SelectCountByExampleMapper<T>
接口:SelectCountByExampleMapper<T>
方法:int selectCountByExample(Object example);
說明:根據Example條件進行查詢總數
查詢總數的方法跟上面的寫法一樣
Update 方法
1.UpdateByExampleMapper<T>
接口:UpdateByExampleMapper<T>
方法:int updateByExample(@Param("record") T record, @Param("example") Object example);
說明:根據Example條件更新實體record包含的全部屬性,null值會被更新
2.UpdateByExampleSelectiveMapper<T>
接口:UpdateByExampleSelectiveMapper<T>
方法:int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);
說明:根據Example條件更新實體record包含的不是null的屬性值
Delete 方法
1.DeleteByExampleMapper<T>
接口:DeleteByExampleMapper<T>
方法:int deleteByExample(Object example);
說明:根據Example條件刪除數據
搭配手寫sql
tk.mybatis對於單表操作可以避免手寫sql,但是業務中一些復雜sql肯定是必不可少的,那么tk.mybatis也支持。
首先看下tk.mybatis的依賴
<dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>4.1.5</version> </dependency>
mapper-spring-boot-starter.jar同時依賴了org.mybatis
application.yml
# MyBatis配置 mybatis: # 搜索指定包別名 typeAliasesPackage: com.yzf.enterprise.market.**.domain # 配置mapper的掃描,找到所有的mapper.xml映射文件 mapperLocations: classpath*:mybatis/**/*Mapper.xml # 加載全局的配置文件 configLocation: classpath:mybatis/mybatis-config.xml
@MapperScan-----掃描所有的Mapper接口
@MapperScan("com.yzf.enterprise.market.**.mapper")
Mapper接口
@Repository public interface WxUserInfoMapper extends Mapper<WxUserInfo>, MySqlMapper<WxUserInfo> { /** * 保存微信用戶相關信息 * @param wxUserInfo */ void saveWxUserInfo(WxUserInfo wxUserInfo); }
mapper.xml
我上面配置的xml文件地址為:mapperLocations: classpath*:mybatis/**/*Mapper.xml
因此xml文件放在這個位置。
<?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.yzf.enterprise.market.project.weixin.mapper.WxUserInfoMapper"> <resultMap type="com.yzf.enterprise.market.project.weixin.domain.WxUserInfo" id="WxUserInfoResult"> <id property="userId" column="id"/> <result property="unionId" column="union_id"/> <result property="openId" column="open_id"/> <result property="status" column="status"/> </resultMap> <!-- unionId字段為唯一索引,因此存在unionId,就更新;不存在,則插入 --> <insert id="saveWxUserInfo" useGeneratedKeys="true" keyProperty="id" parameterType="com.yzf.enterprise.market.project.weixin.domain.WxUserInfo"> insert into wx_user_info( <if test="unionId != null and unionId != ''"> union_id, </if> <if test="openId != null and openId != ''"> open_id, </if> create_time )values ( <if test="unionId != null and unionId != ''"> #{unionId}, </if> <if test="openId != null and openId != ''"> #{openId}, </if> sysdate() ) on duplicate key update <if test="openId != null and openId != ''"> open_id = #{openId}, </if> update_time = now() </insert> </mapper>