最近項目中用了通用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就會只給有值的字段賦值(會對傳進來的值做非空判斷)