最近项目中用了通用mapper,可以在不写xml的情况下快速进行单表的增删改查,下面记录一下使用
pom.xml中引入
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
创建Mapper接口,需要继承Mapper<实体类>
public interface ProductInfoMapper extends Mapper<ProductInfo> {
}
然后在主类中开启自动扫包,注意@MapperSacn是在tk.mybatis包下的
@SpringBootApplication
@MapperScan(basePackages = "com.pers.product.Mapper")
public class ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
}
查询示例:
public List<ProductInfo> getProductUpAll() {
ProductInfo productInfo=new ProductInfo();
productInfo.setProductStatus(0);
List<ProductInfo> productInfoList=productInfoMapper.select(productInfo);
return productInfoList;
}
或使用条件查询
public List<ProductInfo> getProductUpAll() {
Example example = new Example(ProductInfo.class);
example.createCriteria().andEqualTo("productStatus", 0);
List<ProductInfo> productInfoList=productInfoMapper.selectByExample(example);
return productInfoList;
}
插入示例:
public void save() {
OrderMaster orderMaster=new OrderMaster();
orderMaster.setOrderId("1234567");
orderMaster.setBuyerName("孙悟空");
orderMaster.setBuyerPhone("13232228212");
orderMaster.setBuyerAddress("北京");
orderMaster.setBuyerOpenid("1211321");
orderMasterMapper.insertSelective(orderMaster);
}
有Selective就会只给有值的字段赋值(会对传进来的值做非空判断)