This article reprinted from: https://www.cnblogs.com/zkm1992/p/10939730.html
The introduction of dependence
The version used depends SpringBoot version, because there are compatibility issues, version requires confirmation well in advance.
<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>
Increase mapper component scans the configuration
/** * @author zkm * @date 2019/5/19 18:29 */ @Configuration @tk.mybatis.spring.annotation.MapperScan("top.zhangsanwan.eat.repository") @EnableTransactionManagement public class DalConfig { }
Create a base layer interfaces dao
Note: The Base package repository interfaces must not be placed below, in other words, do not be above Mapper component configured to scan to scan!
Creating BaseRepository <T> interface inheritance in three tk.mybatis.mapper:
- Mapper<T>
- IdsMapper<T>
- InsertListMapper<T>
Of course, if the database is used in mysql, you can inherit several interfaces as follows:
- Mapper<T>
- MysqlMapper<T>
public interface BaseMapper<T> extends Mapper<T>, MySqlMapper<T> { }
public interface MySqlMapper<T> extends InsertListMapper<T>, InsertUseGeneratedKeysMapper<T> { }
Create a query interface layer dao
Creating Dao query interface MenuRepository, inherited Base interface BaseRepository Dao layer, corresponding generic database table mapping class.
/** * @author zkm * @date 2019/5/19 18:24 */ public interface MenuRepository extends BaseRepository<Menu> { }
service call dao layer inquiry
/** * @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; } }