项目搭建
填写基本信息点击下一步
勾选相对应的依赖
点击创建
配置pom.xml
缺啥补啥
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
打开此文件(此文件需要改后缀,把后缀改成yml)
粘贴此代码
# DataSource Config
spring:
datasource:
url: jdbc:mysql://localhost:3306/数据库名称
username: 你的数据库名称
password: 你的数据库密码
数据库创建
建库建表
添加数据
测试
创建两个包,和相关文件
package com.waisang.mybatisflex.entity;
import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.annotation.Table;
import lombok.Data;
@Data
@Table("user")// 你自己的表名
public class Account {
// id自增
@Id(keyType = KeyType.Auto)
// 与数据库字段相对应
private int id;
private String user_name;
private String number;
}
import com.mybatisflex.core.BaseMapper;
import com.waisang.mybatisflex.entity.Account;
public interface AccountMapper extends BaseMapper<Account> {
}
主类需要有
@MapperScan("com.waisang.mybatisflex.mapper")
用来扫描映射的mapper
package com.waisang.mybatisflex;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.waisang.mybatisflex.mapper")
public class MybatisFlexApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisFlexApplication.class, args);
}
}
来到测试类
代码如下
package com.waisang.mybatisflex;
import com.mybatisflex.core.query.QueryWrapper;
import com.waisang.mybatisflex.entity.Account;
import com.waisang.mybatisflex.mapper.AccountMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static com.waisang.mybatisflex.entity.table.AccountTableDef.ACCOUNT;
@SpringBootTest
class MybatisFlexApplicationTests {
// 生命变量
@Autowired
private AccountMapper accountMapper;
@Test
void contextLoads() {
List<Account> accounts = accountMapper.selectAll();
accounts.forEach(System.out::println);
}
}
然后点此运行即可查询数据库表的所有信息
运行结果
条件查询
注意这个ID是我数据库要查的字段名,查询条件是ID=1的数据
查询结果