天天看点

mybatis-plus的配置和使用文档

一、安装

pom文件中引入

<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
</dependency>
           

二、配置

1、新建config配置类

@Configuration
@MapperScan("com.test.demo.mapper*")
public class MybatisPlusConfig {

    /**
     * mybatis-plus分页插件<br>
     * 文档:http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        List<ISqlParser> sqlParserList = new ArrayList<>();
        // 攻击 SQL 阻断解析器、加入解析链
        sqlParserList.add(new BlockAttackSqlParser());
        paginationInterceptor.setSqlParserList(sqlParserList);
        return paginationInterceptor;
    }

    /**
     * 乐观锁插件
     *
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}
           

这里的MapperScan里的路径就是我们mapper所在的目录。

2、application.yml中的配置

spring:
  application:
    name: xx
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://127.0.0.1:3306/xx?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: xx
    password: xx
    max-wait: 60000
    max-active: 100
    min-idle: 10
    initial-size: 10
mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  global-config:
    db-config:
      field-strategy: not-empty
      id-type: auto
      db-type: mysql
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true
    auto-mapping-unknown-column-behavior: none
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
           

三、通用方法的使用

mybatis-plus已经封装好了我们开发需要的常见方法,这些方法可以直接使用,如下所示:

mybatis-plus的配置和使用文档

1、创建entity实体类(已订单为例)

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SmartOrders implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private Integer productId;

    private String productName;

    private Integer quantity;

    /**
     * 乐观锁
     */
    @Version
    private Integer version;
           

2、创建mapper

@Repository
public interface SmartOrdersMapper extends BaseMapper<SmartOrders> {
//这个basemapper就是mp提供的通用mapper,里面封装了很多通用的增删改查方法
}
           

3、创建Service

public interface SmartOrdersService extends IService<SmartOrders> {
//要继承Iservice
}

           

4、创建ServiceImpl

@Service
public class SmartOrdersServiceImpl extends ServiceImpl<SmartOrdersMapper, SmartOrders> implements SmartOrdersService {
//需要继承ServiceImpl
}
           

5、测试

5.1、新建数据库,并创建好表

mybatis-plus的配置和使用文档

5.2、编写测试类

@SpringBootTest
@Slf4j
class TestApplicationTests {

    @Autowired
    SmartOrdersService ordersService;

    @Test
    void Test1() {
        SmartOrders orders = ordersService.getById(1);
        log.info(JSONObject.toJSONString(orders));
    }

}
           

5.3、测试结果

mybatis-plus的配置和使用文档

插入更新等操作同理(更新时,配置了乐观锁,那么同一时间只有一个更新操作可以成功)

5.4、可能会遇到的问题

mybatis-plus有很多的关键字,当表中的字段和这些关键字相同时,增删改查就会失败。比如:字段命名为name,表命名为order等。

四、多表关联查询

多表关联查询其实和正常的查询是一样的。

1、创建商品属性表(smart_product)

mybatis-plus的配置和使用文档

2、创建复合实体类

@Data
public class ProductOrderInfo implements Serializable {

    
    private Integer orderId;

    private Integer productId;

    private String productName;

    private String productInfo;

    private Integer quantity;
}
           

3、mapper和mapper.xml

mapper:

@Repository
public interface SmartOrdersMapper extends BaseMapper<SmartOrders> {

    ProductOrderInfo selectByOrderId(@Param("orderId") Integer orderId);

}
           

xml:

<select id="selectByOrderId" resultType="com.chengyan.test.dto.ProductOrderInfo" parameterType="java.lang.Integer">
        select
        a.id as orderId,
        b.id as productId,
        b.product_name as productName,
        b.product_info as productInfo,
        b.quantity as quantity
        from
        smart_orders as a
        join smart_product as b
        on a.product_id = b.id
    </select>
           

4、 测试即结果

测试:

@Test
    void Test2(){
        ProductOrderInfo productOrderInfo = ordersMapper.selectByOrderId(1);
        log.info(JSONObject.toJSONString(productOrderInfo));
    }
           

结果:

mybatis-plus的配置和使用文档

五、 分页查询

通过Page类来实现

1 、Service,impl和mapper

service:

public interface SmartOrdersService extends IService<SmartOrders> {

    Page<ProductOrderInfo> selectByOrderId(Integer orderId);

}

           

impl:

@Override
    public Page<ProductOrderInfo> selectByOrderId(Integer orderId) {
        
        return orderMapper.selectByOrderId(new Page<ProductOrderInfo>(2, 2), orderId);
    }
           
mybatis-plus的配置和使用文档

这里直接通过page类的构造函数来创建了Page类。(current是当前的页数,size是每页有多少条数据)

mapper:

@Repository
public interface SmartOrdersMapper extends BaseMapper<SmartOrders> {

    Page<ProductOrderInfo> selectByOrderId(Page<ProductOrderInfo> page, @Param("orderId") Integer orderId);

}
           

xml不需要修改。

2、结果:

mybatis-plus的配置和使用文档