快速搭建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/