<!--通用mapper起步依赖--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.4</version> </dependency>
在Dao的接口上继承tk包下的Mapper
import tk.mybatis.mapper.common.Mapper;
public interface BrandMapper extends Mapper<Brand> {}
在启动类上添加 开启通用Mapper的包扫描
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan(basePackages = {"com.changgou.goods.dao"}) //开启通用Mapper的包扫描
通用mapper的基础操作
//增加
brandMapper.insertSelective(brand);
//删除
brandMapper.deleteByPrimaryKey(id);
//修改
brandMapper.updateByPrimaryKeySelective(brand);
//查询
brandMapper.selectByPrimaryKey(id);;
根据条件查询
//自定义条件搜索对象Example
Example example = new Example(Brand.class);
Example.Criteria criteria = example.createCriteria();//条件构造器
if (brand != null) {
//brand.name!=null 根据名字模糊查询 where name like '%华%'
if(StringUtil.isNotEmpty(brand.getName())){
criteria.andLike("name","%"+brand.getName()+"%");
}
//brand.letter!=null 根据首字母进行查询
if(StringUtil.isNotEmpty(brand.getLetter())){
criteria.andEqualTo("letter",brand.getLetter());
}
}
return brandMapper.selectByExample(example);
条件分页查询
//分页
PageHelper.startPage(page,size);
//自定义条件搜索对象Example
Example example = new Example(Brand.class);
Example.Criteria criteria = example.createCriteria();//条件构造器
if (brand != null) {
//brand.name!=null 根据名字模糊查询 where name like '%华%'
if(StringUtil.isNotEmpty(brand.getName())){
criteria.andLike("name","%"+brand.getName()+"%");
}
//brand.letter!=null 根据首字母进行查询
if(StringUtil.isNotEmpty(brand.getLetter())){
criteria.andEqualTo("letter",brand.getLetter());
}
}
Page<Brand> page= (Page<Brand>)brandMapper.selectByExample(example);
return new PageResult(page.getTotal(), page.getResult());