一、创建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
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.3</version>
</dependency>
- 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<OrderDb> {
}
OrderDbMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.shardingsphere.dao.OrderDbMapper">
</mapper>
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<OrderDb> {
}
OrderDbServiceImpl :需要继承ServiceImpl类,泛型为Mapper类和实体类,需要添加@Service注解
@Service
public class OrderDbServiceImpl extends ServiceImpl<OrderDbMapper, OrderDb> implements OrderDbService {
}
五、编写测试类进行测试
@SpringBootTest
class ShardingsphereApplicationTests {
@Autowired
OrderDbMapper orderDbMapper;
@Autowired
OrderDbService orderDbService;
@Test
void contextLoads() {
Map<String, Object> map = new HashMap<>();
map.put("status", "over");
List<OrderDb> orderDbs1 = orderDbMapper.selectByMap(map);
List<OrderDb> 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}]
网友评论