在现代 Java 开发中,与数据库交互是一个非常常见的需求。Mybatis - flex 是一个功能强大且易于上手的持久层框架,它为开发者提供了便捷的方式来操作数据库。在这篇博客中,我们将介绍如何快速开始使用Mybatis - flex。
一、环境准备
Maven 环境搭建(Idea)http://maven.apache.org/download.cgi
编辑环境变量:java 1.8
1.1 Maven仓库介绍
本地仓库就是本地计算机上的某个⽂件夹(可以是⾃定义的任何⽂件夹)远程仓库就是远程主机上的jar⽂件仓库
中央仓库maven官⽅提供的仓库,包含了所需的⼀切依赖(免配置)
公共仓库除了中央仓库以外的第三⽅仓库都是公共仓库,例如aliyun(需要配置)
私服企业搭建的供内部使⽤的maven仓库
1.2 Maven仓库配置
在maven_home/conf/settings.xml中进⾏配置公共仓库
<mirrors>
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
</mirrors>
1.3 配置Maven
在创建项目后添加
二、开始搭建
2.1 创建数据库表
可任意选择自己的数据库表,但在后面编写实体类时需要修改属性名和数据类型
CREATE TABLE IF NOT EXISTS `tb_account`
(
`id` INTEGER PRIMARY KEY auto_increment,
`user_name` VARCHAR(100),
`age` INTEGER,
`birthday` DATETIME
);
INSERT INTO tb_account(id, user_name, age, birthday)
VALUES (1, '张三', 18, '2020-01-11'),
(2, '李四', 19, '2021-03-21');
2.2 创建 Spring Boot 项目,并添加 Maven 依赖
创建项⽬ File->New->Project
需要添加的 Maven 主要依赖:在prom.xml中修改
<dependencies>
<dependency>
<groupId>com.mybatis-flex</groupId>
<artifactId>mybatis-flex-spring-boot-starter</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.3 对 Spring Boot 项目进行配置
在 application.yml 中配置数据源:
具体代码:
# DataSource Config
spring:
datasource:
url: jdbc:mysql://localhost:3306/flex_demo
username: root //使用自己数据库的用户名
password: 123456 //使用自己数据库的密码
2.4 在 Spring Boot 启动类中添加 @MapperScan 注解:
具体代码:
@SpringBootApplication
@MapperScan("com.mybatisflex.demo.mapper")
public class MybatisFlexTestApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisFlexTestApplication.class, args);
}
}
2.5 编写实体类和 Mapper 接口
实体类Account.java
具体代码:
@Data
@Table("tb_account") //设置实体类与表名的映射关系
public class Account {
@Id(keyType = KeyType.Auto) //标识主键为自增
private Long id;
private String userName;
private Integer age;
private Date birthday;
}
Mapper 接口继承 BaseMapper 接口:
具体代码:
public interface AccountMapper extends BaseMapper<Account> {
}
2.6 开始使用
添加测试类,进行功能测试:
具体代码:
import static com.mybatisflex.test.entity.table.AccountTableDef.ACCOUNT;
@SpringBootTest
class MybatisFlexTestApplicationTests {
@Autowired //添加此处1
private AccountMapper accountMapper;
@Test
void contextLoads() {
QueryWrapper queryWrapper = QueryWrapper.create()
.select()
.where(ACCOUNT.AGE.eq(18)); //添加此处2
Account account = accountMapper.selectOneByQuery(queryWrapper); //添加此处3
System.out.println(account); //添加此处4
}
}
三、总结
通过以上简单的步骤,我们就可以快速开始使用 Mybatis - flex 进行数据库操作了。它提供了简洁的 API 和注解驱动的开发方式,让我们可以更加高效地与数据库交互。当然,Mybatis - flex 还有很多高级特性,如多表关联查询、动态 SQL 等,我们将在后续的博客中继续探讨。