笔者所接触的项目中,大多拥有大量的数据,数据库都采用分表的设计。本来想分享下分表设计的逻辑,但由于分表都是基于Mybatis的,为了照顾更多的读者,本文先分享在SpringBoot中集成MyBatis的方法,后续将基于此,设计分表的逻辑。
1.主要Maven依赖
MySQL数据库驱动
mysql
mysql-connector-java
runtime
Mybatis的SprignBoot的Starter
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.2.2
2.主要项目配置
配置数据库连接、驼峰命名、mapper路径、domain路径。
# mysql
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/idempotent?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123
# mybatis
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.itspringbootmybatis.domain
3.Domain层
数据库表对应的Java对象
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class UserInfo {
/**
* 自增ID
*/
private Long id;
/**
* 用户名
*/
private String name;
/**
* 用户余额
*/
private BigDecimal money;
/**
* 创建时间
*/
private Date createTime = new Date();
}
4.Mapper层
这里实例定义了一个获取所有用户数据库的接口
@Mapper
@Component
public interface UserInfoMapper {
/**
* 获取所有用户信息
*
* @return 用户
*/
List getAll();
}
对应的SQL
<?xml version="1.0" encoding="UTF-8"?>
5.测试
引入接口,调用方法测试
@SpringBootTest
class ItSpringBootMybatisApplicationTests {
@Resource
private UserInfoMapper userInfoMapper;
@Test
void contextLoads() {
System.out.println(userInfoMapper.getAll());
}
}
可以看到结果是正常输出的
说明集成完毕
本文代码,已经上传到github,详情见如下链接:
https://github.com/larger5/spring-boot-mybaits.git
留言与评论(共有 0 条评论) “” |