tk.mybatis使用方法


引入依賴

使用的版本取決於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下的接口:

    1. Mapper<T>
    2. IdsMapper<T>
    3. InsertListMapper<T>
/**
 * @author zkm
 * @date 2019/5/19 18:29
 */
public interface BaseRepository<T> extends Mapper<T>, IdsMapper<T>, InsertListMapper<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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM