All Downloads are FREE. Search and download functionalities are using the official Maven repository.

nz.net.osnz.common.hibernate.SqlService.groovy Maven / Gradle / Ivy

package nz.net.osnz.common.hibernate

import groovy.sql.Sql
import org.hibernate.Session
import org.hibernate.SessionFactory
import org.hibernate.internal.SessionImpl
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import javax.inject.Inject
import java.sql.Connection
import java.sql.Statement

/**
 * @author Kefeng Deng ([email protected])
 */
public class SqlService {

	private static final Logger LOG = LoggerFactory.getLogger(SqlService)

	@Inject
	SessionFactory sessionFactory

	public String oracleClobToString(clob) {
		return clob.stringValue()
	}

	public void executeSql(String sql) {
		process(openSession()) { Connection connection ->
			Statement s = null
			try {
				s = connection.createStatement()
				s.executeUpdate(sql)
			} catch (Exception ex) {
				LOG.warn("Unable to process ${sql}", ex)
			} finally {
				if (s) s.close()
			}
		}
	}

	public void paramSql(String sql, List params, Closure c) {
		process(openSession()) { Connection connection ->
			Sql q = null
			try {
				q = new Sql(connection)
				q.eachRow(sql, params, c)
			} catch (Exception ex) {
				LOG.warn("Unable to process ${sql}", ex)
			} finally {
				if (q) q.close()
			}
		}
	}

	/**
	 * Perform the passing closure
	 */
	protected void process(Session session, Closure c) {
		Connection connection = ((SessionImpl) session).connection()
		try {
			c(connection)
		} finally {
			if (connection) {
				connection.close()
			}
			if (session) {
				session.close()
			}
		}
	}

	/**
	 * @return a new connection session
	 */
	protected Session openSession() {
		return sessionFactory.openSession()
	}

}