Springboot集成mybatis

1.引入依赖

        <!-- 通用Mapper启动器 -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
        </dependency>

2.定义mapper接口

public interface CategoryMapper extends Mapper<Category> {
}

3.启动类添加包扫描注解

@MapperScan("com.viuman.item.mapper")

或者在每个mapper接口上都加

@org.apache.ibatis.annotations.Mapper

4.基本查询

        Category category = new Category();
        category.setParentId(pid);
        return categoryMapper.select(category);

5.分页查询

1)引入依赖

        <!-- 分页助手启动器 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
        </dependency>

2)service层分页

        //开始分页
        PageHelper.startPage(page, rows);
        List<Brand> brands = brandMapper.selectByExample(example);
        return new PageInfo<>(brands); 

5.自定义sql

● 查

import com.viuman.item.pojo.Category;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import tk.mybatis.mapper.additional.idlist.SelectByIdListMapper;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

public interface CategoryMapper extends Mapper<Category>, SelectByIdListMapper<Category, Long> {
    @Select("SELECT c.id, c.name " +
            "FROM tb_category c " +
            "JOIN tb_category_brand cb ON c.id = cb.category_id AND cb.brand_id = #{bid}")
    List<Category> selectByBid(@Param("bid") Long bid);
}

注意:自定义sql查询如果需要下划线转驼峰需要在application.yml加:

mybatis:
  configuration:
    map-underscore-to-camel-case: true

● 增

import com.viuman.item.pojo.Brand;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import tk.mybatis.mapper.common.Mapper;

public interface BrandMapper extends Mapper<Brand> {
    @Insert("INSERT INTO tb_category_brand (category_id, brand_id) VALUES (#{cid},#{bid})")
    int insertCategoryBrand(@Param("cid") Long cid, @Param("bid") Long bid);
}

高级新增:

1)接口继承MySqlMapper

public interface OrderDetailMapper extends Mapper<OrderDetail>, MySqlMapper<OrderDetail> {
}

2)批量新增

orderDetailMapper.insertList(orderDetails);

● 根据id集合查对象集合

1)dao

public interface CategoryMapper extends Mapper<Category>, SelectByIdListMapper<Category, Long> {
}

2)service

    public List<String> getCategoryNames(List<Long> ids) {
        List<Category> categories = categoryMapper.selectByIdList(ids);
        return categories.stream().map(Category::getName).collect(Collectors.toList());
    }

 

posted on 2019-09-15 16:24  bofeng  阅读(209)  评论(0编辑  收藏  举报