feat: refactor database

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
2022-05-11 10:54:44 +08:00
parent 4ee8fc9a20
commit 47413c6766
5 changed files with 87 additions and 37 deletions

View File

@@ -1,32 +1,12 @@
import { JSClass } from '@ccms/container'
import { Model } from './model'
import { database } from '@ccms/api'
import { JSClass, postConstruct } from '@ccms/container'
/**
* 数据库配置
*/
export interface DataBaseConfig {
/**
* 数据库连接串
*/
url: string | javax.sql.DataSource
/**
* 数据库驱动
*/
driverClassName?: string
/**
* 用户名
*/
username?: string
/**
* 密码
*/
password?: string
}
const Properties = Java.type('java.util.Properties')
/**
* 数据库封装类
*/
export class DataBase {
export class DataBase extends database.DataBase {
private dataSource: javax.sql.DataSource
private jdbcTemplate: org.springframework.jdbc.core.JdbcTemplate
@@ -37,13 +17,13 @@ export class DataBase {
@JSClass('org.springframework.jdbc.core.JdbcTemplate')
private JdbcTemplate: typeof org.springframework.jdbc.core.JdbcTemplate
constructor(dbConfig: DataBaseConfig) {
constructor(dbConfig: database.DataBaseConfig) {
super()
if (!dbConfig.url) { throw new Error('DataBase url can\'t be null!') }
this.createDataSource(dbConfig)
this.initialize()
}
private createDataSource(dbConfig: DataBaseConfig) {
private createDataSource(dbConfig: database.DataBaseConfig) {
if (typeof dbConfig.url === "string") {
let config = new this.HikariConfig()
if (dbConfig.driverClassName) {
@@ -56,12 +36,20 @@ export class DataBase {
config.setPassword(dbConfig.password)
}
config.setJdbcUrl(dbConfig.url)
if (dbConfig.properties) {
let properties = new Properties()
for (const key in dbConfig.properties) {
properties.setProperty(key, dbConfig.properties[key])
}
config.setDataSourceProperties(properties)
}
this.dataSource = new this.HikariDataSource(config)
} else {
this.dataSource = dbConfig.url
}
}
@postConstruct()
private initialize() {
this.jdbcTemplate = new this.JdbcTemplate(this.dataSource)
}
@@ -69,6 +57,7 @@ export class DataBase {
/**
* 执行SQL查询
* @param sql SQL语句
* @param args 参数
*/
query<T>(sql: string, ...args: any[]): Array<T> {
let startTime = Date.now()
@@ -80,6 +69,7 @@ export class DataBase {
/**
* 执行SQL更新
* @param sql SQL语句
* @param args 参数
*/
update(sql: string, ...args: any[]): number {
let startTime = Date.now()
@@ -88,6 +78,16 @@ export class DataBase {
return result
}
/**
* 执行SQL语句
* @param sql SQL语句
*/
execute(sql: string): void {
let startTime = Date.now()
this.jdbcTemplate.execute(sql)
console.debug(java.lang.String.format(`\n[DB] execute \nSQL : sql} \nCOST : ${Date.now() - startTime}ms`))
}
close() {
//@ts-ignore
this.dataSource.close()