最近在學習MybatisPlus是總結了一些常見的方法,記錄下來方便之后使用:
BaseMapper源碼展示:
public interface BaseMapper<T> { /** * <p> * 根據 ID 查詢 * </p> * * @param id 主鍵ID */ T selectById(Serializable id); /** * <p> * 查詢(根據ID 批量查詢) * </p> * * @param idList 主鍵ID列表(不能為 null 以及 empty) */ List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); /** * <p> * 查詢(根據 columnMap 條件) * </p> * * @param columnMap 表字段 map 對象 */ List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); }
1.根據ID查詢實體類信息,例如:
@Test public void selectById(){ User user = userMapper.selectById(1088250446457389058L); System.out.println(user); }
結果:
User(id=1088250446457389058, name=李藝偉, age=28, email=lyw@baomidou.com, managerId=1088248166370832385, createTime=2019-02-14T08:31:16, remark=null)
2.根據ID批量查詢,例如:
@Test public void selectIds(){ List<Long> idList = Arrays.asList(1088248166370832385L, 1094592041087729666L,1094590409767661570L); List<User> userList = userMapper.selectBatchIds(idList); userList.forEach(System.out :: println); }
結果:
User(id=1088248166370832385, name=王天風, age=25, email=wtf@baomidou.com, managerId=1087982257332887553, createTime=2019-02-05T11:12:22, remark=null)
User(id=1094590409767661570, name=張雨琪, age=31, email=zjq@baomidou.com, managerId=1088248166370832385, createTime=2019-01-14T09:15:15, remark=null)
User(id=1094592041087729666, name=劉紅雨, age=32, email=lhm@baomidou.com, managerId=1088248166370832385, createTime=2019-01-14T09:48:16, remark=null)
3.根據 columnMap 條件查詢,例如:
@Test public void selectByMap(){ //map.put("name","王天風") //map.put("age",30) //where name="王天風" and age=30 Map<String,Object> columnMap = new HashMap<>(); //columnMap.put("name","王天風"); //列age為數據庫中的列名,不是實體類中的屬性名 columnMap.put("age",27); List<User> userList = userMapper.selectByMap(columnMap); userList.forEach(System.out::println); }
結果:
User(id=1212614062686031873, name=向南, age=27, email=xn@baomidou.com, managerId=1088248166370832385, createTime=2020-01-02T13:58:16, remark=null)
User(id=1212615304313184258, name=向東, age=27, email=xd@baomidou.com, managerId=1088248166370832385, createTime=2020-01-02T14:03:12, remark=null)
User(id=1212616053072060417, name=向西, age=27, email=xx@baomidou.com, managerId=1088248166370832385, createTime=2020-01-02T14:06:10, remark=null)