当前位置: 动力学知识库 > 问答 > 编程问答 >

groovy synchronizing singleton that holds sql instance

问题描述:

I've got this singleton

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))

}

}

As far as I understand I have to synchronize at least instance method, which is used to get the instance of the object

def sql = SqlPersistence.instance

What I'd like to know is what is the best way doing it? Override getInstance method? Or there is another way? Or maybe using something like GPars?

分享给朋友:
您可能感兴趣的文章:
随机阅读: