JDBC 查询

如果需要,我们可以获取 JDBC 连接并使用原始 JDBC。

请注意,在实践中,这种情况很少见,在最近的应用程序中发生率低于 1%。如果需要,我们可以使用原始 JDBC,但大多数应用程序不需要降至原始 JDBC 级别。

try (Transaction transaction = DB.beginTransaction()) {

  // obtain the JDBC connection from the transaction
  final Connection connection = transaction.getConnection();

  // use PreparedStatement etc
  String sql = "select id, name from customer where name like ?";
  try (PreparedStatement stmt = connection.prepareStatement(sql)) {
   stmt.setString(1, "Rob");
    try (ResultSet rset = stmt.executeQuery()) {
      while (rset.next()) {
        final long id = rset.getLong(1);
        final String name = rset.getString(2);
        ...
      }
    }
  }

  transaction.commit();
}
DB.beginTransaction().use { transaction ->

  // obtain the JDBC connection from the transaction
  val connection = transaction.connection

  // use PreparedStatement etc
  val sql = "select id, name from customer where name like ?"
  connection.prepareStatement(sql).use { stmt ->

    stmt.setString(1, "Rob")
    stmt.executeQuery().use { rset ->
      while (rset.next()) {
        val id = rset.getLong(1)
        val name = rset.getString(2)
        ...
      }
    }
  }

  transaction.commit()
}