本文转载自:https://www.cnblogs.com/zkm1992/p/10939730.html
引入依赖
使用的版本取决于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; } }