Guest User

Untitled

a guest
Jul 18th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. @CordaService
  2. open class DatabaseService(private val services: ServiceHub) : SingletonSerializeAsToken() {
  3.  
  4. companion object {
  5. val log = loggerFor<DatabaseService>()
  6. }
  7.  
  8. /**
  9. * Executes a database update.
  10. *
  11. * @param query The query string with blanks for the parameters.
  12. * @param params The parameters to fill the blanks in the query string.
  13. */
  14. protected fun executeUpdate(query: String, params: Map<Int, Any>) {
  15. val preparedStatement = prepareStatement(query, params)
  16.  
  17. try {
  18. preparedStatement.executeUpdate()
  19. } catch (e: SQLException) {
  20. log.error(e.message)
  21. throw e
  22. } finally {
  23. preparedStatement.close()
  24. }
  25. }
  26.  
  27. /**
  28. * Executes a database query.
  29. *
  30. * @param query The query string with blanks for the parameters.
  31. * @param params The parameters to fill the blanks in the query string.
  32. * @param transformer A function for processing the query's ResultSet.
  33. *
  34. * @return The list of transformed query results.
  35. */
  36. protected fun <T : Any> executeQuery(
  37. query: String,
  38. params: Map<Int, Any>,
  39. transformer: (ResultSet) -> T
  40. ): List<T> {
  41. val preparedStatement = prepareStatement(query, params)
  42. val results = mutableListOf<T>()
  43.  
  44. return try {
  45. val resultSet = preparedStatement.executeQuery()
  46. while (resultSet.next()) {
  47. results.add(transformer(resultSet))
  48. }
  49. results
  50. } catch (e: SQLException) {
  51. log.error(e.message)
  52. throw e
  53. } finally {
  54. preparedStatement.close()
  55. }
  56. }
  57.  
  58. /**
  59. * Creates a PreparedStatement - a precompiled SQL statement to be
  60. * executed against the database.
  61. *
  62. * @param query The query string with blanks for the parameters.
  63. * @param params The parameters to fill the blanks in the query string.
  64. *
  65. * @return The query string and params compiled into a PreparedStatement
  66. */
  67. private fun prepareStatement(query: String, params: Map<Int, Any>): PreparedStatement {
  68. val session = services.jdbcSession()
  69. val preparedStatement = session.prepareStatement(query)
  70.  
  71. params.forEach { (key, value) ->
  72. when (value) {
  73. is String -> preparedStatement.setString(key, value)
  74. is Int -> preparedStatement.setInt(key, value)
  75. is Long -> preparedStatement.setLong(key, value)
  76. else -> throw IllegalArgumentException("Unsupported type.")
  77. }
  78. }
  79.  
  80. return preparedStatement
  81. }
  82. }
Add Comment
Please, Sign In to add comment