快速搭建Mybatis-plus应用
网上很多Mybatis-plus教程都是基于Spring框架的,有时我们写个小控制台实验程序十分不方便,由于平时我写Java控制台程序一般都用maven-archetype-quickstart原型创建,所以就尝试着把Mybatis-plus整合到Java控制台应用里,在这里先把整合的过程记录下来。
1. 使用Maven原型创建项目
我使用的IDE是IDEA社区版,新建Project项目后选择Maven原型创建工程,这里选择maven-archetype-quickstart,如图所示:
创建好后,就可以使用啦。
2. 添加依赖包
这里添加一些依赖的Java类库包
- snakeyaml 加载读取yaml配置文件用的
- spring-jdbc spring框架中的对原始 Jdbc API 对象的简单封装库
- lombok 懒人利器,用注解生成很多"砖"用的
- mysql-connector-java mysql的Java驱动
- mybatis-plus ORM框架
<!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.26</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.1</version>
</dependency>
3. yaml配置文件使用
接下来就是写应用的配置文件了,配置文件采用yaml格式,用snakeyaml库来读取。
- 配置文件 application.yaml
# DataSource Config
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://xxxx.xxx:3306/mylearnlab?characterEncoding=utf8&useSSL=false
username: xxxx
password: xxxxx
- 读取配置文件
因为没有Spring框架了,所以我们需要自己手工读取配置文件。我找了个别人封装好的帮助类,还挺好用的,顺便在这里分享了。
public class YamlReader {
private static Map<String, Map<String, Object>> properties;
private YamlReader() {
if (SingletonHolder.instance != null) {
throw new IllegalStateException();
}
}
/**
* use static inner class achieve singleton
*/
private static class SingletonHolder {
private static YamlReader instance = new YamlReader();
}
public static YamlReader getInstance() {
return SingletonHolder.instance;
}
//init property when class is loaded
static {
InputStream in = null;
try {
properties = new HashMap<>();
Yaml yaml = new Yaml();
in = YamlReader.class.getClassLoader().getResourceAsStream("application.yaml");
properties = yaml.loadAs(in, HashMap.class);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* get yaml property
*
* @param key
* @return
*/
public Object getValueByKey(String root, String key) {
Map<String, Object> rootProperty = properties.get(root);
return rootProperty.getOrDefault(key, "");
}
}
使用也很方便,下面就是使用方法。
String jdbcUrl = String.valueOf(YamlReader.getInstance().getValueByKey("datasource", "url"));
String jdbcUserName = String.valueOf(YamlReader.getInstance().getValueByKey("datasource", "username"));
String jdbcPassword = String.valueOf(YamlReader.getInstance().getValueByKey("datasource", "password"));
4. 使用 mybatis-plus
下面进入正题,还是照着官方文档上的老规矩,先创建 Entity 实体类,之后创建 Mapper接口类,然后在Main入口方法里使用就可以了。由于没有了Spring框架为我们自动处理一些事情,所以我们就要在Main方法里自己手动处理一些以前自动装配的代码。
- entity 实体类
@Data
@TableName(value = "tb_user")
public class TbUser {
@TableId("id")
private int id;
@TableField("name")
private String name;
@TableField("age")
private int age;
@TableField("roleId")
private int roleId;
}
- mapper 接口类
public interface TbUserMapper extends BaseMapper<TbUser> {
}
- Main 方法使用
步骤包括:初始化数据源,构建数据库连接会话对象,执行查询语句等。
// 数据库连接会话工厂全局对象
private static SqlSessionFactory sqlSessionFactory = initSqlSessionFactory();
public static void main( String[] args )
{
try (SqlSession session = sqlSessionFactory.openSession(true)) {
TbUserMapper userMapper = session.getMapper(TbUserMapper.class);
List<TbUser> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
}
// 初始化构建MybatisSqlSession会话配置
public static SqlSessionFactory initSqlSessionFactory() {
DataSource dataSource = dataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("mylearnlab", transactionFactory, dataSource);
MybatisConfiguration configuration = new MybatisConfiguration(environment);
configuration.addMapper(TbUserMapper.class);
configuration.setLogImpl(StdOutImpl.class);
return new MybatisSqlSessionFactoryBuilder().build(configuration);
}
// 初始化数据源
public static DataSource dataSource() {
String jdbcUrl = String.valueOf(YamlReader.getInstance().getValueByKey("datasource", "url"));
String jdbcUserName = String.valueOf(YamlReader.getInstance().getValueByKey("datasource", "username"));
String jdbcPassword = String.valueOf(YamlReader.getInstance().getValueByKey("datasource", "password"));
SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
dataSource.setDriverClass(com.mysql.jdbc.Driver.class);
dataSource.setUrl(jdbcUrl);
dataSource.setUsername(jdbcUserName);
dataSource.setPassword(jdbcPassword);
return dataSource;
}
- 查询结果截图
5. 相关文档链接
- Mybatis-Plus 中文文档 https://baomidou.gitee.io/mybatis-plus-doc/#/
- mybatis.Plus 官方中文站 https://mybatis.plus/