我有这个单身人士
import java.sql.*
import groovy.sql.Sql
import groovy.transform.*
import org.h2.jdbcx.JdbcConnectionPool
import groovy.util.logging.Log
@Singleton
@Log
class SqlPersistence {
@Lazy def templates = new SqlTemplateEngine()
@Lazy def sql = Sql.newInstance(
"jdbc:h2:bookRental",
"sa",
"sa",
"org.h2.Driver"
)
{
sql.execute(
'''
create table $booksTable (
id int primary key,
title varchar(100)
)
'''
)
sql.execute(
'''
create table $usersTable (
id int primary key,
name varchar(50),
surname varchar(50),
age int
)
'''
)
sql.execute(
'''
create table $rentalTable (
id int primary key,
userId int primary key,
foreign key(id) references $booksTable,
foreign key(userId) references $usersTable
)
'''
)
}
def findAll(table) {
log.info 'attempt to select all from $table'
sql.rows(templates.selectAll_template(table))
}
}
据我所知,我必须同步至少instance
方法,该方法用于获取对象的实例
def sql = SqlPersistence.instance
我想知道的是最好的方法是什么?覆盖getInstance
方法?还是有另一种方式?或者使用像GPars
这样的东西?