Core Concepts
ResultSet Mapping
When you execute a SQL query, Pyranid will walk each row in the java.sql.ResultSet and ask your ResultSetMapper to provide an object representation of that row.
@FunctionalInterface
public interface ResultSetMapper {
// T is the type to which we're mapping this row.
@NonNull
public <T> Optional<T> map(
@NonNull StatementContext<T> statementContext,
@NonNull ResultSet resultSet,
@NonNull Class<T> resultSetRowType,
@NonNull InstanceProvider instanceProvider
) throws SQLException;
}
@FunctionalInterface
public interface ResultSetMapper {
// T is the type to which we're mapping this row.
@NonNull
public <T> Optional<T> map(
@NonNull StatementContext<T> statementContext,
@NonNull ResultSet resultSet,
@NonNull Class<T> resultSetRowType,
@NonNull InstanceProvider instanceProvider
) throws SQLException;
}
The ResultSetMapper is given an InstanceProvider so it can create an object to hold the row's data. It's the mapper's job to copy the row's data into that object and return it.
Return Optional.empty() to represent a mapped SQL NULL; a mapper itself must not return null.
The out-of-the-box implementation supports mapping common JDK types as well as your JavaBeans and Record types, and generally "just works" as you would expect.
For native SQL intervals, use SqlInterval (see SQL Intervals). Duration, Period and MonthDay have no built-in scalar conversion. Register a CustomColumnMapper for the representation your query returns; the unsupported single-column error points to that extension. For PostgreSQL fixed elapsed intervals, see the constrained Duration recipe.
Calling planCachingEnabled(false) disables mapping-plan caching without changing conversion behavior. Caching never retains row values or live JDBC resources. Custom mappers run in registration order for each non-null value; a handled-null result is distinct from fallback.
If you need to customize mapping behavior, you might bring your own list of CustomColumnMapper...
// CustomColumnMappers supply "surgical" overrides to handle custom types.
// If multiple mappers apply, Pyranid tries them in list order.
// Normalization locale should match the language of your database tables/column names.
// Plan caching (on by default) trades memory for faster mapping of wide ResultSets
ResultSetMapper resultSetMapper = ResultSetMapper.withCustomColumnMappers(List.of(...))
.normalizationLocale(Locale.forLanguageTag("pt-BR"))
.planCachingEnabled(false)
.build();
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(resultSetMapper)
.build();
// CustomColumnMappers supply "surgical" overrides to handle custom types.
// If multiple mappers apply, Pyranid tries them in list order.
// Normalization locale should match the language of your database tables/column names.
// Plan caching (on by default) trades memory for faster mapping of wide ResultSets
ResultSetMapper resultSetMapper = ResultSetMapper.withCustomColumnMappers(List.of(...))
.normalizationLocale(Locale.forLanguageTag("pt-BR"))
.planCachingEnabled(false)
.build();
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(resultSetMapper)
.build();
...or you might choose to directly implement the ResultSetMapper interface for fine-grained control:
ResultSetMapper resultSetMapper = new ResultSetMapper() {
@Override
@NonNull
public <T> Optional<T> map(
@NonNull StatementContext<T> statementContext,
@NonNull ResultSet resultSet,
@NonNull Class<T> resultSetRowType,
@NonNull InstanceProvider instanceProvider
) throws SQLException {
// Do your mapping here
return Optional.empty();
}
};
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(resultSetMapper)
.build();
ResultSetMapper resultSetMapper = new ResultSetMapper() {
@Override
@NonNull
public <T> Optional<T> map(
@NonNull StatementContext<T> statementContext,
@NonNull ResultSet resultSet,
@NonNull Class<T> resultSetRowType,
@NonNull InstanceProvider instanceProvider
) throws SQLException {
// Do your mapping here
return Optional.empty();
}
};
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(resultSetMapper)
.build();
Standard Types
When querying for a single column, e.g. a SQL COUNT, it's often useful to map to a standard type like String, Integer, or Boolean.
Boolean result targets use the same conversion rule for scalar results, record components, JavaBean properties, and typed array/list elements. Text accepts case-insensitive true/false, yes/no, on/off, and 1/0, with surrounding whitespace ignored. Unambiguous word prefixes are also accepted, following PostgreSQL's Boolean aliases: for example, tr, y, and of; o is ambiguous and rejected. Invalid text raises DatabaseException instead of silently becoming false. Native Boolean values and numeric zero/nonzero conversion retain their existing behavior: numeric 2 is true, while text "2" is invalid. Use a custom mapper for other conventions; custom mappers and native Object/map results still receive the original JDBC values.
Floating-point targets preserve native JDBC Float/Double NaN, positive/negative infinity and signed zero across scalar, row and typed-container results. A finite source that overflows the requested floating type still fails; ordinary floating-point precision rounding is unchanged. Integer conversions retain their exactness checks, and vector text literals still require finite elements.
There's no need to create a custom "row" type to hold the result.
// Returns Optional<Long>, which we immediately unwrap because COUNT(*) is never null
Long count = database.query("SELECT COUNT(*) FROM car")
.fetchObject(Long.class)
.orElseThrow();
// Standard primitives and JDK types are supported by default
Optional<UUID> id = database.query("SELECT id FROM employee LIMIT 1")
.fetchObject(UUID.class);
// Lists work as you would expect
List<String> names = database.query("SELECT name FROM employee")
.fetchList(String.class);
// Returns Optional<Long>, which we immediately unwrap because COUNT(*) is never null
Long count = database.query("SELECT COUNT(*) FROM car")
.fetchObject(Long.class)
.orElseThrow();
// Standard primitives and JDK types are supported by default
Optional<UUID> id = database.query("SELECT id FROM employee LIMIT 1")
.fetchObject(UUID.class);
// Lists work as you would expect
List<String> names = database.query("SELECT name FROM employee")
.fetchList(String.class);
Large Object Values
The default mapper converts SQL CLOB and NCLOB values to String, and BLOB values to byte[], for both scalar results and matching bean properties or record components. Materialized values are detached from the JDBC cursor. When aliases map one source LOB to multiple compatible properties, Pyranid reads it once and shares the detached value.
public record Document(String body, byte[] attachment) {}
Document document = database.query("SELECT body, attachment FROM document WHERE id = :id")
.bind("id", 123)
.fetchObject(Document.class)
.orElseThrow();
public record Document(String body, byte[] attachment) {}
Document document = database.query("SELECT body, attachment FROM document WHERE id = :id")
.bind("id", 123)
.fetchObject(Document.class)
.orElseThrow();
Built-in materialization is limited to 16 MiB per binary LOB and 8,388,608 UTF-16 code units per character LOB by default. Exceeding a limit raises DatabaseException. Configure larger limits when your application needs to read larger values:
ResultSetMapper mapper = ResultSetMapper.withPlanCachingEnabled(true)
.maxLobBytes(64L * 1024 * 1024)
.maxLobCharacters(32L * 1024 * 1024)
.build();
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(mapper)
.build();
ResultSetMapper mapper = ResultSetMapper.withPlanCachingEnabled(true)
.maxLobBytes(64L * 1024 * 1024)
.maxLobCharacters(32L * 1024 * 1024)
.build();
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(mapper)
.build();
Both maxLobBytes(...) and maxLobCharacters(...) require a positive Long. The unboundedLobMaterialization() method explicitly disables both limits; a later finite setter re-enables its own limit independently. Java array/string size limits still apply. These limits cover Pyranid's built-in LOB materialization, including supported nested typed values. They do not limit ordinary VARCHAR or binary columns, driver buffering, custom mapper allocations, or the combined size of a result list. Already detached driver values are checked before acceptance, but the driver has already allocated their storage.
Other scalar LOB conversions retain the JDBC driver's getter behavior, such as DuckDB BLOB-to-String. These cross-type driver conversions are outside the built-in BLOB-to-byte[] and CLOB/NCLOB-to-String limits.
To return detached LOB values from native Map/Object results and Object-valued properties, opt in explicitly:
ResultSetMapper mapper = ResultSetMapper.withPlanCachingEnabled(true)
.detachLobValues(true)
.maxLobBytes(16L * 1024 * 1024)
.maxLobCharacters(8L * 1024 * 1024)
.build();
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(mapper)
.build();
Map<String, Object> document = database.query("SELECT body, attachment FROM document WHERE id = :id")
.bind("id", 123)
.fetchObject(Query.mapRowType())
.orElseThrow();
ResultSetMapper mapper = ResultSetMapper.withPlanCachingEnabled(true)
.detachLobValues(true)
.maxLobBytes(16L * 1024 * 1024)
.maxLobCharacters(8L * 1024 * 1024)
.build();
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(mapper)
.build();
Map<String, Object> document = database.query("SELECT body, attachment FROM document WHERE id = :id")
.bind("id", 123)
.fetchObject(Query.mapRowType())
.orElseThrow();
The default is false. When enabled, visible Blob values become byte[], and Clob/NClob/SQLXML values become String, including nested native Java maps, collections and arrays. Known LOB metadata also checks already detached driver values against the corresponding bound. Native containers are copied without mutating driver values; repeated references and cycles are retained within the copied graph. Arrays whose LOB elements change type may widen to Object[]; primitive and compatible native scalar array types are retained. Converted map-key/set-element collisions fail rather than losing entries.
This option does not invent an attribute model for an opaque scalar JDBC Struct/Array. Dialect-normalized containers expose their visible contents, but explicit JDBC-handle targets and handled custom mapper outputs remain borrowed. Custom hooks receive their original inputs; a fallback can request built-in detachment while retaining the input handle's borrowed ownership. SQLXML uses the character bound; if only getString() is supported, the bound is checked after that driver allocation. The existing limits do not bound aggregate result size or all driver allocations.
Custom column mappers run before built-in LOB conversion and may handle the value themselves, return a mapped null, or request fallback. Pyranid closes readers and streams it opens and frees LOB handles it exclusively owns after all row bindings finish. A handle exposed to a custom mapper is treated as borrowed, even when that mapper returns fallback, because the mapper could retain it. With detachLobValues disabled, raw Object, map, and JDBC-handle results retain their native/dialect behavior and cursor-lifetime constraints; do not assume a raw handle remains usable after the statement closes. A query stream does not extend the lifetime of a raw handle beyond its cursor.
LOB handles returned by custom mappers, including nested mappings, remain borrowed. Copy their contents into detached values when results must outlive the cursor. Custom Iterable and Map outputs are left untouched; keep any JDBC handles they contain within the cursor's lifetime. Do not rely on Pyranid to discover or free handles hidden inside application objects.
User-defined Types
The standard mapper matches result-column labels to writable JavaBean properties and record components. Bean property names come from public setters using JavaBeans capitalization; the mapper invokes setters rather than writing fields directly. @DatabaseColumn on a bean field supplies additional aliases for the associated property, while a record-component annotation supplies aliases for that component.
JavaBean and Record mapping require at least one selected column to match a writable property or record component. If no selected columns match, Pyranid raises a DatabaseException instead of returning an object with all default values. Use column aliases or a custom ResultSetMapper when the default property matching is not appropriate.
After that one-match minimum, matching is otherwise partial: Pyranid does not require every writable JavaBean property or Record component to have a selected column. Pyranid supplies null for an unmatched reference-type Record component; an unmatched primitive Record component raises a DatabaseException. For an unmatched JavaBean property, Pyranid does not invoke its setter, so the instance supplied by the InstanceProvider keeps its current value, including constructor or field-initializer values and primitive defaults such as 0 or false.
Opt into unmatched source-column detection when a projection should consume every selected column:
ResultSetMapper mapper = ResultSetMapper.withPlanCachingEnabled(true)
.failOnUnmappedColumns(true)
.build();
ResultSetMapper mapper = ResultSetMapper.withPlanCachingEnabled(true)
.failOnUnmappedColumns(true)
.build();
The default is false. With strict mode enabled, a row target record Account(Long accountId) {} accepts SELECT account_id, but SELECT account_id, display_name fails because display_name has no mapped property. Validation happens while building the standard row plan, before built-in row binding reads values. Empty results do not invoke the row mapper and are not schema-validated by this option. Alias matching and one-column fan-out still work. Missing target members retain the existing partial-mapping rules; this option does not require every member to be selected. Scalars, whole-row Map targets, handled whole-row custom mappings and the eligible direct single-STRUCT record fallback keep their own mapping contracts. A custom mapper attempt can read its input before built-in planning begins.
The built-in mapper does not support selected target shapes containing Optional<T> in their declared types, including nested typed containers or generic records. Without a whole-shape custom mapper, these targets fail during planning even when the selected SQL value is NULL. Direct Optional-valued properties always fail during planning. Use nullable underlying value types or a custom ResultSetMapper that defines the wrapper/null behavior. Unselected top-level members retain the existing partial-mapping defaults.
A CustomColumnMapper may manually construct a complete row or a non-Optional container/record containing Optional values. If it declines a non-null value, built-in fallback still rejects the unsupported target shape. Column callbacks are skipped for SQL NULL: a nullable outer container/record remains null, and a directly mapped Optional property cannot receive Optional.empty() through this hook.
An omitted column differs from a selected column containing SQL NULL. A selected NULL is mapped as null for reference targets - including invoking a JavaBean setter with null - and raises a DatabaseException for a primitive target. Prefer a projection type whose members match the selected columns, or provide a custom ResultSetMapper, when your application requires every target member to be populated.
The default InstanceProvider uses public constructors and the standard mapper uses public JavaBean accessors. Define mapped beans, records, constructors, getters, and setters as public. Your own InstanceProvider can instantiate an intentionally non-public record. Mapping a non-public JavaBean generally requires a custom ResultSetMapper, because the standard mapper invokes the bean's setters itself.
Run A Bean Hook After Mapping
Wrap a separately constructed default mapper when a bean needs validation or derived fields after all selected setters have run. A generic map method needs an anonymous implementation rather than a lambda:
public interface AfterMapping {
void afterMapping();
}
ResultSetMapper defaults = ResultSetMapper.withDefaultConfiguration();
ResultSetMapper hooks = new ResultSetMapper() {
@Override public <T> Optional<T> map(StatementContext<T> context, ResultSet rows,
Class<T> type, InstanceProvider provider) throws SQLException {
Optional<T> mapped = defaults.map(context, rows, type, provider);
mapped.ifPresent(value -> {
if (value instanceof AfterMapping hook) hook.afterMapping();
});
return mapped;
}
};
public interface AfterMapping {
void afterMapping();
}
ResultSetMapper defaults = ResultSetMapper.withDefaultConfiguration();
ResultSetMapper hooks = new ResultSetMapper() {
@Override public <T> Optional<T> map(StatementContext<T> context, ResultSet rows,
Class<T> type, InstanceProvider provider) throws SQLException {
Optional<T> mapped = defaults.map(context, rows, type, provider);
mapped.ifPresent(value -> {
if (value instanceof AfterMapping hook) hook.afterMapping();
});
return mapped;
}
};
Install hooks with Database.Builder.resultSetMapper(...) or query.resultSetMapper(...). The hook runs once per mapped row, including list and stream rows; empty results and SQL-null scalar values have no object to visit. Delegate to the captured mapper rather than calling the Database's configured mapper, which could recurse into this wrapper. Build that delegate with any desired custom column mappers or strict-column settings.
Keep the hook local to the mapped value. If it throws and the failure escapes a transaction callback, earlier transactional writes roll back. Retrying a transaction can run the hook again, so external side effects need their own retry-safe design.
Inject Record Construction Values
Records have no setters. Override InstanceProvider.provideRecord to supply an application-owned dependency while preserving the mapped constructor arguments. This example reserves the second component for injection rather than selecting it from SQL:
public record ContactRow(String name, ContactService service) {}
InstanceProvider instances = new InstanceProvider() {
@Override public <T extends Record> T provideRecord(StatementContext<T> context,
Class<T> type, Object... arguments) {
if (type == ContactRow.class) {
arguments = arguments.clone();
arguments[1] = contactService;
}
return InstanceProvider.super.provideRecord(context, type, arguments);
}
};
Database configured = Database.with(dataSource, databaseType)
.instanceProvider(instances).build();
ContactRow contact = configured.query("SELECT name FROM contact WHERE id=:id")
.bind("id", 42).fetchObject(ContactRow.class).orElseThrow();
public record ContactRow(String name, ContactService service) {}
InstanceProvider instances = new InstanceProvider() {
@Override public <T extends Record> T provideRecord(StatementContext<T> context,
Class<T> type, Object... arguments) {
if (type == ContactRow.class) {
arguments = arguments.clone();
arguments[1] = contactService;
}
return InstanceProvider.super.provideRecord(context, type, arguments);
}
};
Database configured = Database.with(dataSource, databaseType)
.instanceProvider(instances).build();
ContactRow contact = configured.query("SELECT name FROM contact WHERE id=:id")
.bind("id", 42).fetchObject(ContactRow.class).orElseThrow();
ContactService, contactService, the data source and database type belong to the application. This provider must be thread-safe. The default mapper converts selected columns before calling it; absent reference components are null. Restrict injection to known record types and keep the component positions aligned with their declarations. This hook constructs top-level row records; nested STRUCT records use their own canonical constructors.
Construct An Intentionally Private Record
Use an application lookup only for the record types you explicitly allow. In this example the private record and provider live in the same application class:
private record PrivateContact(String name) {}
static InstanceProvider privateRecords() {
return new InstanceProvider() {
@Override public <T extends Record> T provideRecord(StatementContext<T> context,
Class<T> type, Object... arguments) {
if (type != PrivateContact.class) {
return InstanceProvider.super.provideRecord(context, type, arguments);
}
try {
Class<?>[] parameters = Arrays.stream(type.getRecordComponents())
.map(component -> component.getType()).toArray(Class<?>[]::new);
var lookup = MethodHandles.privateLookupIn(type, MethodHandles.lookup());
return type.cast(lookup.findConstructor(type,
MethodType.methodType(void.class, parameters)).invokeWithArguments(arguments));
} catch (RuntimeException | Error failure) {
throw failure;
} catch (Throwable failure) {
throw new IllegalStateException("Cannot construct " + type.getName(), failure);
}
}
};
}
private record PrivateContact(String name) {}
static InstanceProvider privateRecords() {
return new InstanceProvider() {
@Override public <T extends Record> T provideRecord(StatementContext<T> context,
Class<T> type, Object... arguments) {
if (type != PrivateContact.class) {
return InstanceProvider.super.provideRecord(context, type, arguments);
}
try {
Class<?>[] parameters = Arrays.stream(type.getRecordComponents())
.map(component -> component.getType()).toArray(Class<?>[]::new);
var lookup = MethodHandles.privateLookupIn(type, MethodHandles.lookup());
return type.cast(lookup.findConstructor(type,
MethodType.methodType(void.class, parameters)).invokeWithArguments(arguments));
} catch (RuntimeException | Error failure) {
throw failure;
} catch (Throwable failure) {
throw new IllegalStateException("Cannot construct " + type.getName(), failure);
}
}
};
}
Import java.lang.invoke.MethodHandles and MethodType, plus java.util.Arrays. Configure the provider through Database.Builder.instanceProvider(...). The lookup has the application's access rights; it does not bypass module boundaries. Across named modules, the package may need to be opened and the lookup must have the required access. This recipe does not add a JPMS module descriptor to Pyranid. It also does not make private JavaBean setters accessible to the standard mapper.
Project Into Immutable Domain Classes
For immutable classes produced by hand, Lombok or Kotlin, map a public record projection and convert it explicitly. The domain class needs no no-argument constructor or writable setters:
public record ContactProjection(String name) {
DomainContact toDomain() { return new DomainContact(name.strip()); }
}
List<DomainContact> contacts = database.query("SELECT name FROM contact ORDER BY id")
.fetchList(ContactProjection.class).stream()
.map(ContactProjection::toDomain).toList();
public record ContactProjection(String name) {
DomainContact toDomain() { return new DomainContact(name.strip()); }
}
List<DomainContact> contacts = database.query("SELECT name FROM contact ORDER BY id")
.fetchList(ContactProjection.class).stream()
.map(ContactProjection::toDomain).toList();
The application defines DomainContact and its constructor. For large result sets, perform the conversion inside the fetchStream callback and consume it there rather than first building an intermediate list.
Match Properties And Generic Types
Inherited setter types resolve against the concrete fetched class. For class Account extends Entity<Long>, an inherited setId(ID) receives a converted Long rather than a raw JDBC Integer or String. Resolution follows superclass, interface and owner bindings and preserves nested collection and generic-array element types. Custom column mappers receive that resolved TargetType too.
A selected JavaBean property with unresolved type variables now raises a clear planning error. Fetch a concrete subclass that binds those variables, use an intentional Object/raw collection property, or provide a custom mapper. Generic properties without a matching selected column retain their existing values/defaults.
Default name candidates include the Java property spelling, conventional snake case, digit-to-word boundaries and acronym boundaries. For example, employeeId matches both employee_id and a quoted employeeId alias; sha256Hash, s3Key, ipv4Address and oauth2Token match sha256_hash, s3_key, ipv4_address and oauth2_token. URLValue and the JavaBeans property XCoordinate also match url_value and x_coordinate. Historical compact/acronym and digit-separated candidates remain supported.
Annotated fields follow the setter's property name even when the field spelling differs: @DatabaseColumn("stored_active") boolean isActive can identify setActive(boolean), and an annotated xCoordinate field can identify setXCoordinate(...). Only primitive boolean isX fields receive the boolean-prefix convention; boxed Boolean fields retain their normal property names. Unmatched, static or ambiguous annotated bean fields, and competing annotated fields for one property in the same class, raise a metadata error during standard mapping, even when their aliases are not selected. Provide an unambiguous public instance setter, correct the annotation, or use a custom result-set mapper. Record components do not require setters. The nearest annotated declaration supplies inherited aliases; an unannotated shadow does not erase an ancestor's annotation.
With default settings, matching remains partial after the existing one-match minimum. Aliases are additive, and existing fan-out and result-column assignment order are unchanged; newly recognized candidates can now populate properties that previously kept their defaults. Use a clear projection when multiple selected columns would match the same property. Ordinary named-column mapping still takes precedence over direct STRUCT mapping; give an outer STRUCT payload a distinct alias when its contents should form the whole record.
Name normalization first folds ASCII A–Z to a–z, then lowercases the whole label with normalizationLocale (default Locale.ROOT). This keeps ASCII identifiers such as ID/id stable under Turkish and Azerbaijani settings. The locale still affects non-ASCII letters; this two-pass identifier rule can differ from the previous locale-only treatment of mixed-language names. The same normalization is used for properties, aliases, Map keys, STRUCT attributes and duplicate-label detection.
For example:
public class Car {
private Long carId;
private Color color;
// For schema flexibility, Pyranid will match both "deposit_amount1" and "deposit_amount_1" column names
private BigDecimal depositAmount1;
// Use this annotation to specify variants if the field name doesn't match the column name
@DatabaseColumn({"systok", "sys_tok"})
private UUID systemToken;
public Long getCarId() { return this.carId; }
public void setCarId(Long carId) { this.carId = carId; }
public Color getColor() { return this.color; }
public void setColor(Color color) { this.color = color; }
public BigDecimal getDepositAmount1() { return this.depositAmount1; }
public void setDepositAmount1(BigDecimal depositAmount1) { this.depositAmount1 = depositAmount1; }
public UUID getSystemToken() { return this.systemToken; }
public void setSystemToken(UUID systemToken) { this.systemToken = systemToken; }
}
Car car = database.query("""
SELECT car_id, color, systok
FROM car
LIMIT 1
""")
.fetchObject(Car.class)
.orElseThrow();
// Output might be "Car ID is 123 and color is BLUE. Token is d73c523a-8344-44ef-819c-40467662d619"
out.printf("Car ID is %s and color is %s. Token is %s\n",
car.getCarId(), car.getColor(), car.getSystemToken());
// Column names will work with wildcard queries as well
car = database.query("""
SELECT *
FROM car
LIMIT 1
""")
.fetchObject(Car.class)
.orElseThrow();
// Column aliases work too
car = database.query("""
SELECT some_id AS car_id, some_color AS color
FROM car
LIMIT 1
""")
.fetchObject(Car.class)
.orElseThrow();
public class Car {
private Long carId;
private Color color;
// For schema flexibility, Pyranid will match both "deposit_amount1" and "deposit_amount_1" column names
private BigDecimal depositAmount1;
// Use this annotation to specify variants if the field name doesn't match the column name
@DatabaseColumn({"systok", "sys_tok"})
private UUID systemToken;
public Long getCarId() { return this.carId; }
public void setCarId(Long carId) { this.carId = carId; }
public Color getColor() { return this.color; }
public void setColor(Color color) { this.color = color; }
public BigDecimal getDepositAmount1() { return this.depositAmount1; }
public void setDepositAmount1(BigDecimal depositAmount1) { this.depositAmount1 = depositAmount1; }
public UUID getSystemToken() { return this.systemToken; }
public void setSystemToken(UUID systemToken) { this.systemToken = systemToken; }
}
Car car = database.query("""
SELECT car_id, color, systok
FROM car
LIMIT 1
""")
.fetchObject(Car.class)
.orElseThrow();
// Output might be "Car ID is 123 and color is BLUE. Token is d73c523a-8344-44ef-819c-40467662d619"
out.printf("Car ID is %s and color is %s. Token is %s\n",
car.getCarId(), car.getColor(), car.getSystemToken());
// Column names will work with wildcard queries as well
car = database.query("""
SELECT *
FROM car
LIMIT 1
""")
.fetchObject(Car.class)
.orElseThrow();
// Column aliases work too
car = database.query("""
SELECT some_id AS car_id, some_color AS color
FROM car
LIMIT 1
""")
.fetchObject(Car.class)
.orElseThrow();
Rows As Maps
When you don't want to define a type at all - exploratory queries, admin tooling, dynamic-shape SELECT *, exports - fetch rows as maps with Query::mapRowType():
List<Map<String, Object>> rows = database.query("SELECT * FROM car")
.fetchList(Query.mapRowType());
Object make = rows.get(0).get("make");
Optional<Map<String, Object>> row = database.query("""
SELECT *
FROM car
WHERE id = :id
""")
.bind("id", 123)
.fetchObject(Query.mapRowType());
List<Map<String, Object>> rows = database.query("SELECT * FROM car")
.fetchList(Query.mapRowType());
Object make = rows.get(0).get("make");
Optional<Map<String, Object>> row = database.query("""
SELECT *
FROM car
WHERE id = :id
""")
.bind("id", 123)
.fetchObject(Query.mapRowType());
Each row is an insertion-ordered LinkedHashMap in column order. Keys are normalized (lowercase) column labels, so lookups behave identically across databases regardless of whether the driver reports unquoted labels uppercased (Oracle, HSQLDB), lowercased (PostgreSQL), or as written (MySQL, SQL Server). AS aliases are respected (and lowercased); NULL columns are present with a null value; values use the same dialect-aware extraction as record/bean mapping. Duplicate column labels - e.g. an unaliased multi-table join - fail fast with a DatabaseException; use column aliases to disambiguate.
The raw Map.class and LinkedHashMap.class tokens are also accepted anywhere a result type token is accepted, but Java's type erasure means they produce raw result types:
List<Map> rows = database.query("SELECT * FROM car").fetchList(Map.class);
List<Map> rows = database.query("SELECT * FROM car").fetchList(Map.class);
The well-known JDK map tokens (HashMap.class, TreeMap.class, Hashtable.class, ConcurrentHashMap.class, and the SortedMap/NavigableMap/ConcurrentMap interfaces) are rejected with a clear error; other classes that happen to implement Map continue to map via the JavaBean path.
The special case lives in the default ResultSetMapper implementation only - a custom database-wide or per-query ResultSetMapper receiving the token decides for itself how to handle it.
Supported Primitives
Supported JDK Types
Enum<E>UUIDBigDecimalBigIntegerDateInstantLocalDateforDATELocalTimeforTIMELocalDateTimeforTIMESTAMPOffsetTimeforTIME WITH TIME ZONEOffsetDateTimeforTIMESTAMP WITH TIME ZONEZonedDateTimeforTIMESTAMPandTIMESTAMP WITH TIME ZONEYearfromINTEGER-like, string, orDATE-surfaced year columns (e.g. MySQLYEAR)YearMonthfrom ISO-8601 string columns (e.g.2027-12); expanded positive years emitted byYearMonth.toString()(for example10000-02) are readable alongside signed ISO formsjava.sql.Timestampjava.sql.DateZoneIdZoneOffsetTimeZoneLocale(IETF BCP 47 "language tag" format)Currency
Temporal result-set mapping uses JDBC ResultSetMetaData for the returned column. Zone-less TIMESTAMP values are wall-clock values; when mapping them to Instant, OffsetDateTime, ZonedDateTime, or Date, Pyranid interprets that wall clock in Database.Builder::timeZone(...). Mapping a zone-less TIMESTAMP to LocalDateTime keeps the wall clock unchanged. TIMESTAMP WITH TIME ZONE values already identify an instant; mapping to Instant preserves that instant, and mapping to ZonedDateTime represents it in the configured Database.Builder::timeZone(...).
Zoned timestamps mapped to LocalDate or java.sql.Date use the configured database time zone to choose the calendar date, consistently for scalar, record, and JavaBean results.
Zone-less timestamp text mapped to OffsetDateTime follows the same configured-zone resolution as Instant: a DST gap advances to a valid local time, and an overlap chooses the earlier offset. Explicit timestamp text offsets retain their offset and instant. A plain TIME or local-time string has no calendar date, so inferring an offset for OffsetTime requires a fixed-offset Database.timeZone such as UTC or ZoneOffset.of("+05:45"). Region zones with historical/DST changes fail clearly instead of borrowing a 1970 offset. Use LocalTime, an explicit-offset TIME value or a custom mapper when a calendar date is needed to choose an offset.
4.9 read migration: legacy temporal targets now fail for values they cannot represent safely, including PostgreSQL positive and negative infinity, rather than returning wrapped years or unusable legacy sentinels. java.sql.Date requires years 0001–9999 and an unchanged calendar-date round trip; dates normalized by the legacy calendar also fail. java.sql.Timestamp requires a lossless instant round trip within its millisecond range, retaining nanoseconds, while java.util.Date retains its existing millisecond precision and rejects overflow. These checks also apply within typed containers. For PostgreSQL infinity, use the matching java.time target: LocalDate for DATE, LocalDateTime for TIMESTAMP, or OffsetDateTime for TIMESTAMPTZ. These retain the driver's minimum/maximum sentinels; cross-type conversions remain subject to Java's calendar and zone bounds. Native Object results retain their driver representations, and row maps retain their existing column-reader values. Custom mappers keep their existing column-reader inputs, and handled custom results bypass the built-in range checks.
Explicit java.sql.Timestamp targets follow instant semantics on both read and write. A zone-less timestamp is interpreted in Database.timeZone before constructing the Timestamp; a zoned timestamp retains its instant. This applies to scalar, record, JavaBean and typed array results, with or without cached mapping plans, and prevents JVM-zone drift when a fetched value is bound again. Native Object/map values and inputs exposed to custom mappers retain the driver's representation. Use LocalDateTime when the desired result is the unchanged wall clock.
Explicit java.sql.Time targets retain the millisecond portion of the driver's local time, consistently across supported scalar and structured mapping paths. java.sql.Time cannot represent sub-millisecond precision; use LocalTime to retain finer fractions supplied by the driver.
SQLite TIMESTAMP text is parsed strictly and retains fractional seconds when the driver uses its default JDBC date string format. With that default configuration, explicit offsets are preserved for OffsetDateTime, and Instant preserves the instant they identify. Local date/time targets use the configured database time zone; text without an offset is interpreted in that zone. Explicit custom SQLite JDBC date string formats retain JDBC driver conversion semantics, including their validation and precision limits. Numeric timestamp storage also retains JDBC driver semantics.
Starting in 4.9, SQLite's built-in temporal writes use fixed fractional-width text. Earlier text remains readable, but reading it does not normalize storage. Rebinding a fetched pre-4.9 value can fail equality and optimistic-lock predicates. Mixed representations also affect joins, UNIQUE/ON CONFLICT, GROUP BY/DISTINCT, ordering and ranges. New instant-bearing writes convert to UTC and do not preserve the original offset; local timestamp columns remain wall-clock values. Choose the model for each column and use the tested SQLite timestamp migration recipe, preserving nanoseconds and checking logical duplicates before rewriting. No automatic data migration occurs.
Some JDBC drivers expose temporal columns as strings instead of JDBC temporal objects. For JavaBean and record mapping, Pyranid parses ISO-8601 strings and common JDBC timestamp strings such as 2020-01-02 03:04:05 when the target property or component is LocalDate, LocalTime, LocalDateTime, Instant, OffsetDateTime, or ZonedDateTime.
Pyranid preserves the fractional-second precision returned by your JDBC driver; it does not round or truncate Instant, OffsetDateTime, or ZonedDateTime values to milliseconds. The maximum precision is still determined by the database column and driver (for example, PostgreSQL timestamps are stored at microsecond precision).
Invalid TimeZone or Locale values in your resultset will raise a DatabaseException instead of silently falling back to defaults.
SQL Intervals
SqlInterval maps native interval columns into independent signed total months, calendar days and a Duration time part. Scalar fetches return the existing outer Optional; nullable record components and bean properties use SqlInterval itself:
record Policy(String name, SqlInterval timeout) {}
SqlInterval timeout = database.query("SELECT timeout FROM policy WHERE name = :name")
.bind("name", "webhooks")
.fetchObject(SqlInterval.class).orElseThrow();
Duration elapsed = timeout.toDuration();
record Policy(String name, SqlInterval timeout) {}
SqlInterval timeout = database.query("SELECT timeout FROM policy WHERE name = :name")
.bind("name", "webhooks")
.fetchObject(SqlInterval.class).orElseThrow();
Duration elapsed = timeout.toDuration();
toDuration() succeeds only when months and calendar days are zero. toPeriod() succeeds only when elapsed time is zero and normalizes total months into years/months. These are explicit conservative conversions: a subtraction result such as 3 days 02:00:00 remains representable but cannot become Duration automatically. For elapsed time between original instants, use Duration.between(startedAt, finishedAt). SQL calendar arithmetic and Java can resolve DST overlaps differently; adding months, days and time in Java is an application policy, not guaranteed database emulation.
PostgreSQL reads support all four IntervalStyle formats and binary interval transfer. Stored infinities fail. DuckDB text is parsed as a native interval. Oracle uses native YEAR-MONTH/DAY-SECOND values; DAY-SECOND's fixed 24-hour days become elapsed time. GENERIC support is driver-specific, including HSQLDB, and requires recognizable interval-family metadata. Text/numeric columns are not guessed to contain intervals. Returned values beyond the signed 32-bit total-month/day representation fail; for example, Oracle can return a wider leading-year range. Server coercion that changes fields before the read is subject to the storage caveats in the binding contract.
Field-wise equality distinguishes one calendar day from 24 elapsed hours and one month from 30 days; SQL equality may not. There is no ordering or TemporalAmount implementation. Optional-valued row properties remain unsupported, and interval ARRAY/STRUCT conversion is not included.
Custom column mappers retain their original driver inputs and precedence. With PostgreSQL binary transfer, a driver's PGInterval value may have no text representation; return fallback to request built-in SqlInterval conversion instead of parsing that object yourself. A custom/native target that requires an unsupported driver read still reports that failure. Native Map/Object targets retain driver representations and their existing limitations. Handled custom outputs and LOB ownership remain unchanged; SqlInterval itself owns no JDBC resource. Existing Duration/Period properties and SQL NULLs retain their behavior; no automatic SQL-interval coercion to those types is added.
SQL ARRAY and JSON Results
Typed temporal ARRAY elements follow the same time-zone rules as scalar columns when the driver supplies their SQL type. Pyranid uses Array::getBaseType() and Array::getBaseTypeName() to distinguish zone-less TIMESTAMP values from TIMESTAMP WITH TIME ZONE, including PostgreSQL TIMESTAMPTZ; nested arrays preserve that information. SQL DATE elements map through their calendar date, including when the destination is Instant, and timestamp nanoseconds are retained. Raw Object, List, and Set targets keep native element representations.
SQL TIME arrays mapped to LocalTime[], typed List<LocalTime> or Set<LocalTime> properties, or nested arrays preserve the fractional seconds supplied by the driver's typed reads. For drivers that expose array contents as legacy java.sql.Time[], Pyranid reads typed LocalTime elements before freeing the JDBC array. This also preserves the driver's end-of-day representation: a database value such as 24:00:00 cannot be represented directly by LocalTime, so Pyranid retains the driver's typed value (for example, LocalTime.MAX) instead of deriving midnight from the legacy value. If the driver cannot provide the required typed read, built-in temporal mapping raises DatabaseException rather than silently losing precision or changing that meaning.
PostgreSQL TIMETZ scalars and arrays preserve the original offset and fractional seconds when mapped to OffsetTime, including nested arrays. For drivers that expose zoned time arrays as legacy java.sql.Time[], Pyranid reads typed array elements before freeing the JDBC array. If the driver cannot supply a lossless typed read, built-in temporal mapping fails instead of inventing an offset; native results and custom mapper inputs retain their driver representations.
Mapping TIMETZ to LocalTime keeps its wall-clock time and fractional seconds while dropping the offset. This rule is the same for scalar results, record and JavaBean properties, and typed array elements.
SQL ARRAY columns can be mapped to Java array targets such as String[] or UUID[]. They can also be mapped to List<T> or Set<T> when Pyranid can see the generic element type from a Record component or JavaBean setter, for example record Row(List<String> tags, Set<String> labels) {} or void setTags(Set<String> tags). Raw scalar List.class and Set.class targets are supported too, but the element type is whatever the JDBC driver returns because Java's Class<List> and Class<Set> tokens carry no generic type argument. Set targets use insertion order from the SQL ARRAY and apply normal Set semantics, so duplicates collapse and multiple SQL NULL elements become one null.
For a typed scalar list from one SQL ARRAY column, fetch an array token and convert it explicitly. Long[].class carries its element type, whereas List.class does not:
Long[] values = database.query("SELECT ids FROM saved_filter WHERE id=:id")
.bind("id", 42).fetchObject(Long[].class).orElseThrow();
List<Long> ids = Arrays.asList(values);
Long[] values = database.query("SELECT ids FROM saved_filter WHERE id=:id")
.bind("id", 42).fetchObject(Long[].class).orElseThrow();
List<Long> ids = Arrays.asList(values);
Arrays.asList preserves SQL-null elements and returns a fixed-size view of this detached array. Use new ArrayList<>(ids) for a mutable independent list. List.of(values) and List.copyOf(ids) reject null elements. A SQL NULL array yields an empty fetch Optional, separately from an empty array.
PostgreSQL JSON/JSONB values returned by supported PostgreSQL JDBC drivers as PGobject, and DuckDB JSON values returned as driver nodes, map to String by default. Pyranid does not parse JSON into application objects; register a CustomColumnMapper when you want to inflate JSON into your own type.
Text-backed vector columns such as pgvector, which supported PostgreSQL JDBC drivers surface as literals like [0.1,0.2,0.3], map to float[] and double[] targets by parsing that literal. DuckDB fixed-size vector ARRAYs use Pyranid's SQL ARRAY conversion path. See Vector in the Parameter Binding docs for the bind side.
SQL STRUCT Results
On databases whose dialects surface SQL STRUCT columns as attribute-name-to-value maps - currently DuckDB - STRUCT values map onto Java records, recursively. Attribute names follow the same matching rules as result columns: camelCase components match snake_case attributes, and @DatabaseColumn aliases apply.
Typed DuckDB STRUCT timestamp attributes follow the scalar time-zone rules: zone-less timestamps use the configured database time zone, while timezone-bearing timestamps preserve their instant. This applies to nested records and records inside arrays; raw Map and Object attributes retain native values.
CREATE TABLE employee (
employee_id BIGINT PRIMARY KEY,
person STRUCT(name VARCHAR, email_address VARCHAR),
badges STRUCT(label VARCHAR, level INTEGER)[]
);
CREATE TABLE employee (
employee_id BIGINT PRIMARY KEY,
person STRUCT(name VARCHAR, email_address VARCHAR),
badges STRUCT(label VARCHAR, level INTEGER)[]
);
public record Person(String name, String emailAddress) {}
public record Badge(String label, Integer level) {}
public record Employee(Long employeeId, Person person, List<Badge> badges) {}
// STRUCT columns become record components; STRUCT lists become record lists
List<Employee> employees = database.query("SELECT * FROM employee")
.fetchList(Employee.class);
// A single-column STRUCT result maps directly to a record target...
Optional<Person> person = database.query("SELECT person FROM employee WHERE employee_id=:id")
.bind("id", 1L)
.fetchObject(Person.class);
// ...including STRUCT projections built in SQL (note the space after ':' - see SQL Parsing Rules)
Optional<Person> projected = database.query("""
SELECT {'name': name, 'email_address': email_address} AS person
FROM legacy_employee
WHERE employee_id=:id
""")
.bind("id", 1L)
.fetchObject(Person.class);
public record Person(String name, String emailAddress) {}
public record Badge(String label, Integer level) {}
public record Employee(Long employeeId, Person person, List<Badge> badges) {}
// STRUCT columns become record components; STRUCT lists become record lists
List<Employee> employees = database.query("SELECT * FROM employee")
.fetchList(Employee.class);
// A single-column STRUCT result maps directly to a record target...
Optional<Person> person = database.query("SELECT person FROM employee WHERE employee_id=:id")
.bind("id", 1L)
.fetchObject(Person.class);
// ...including STRUCT projections built in SQL (note the space after ':' - see SQL Parsing Rules)
Optional<Person> projected = database.query("""
SELECT {'name': name, 'email_address': email_address} AS person
FROM legacy_employee
WHERE employee_id=:id
""")
.bind("id", 1L)
.fetchObject(Person.class);
Nested parameterized records retain their declared component types: for example, a Box<UUID> nested directly, inside a List, or as a typed Map value converts its UUID component rather than leaving the driver string. The canonical constructor still follows the record declaration.
Nested STRUCTs map to nested records to any depth, and a record component typed Map<String, Object> receives the attribute map itself. Map row targets surface STRUCT values as plain insertion-ordered maps with no driver-specific types, including elements of top-level STRUCT/JSON list columns. Ordinary by-name row mapping always takes precedence: the single-column direct mapping applies only when no result column matches a record component. A NULL STRUCT maps to a null component (or an empty Optional for single-column fetches). Top-level row records - the single-column direct mapping included - are constructed via the configured InstanceProvider; nested records are constructed via their canonical constructors, and CustomColumnMappers are not consulted for individual STRUCT attributes.
Map-valued record components and JavaBean properties also convert visible generic key/value types recursively. For example, record Row(Map<String, Long> counts) {} converts DuckDB integer values to Long, while Map<UUID, List<Long>> converts both UUID keys and nested elements. This includes maps nested in arrays, lists or STRUCTs, and inherited generic setters. Nested generic collections use declared List<T>/Set<T> interfaces or arrays; typed concrete collection targets such as ArrayList<T> require a custom mapper. Converted maps use insertion-ordered LinkedHashMap instances; Map, HashMap and LinkedHashMap property types are compatible. Targets requiring another implementation, such as SortedMap, EnumMap or a custom map subclass, fail clearly; use a custom mapper for those policies. Null keys/values are retained, and distinct source keys that become equal after conversion cause a mapping error instead of losing an entry. DuckDB legacy Timestamp entries require readable MAP/STRUCT type declarations to distinguish local from zoned timestamps; ambiguous entries fail rather than guessing a zone.
By default, raw Map properties, Map<Object, Object>, and native Object targets retain native value semantics. Query.mapRowType() still maps a whole row by column labels; it does not supply a generic type token for a single MAP-valued column. A custom column mapper for the property still receives the original JDBC value and can override the built-in conversion.
Custom Mapping
Fine-grained control of mapping is supported by registering CustomColumnMapper instances. For example, you might want to "inflate" a JSONB column into a Java type:
When multiple custom column mappers apply, Pyranid tries them in the order supplied. Returning MappingResult::fallback() lets the next applicable mapper run; if none handles the value, normal mapping continues.
In 4.9, TargetType::getArrayComponentType() prefers the declared generic component before the erased array class. For List<String>[], a custom hook sees List<String> as the component; generic bounds and type variables are retained too. Audit hooks that assume the component’s getType() is always a Class or cache selection only by the raw component class. Use getRawClass() explicitly when erasure is your intended policy. Ordinary non-generic arrays keep their component shape.
When mapping JavaBeans or records, custom column mappers run against matched properties or components. Row-type custom mapping is for single-column results that represent the target value itself.
// Your application-specific type
class MySpecialType {
List<UUID> uuids;
Currency currency;
}
// Your application-specific type
class MySpecialType {
List<UUID> uuids;
Currency currency;
}
Just add a CustomColumnMapper that handles it:
ResultSetMapper resultSetMapper = ResultSetMapper.withCustomColumnMappers(List.of(new CustomColumnMapper() {
@NonNull
@Override
public Boolean appliesTo(@NonNull TargetType targetType) {
// Can also apply to parameterized types, e.g.
// targetType.matchesParameterizedType(List.class, UUID.class) for List<UUID>
return targetType.matchesClass(MySpecialType.class);
}
@NonNull
@Override
public MappingResult map(
@NonNull StatementContext<?> statementContext,
@NonNull ResultSet resultSet,
@NonNull Object resultSetValue,
@NonNull TargetType targetType,
@NonNull Integer columnIndex,
@Nullable String columnLabel,
@NonNull InstanceProvider instanceProvider
) {
// Pull JSON String data from the ResultSet and inflate it
String json = resultSetValue.toString();
MySpecialType mySpecialType = GSON.fromJson(json, MySpecialType.class);
// Or return MappingResult.fallback() to let the next applicable custom mapper run.
// If none handles the value, Pyranid continues with normal mapping behavior.
return MappingResult.of(mySpecialType);
}
}))
.build();
// Construct your database with the custom mapper
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(resultSetMapper)
.build();
ResultSetMapper resultSetMapper = ResultSetMapper.withCustomColumnMappers(List.of(new CustomColumnMapper() {
@NonNull
@Override
public Boolean appliesTo(@NonNull TargetType targetType) {
// Can also apply to parameterized types, e.g.
// targetType.matchesParameterizedType(List.class, UUID.class) for List<UUID>
return targetType.matchesClass(MySpecialType.class);
}
@NonNull
@Override
public MappingResult map(
@NonNull StatementContext<?> statementContext,
@NonNull ResultSet resultSet,
@NonNull Object resultSetValue,
@NonNull TargetType targetType,
@NonNull Integer columnIndex,
@Nullable String columnLabel,
@NonNull InstanceProvider instanceProvider
) {
// Pull JSON String data from the ResultSet and inflate it
String json = resultSetValue.toString();
MySpecialType mySpecialType = GSON.fromJson(json, MySpecialType.class);
// Or return MappingResult.fallback() to let the next applicable custom mapper run.
// If none handles the value, Pyranid continues with normal mapping behavior.
return MappingResult.of(mySpecialType);
}
}))
.build();
// Construct your database with the custom mapper
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(resultSetMapper)
.build();
With the custom mapper in place, and a table like this...
CREATE TABLE row (
row_id UUID PRIMARY KEY,
my_special_type JSONB NOT NULL
);
INSERT INTO row (row_id, my_special_type) VALUES (
'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
'
{
"uuids": ["bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"],
"currency": "BRL"
}
'::JSONB
);
CREATE TABLE row (
row_id UUID PRIMARY KEY,
my_special_type JSONB NOT NULL
);
INSERT INTO row (row_id, my_special_type) VALUES (
'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
'
{
"uuids": ["bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"],
"currency": "BRL"
}
'::JSONB
);
...your application code might look like this:
// A ResultSet row with our special type as a column
public record MyRow(UUID rowId, MySpecialType mySpecialType) {}
// Query for data
List<MyRow> rows = database.query("SELECT * FROM row").fetchList(MyRow.class);
// Examine the first row of the ResultSet
MyRow myRow = rows.get(0);
// Our custom mapper has instantiated this for us
MySpecialType mySpecialType = myRow.mySpecialType();
// Prints contents of List<UUID>, as expected
out.println(mySpecialType.uuids);
// e.g. "Real brasileiro" for Brazilian Real
out.println(mySpecialType.currency.getDisplayName(Locale.forLanguageTag("pt-BR")));
// A ResultSet row with our special type as a column
public record MyRow(UUID rowId, MySpecialType mySpecialType) {}
// Query for data
List<MyRow> rows = database.query("SELECT * FROM row").fetchList(MyRow.class);
// Examine the first row of the ResultSet
MyRow myRow = rows.get(0);
// Our custom mapper has instantiated this for us
MySpecialType mySpecialType = myRow.mySpecialType();
// Prints contents of List<UUID>, as expected
out.println(mySpecialType.uuids);
// e.g. "Real brasileiro" for Brazilian Real
out.println(mySpecialType.currency.getDisplayName(Locale.forLanguageTag("pt-BR")));
Your CustomColumnMapper also works for the single-column "Standard Type" scenario.
// Pull back the column for a single row
Optional<MySpecialType> mySpecialType =
database.query("SELECT my_special_type FROM row LIMIT 1")
.fetchObject(MySpecialType.class);
// Pull back a list of just the column values
List<MySpecialType> mySpecialTypes =
database.query("SELECT my_special_type FROM row")
.fetchList(MySpecialType.class);
// Pull back the column for a single row
Optional<MySpecialType> mySpecialType =
database.query("SELECT my_special_type FROM row LIMIT 1")
.fetchObject(MySpecialType.class);
// Pull back a list of just the column values
List<MySpecialType> mySpecialTypes =
database.query("SELECT my_special_type FROM row")
.fetchList(MySpecialType.class);
Parameterized-Type Example
Custom mapping is not limited to concrete classes. You can target parameterized types directly.
Suppose your database stores localized strings in a JSONB column and you want Pyranid to map it to a Map from Locale to String.
ResultSetMapper resultSetMapper = ResultSetMapper.withCustomColumnMappers(List.of(new CustomColumnMapper() {
@NonNull
@Override
public Boolean appliesTo(@NonNull TargetType targetType) {
return targetType.matchesParameterizedType(Map.class, Locale.class, String.class);
}
@NonNull
@Override
public MappingResult map(
@NonNull StatementContext<?> statementContext,
@NonNull ResultSet resultSet,
@Nullable Object rawColumnValue,
@NonNull TargetType targetType,
@Nullable Integer columnIndex,
@Nullable String columnLabel,
@NonNull InstanceProvider instanceProvider
) {
if (rawColumnValue == null)
return MappingResult.of(null);
Type mapType = new TypeToken<Map<Locale, String>>() {}.getType();
Map<Locale, String> valuesByLocale = GSON.fromJson(rawColumnValue.toString(), mapType);
return MappingResult.of(valuesByLocale);
}
})).build();
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(resultSetMapper)
.build();
ResultSetMapper resultSetMapper = ResultSetMapper.withCustomColumnMappers(List.of(new CustomColumnMapper() {
@NonNull
@Override
public Boolean appliesTo(@NonNull TargetType targetType) {
return targetType.matchesParameterizedType(Map.class, Locale.class, String.class);
}
@NonNull
@Override
public MappingResult map(
@NonNull StatementContext<?> statementContext,
@NonNull ResultSet resultSet,
@Nullable Object rawColumnValue,
@NonNull TargetType targetType,
@Nullable Integer columnIndex,
@Nullable String columnLabel,
@NonNull InstanceProvider instanceProvider
) {
if (rawColumnValue == null)
return MappingResult.of(null);
Type mapType = new TypeToken<Map<Locale, String>>() {}.getType();
Map<Locale, String> valuesByLocale = GSON.fromJson(rawColumnValue.toString(), mapType);
return MappingResult.of(valuesByLocale);
}
})).build();
Database database = Database.with(dataSource, DatabaseType.POSTGRESQL)
.resultSetMapper(resultSetMapper)
.build();
With that mapper in place, a row type like this works as expected:
public record Product(
UUID productId,
Map<Locale, String> nameTranslations
) {}
Optional<Product> product = database.query("""
SELECT product_id, name_translations
FROM product
WHERE product_id = :productId
""")
.bind("productId", UUID.fromString("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"))
.fetchObject(Product.class);
public record Product(
UUID productId,
Map<Locale, String> nameTranslations
) {}
Optional<Product> product = database.query("""
SELECT product_id, name_translations
FROM product
WHERE product_id = :productId
""")
.bind("productId", UUID.fromString("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"))
.fetchObject(Product.class);
If you also need to write the same type, pair this mapper with a matching CustomParameterBinder as shown in the Parameterized-Type Example in the Parameter Binding docs.
Per-Query Mapping and Binding
The ResultSetMapper and PreparedStatementBinder SPIs are normally configured database-wide at build time. They can also be overridden for a single query via Query::resultSetMapper(...) and Query::preparedStatementBinder(...); the same contracts apply per query.
These SPIs declare generic methods. Implement map(...) in an anonymous class to handle an ad-hoc projection (a join, computed columns, a tuple) for one query:
public record NameCount(String name, Long total) {}
List<NameCount> counts = database.query("""
SELECT name, COUNT(*) AS total
FROM employee
GROUP BY name
""")
.resultSetMapper(new ResultSetMapper() {
@Override
public <T> Optional<T> map(
StatementContext<T> ctx, ResultSet rs, Class<T> type,
InstanceProvider ip
) throws SQLException {
return Optional.of(type.cast(new NameCount(rs.getString(1), rs.getLong(2))));
}
})
.fetchList(NameCount.class);
public record NameCount(String name, Long total) {}
List<NameCount> counts = database.query("""
SELECT name, COUNT(*) AS total
FROM employee
GROUP BY name
""")
.resultSetMapper(new ResultSetMapper() {
@Override
public <T> Optional<T> map(
StatementContext<T> ctx, ResultSet rs, Class<T> type,
InstanceProvider ip
) throws SQLException {
return Optional.of(type.cast(new NameCount(rs.getString(1), rs.getLong(2))));
}
})
.fetchList(NameCount.class);
The override applies to every row this query maps - including Query::fetchStream(...) rows and DML-returning results - and to every parameter this query binds, including expanded IN-list elements and each batch group. Other queries on the same Database are unaffected; passing null restores the database-wide instance. Metrics, statement logging, and exception diagnostics behave identically with an override present.
Custom binders receive bound-ready raw values: SecureParameter and Optional wrappers are unwrapped by Pyranid before the binder is invoked, and null parameters never reach the binder (Pyranid binds them via PreparedStatement::setNull(...) even when an override is present).

