- All Superinterfaces:
AutoCloseable,Query
Unlike regular Query instances which are constructed lazily, a PreparedQuery is constructed
eagerly when Query.prepare() or QueryBuilder.prepare() is called. This enables:
- Batch operations -- Add multiple records via
addBatch(Data)and execute them in a single database round-trip withQuery.executeBatch(). - Generated keys -- Retrieve auto-generated primary keys after INSERT via
getGeneratedKeys(Class).
As PreparedQuery implements AutoCloseable, it must be closed after usage to release database
resources. Use it within a try-with-resources block:
var bindVars = orm.createBindVars();
try (var query = orm.query(RAW."""
INSERT INTO \{User.class}
VALUES \{bindVars}""").prepare()) {
users.forEach(query::addBatch);
query.executeBatch();
}
- See Also:
-
Method Summary
Methods inherited from interface st.orm.template.Query
executeBatch, executeUpdate, getOptionalResult, getOptionalResult, getRefList, getRefStream, getResultCount, getResultList, getResultList, getResultStream, getResultStream, getSingleResult, getSingleResult, isVersionAware, prepare, unsafe
-
Method Details
-
addBatch
Add a record to the batch.- Parameters:
record- the record to add to the batch.- Throws:
PersistenceException- if adding the batch fails, for instance when query has not specifiedBatchVars.
-
getGeneratedKeys
Returns a stream of generated keys as the result of an insert statement. Returns an empty stream if the insert statement did not generate any keys.The returned stream allows for lazy processing, meaning elements are generated only as they are consumed, optimizing resource usage. Note, however, that calling this method does trigger the execution of the underlying query, so it should only be invoked when the query is intended to run. Since the stream holds resources open while in use, it must be closed after usage to prevent resource leaks. As the stream is AutoCloseable, it is recommended to use it within a try-with-resources block.
- Type Parameters:
ID- the type of generated keys- Parameters:
type- the class of the keys- Returns:
- a stream of generated keys resulting from an insert statement; returns an empty stream if no keys are generated.
- Throws:
PersistenceException- if the statement fails
-
close
void close()Close the resources associated with this query.- Specified by:
closein interfaceAutoCloseable- Throws:
PersistenceException- if the resource cannot be closed.
-