Springboot整合Mybatis+Mybatis Plus

一、创建springboot项目

二、配置数据库连接

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/order?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

新建数据库表:

DROP TABLE IF EXISTS `order_db`;
CREATE TABLE `order_db` (
  `order_id` bigint(20) NOT NULL,
  `price` decimal(10,0) NOT NULL,
  `user_id` bigint(20) NOT NULL,
  `status` varchar(50) NOT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `order_db` VALUES ('1', '222', '2', 'over');

三、配置Mybatis+Mybatis Plus

  • 添加mybatis-plus-boot-starter
        
            com.baomidou
            mybatis-plus-boot-starter
            2.3
        
  • yml配置Mybatis Plus
mybatis-plus:
  global-config:
    db-config:
      id-type: auto
      field-strategy: not_empty
      #驼峰下划线转换
      column-underline: true
      #逻辑删除配置
      logic-delete-value: 0
      logic-not-delete-value: 1
      db-type: mysql
    refresh: false
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.springbootshardingjdbc.entity
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
  • 创建实体类和映射文件


实体类:

public class OrderDb {
    public Long orderId;
    public BigDecimal price;
    public Integer userId;
    public String status;

    get\set....

OrderDbMapper :继承BaseMapper,泛型为所要操作实体类

public interface OrderDbMapper extends BaseMapper {
}

OrderDbMapper.xml






ShardingsphereApplication 中开启Mapper文件扫描 :@MapperScan

@SpringBootApplication
@MapperScan(value = "com.example.shardingsphere.dao")
public class ShardingsphereApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShardingsphereApplication.class, args);
    }

}

四、添加Service

OrderDbService

public interface OrderDbService extends  IService {
}

OrderDbServiceImpl :需要继承ServiceImpl类,泛型为Mapper类和实体类,需要添加@Service注解

@Service
public class OrderDbServiceImpl extends ServiceImpl implements OrderDbService {
    
}

五、编写测试类进行测试

@SpringBootTest
class ShardingsphereApplicationTests {

  @Autowired
    OrderDbMapper orderDbMapper;
    @Autowired
    OrderDbService orderDbService;

    @Test
    void contextLoads() {
        Map map = new HashMap<>();
        map.put("status", "over");
        List orderDbs1 = orderDbMapper.selectByMap(map);
        List orderDbs2 = orderDbService.selectByMap(map);
        System.out.println(JSON.toJSONString(orderDbs1));
        System.out.println(JSON.toJSONString(orderDbs2));
    }

}

输出:
[{"orderId":1,"price":222,"status":"over","userId":2}]
[{"orderId":1,"price":222,"status":"over","userId":2}]

你可能感兴趣的:(Springboot整合Mybatis+Mybatis Plus)