use of io.micronaut.data.runtime.mapper.TypeMapper in project micronaut-data by micronaut-projects.
the class DefaultJdbcRepositoryOperations method findOne.
@Nullable
@Override
public <T, R> R findOne(@NonNull PreparedQuery<T, R> preparedQuery) {
return executeRead(connection -> {
RuntimePersistentEntity<T> persistentEntity = getEntity(preparedQuery.getRootEntity());
try (PreparedStatement ps = prepareStatement(connection, connection::prepareStatement, preparedQuery, false, true)) {
try (ResultSet rs = ps.executeQuery()) {
Class<R> resultType = preparedQuery.getResultType();
if (preparedQuery.getResultDataType() == DataType.ENTITY) {
RuntimePersistentEntity<R> resultPersistentEntity = getEntity(resultType);
final Set<JoinPath> joinFetchPaths = preparedQuery.getJoinFetchPaths();
SqlResultEntityTypeMapper<ResultSet, R> mapper = new SqlResultEntityTypeMapper<>(resultPersistentEntity, columnNameResultSetReader, joinFetchPaths, jsonCodec, (loadedEntity, o) -> {
if (loadedEntity.hasPostLoadEventListeners()) {
return triggerPostLoad(o, loadedEntity, preparedQuery.getAnnotationMetadata());
} else {
return o;
}
}, conversionService);
SqlResultEntityTypeMapper.PushingMapper<ResultSet, R> oneMapper = mapper.readOneWithJoins();
if (rs.next()) {
oneMapper.processRow(rs);
}
while (!joinFetchPaths.isEmpty() && rs.next()) {
oneMapper.processRow(rs);
}
R result = oneMapper.getResult();
if (preparedQuery.hasResultConsumer()) {
preparedQuery.getParameterInRole(SqlResultConsumer.ROLE, SqlResultConsumer.class).ifPresent(consumer -> consumer.accept(result, newMappingContext(rs)));
}
return result;
} else if (rs.next()) {
if (preparedQuery.isDtoProjection()) {
TypeMapper<ResultSet, R> introspectedDataMapper = new DTOMapper<>(persistentEntity, columnNameResultSetReader, jsonCodec, conversionService);
return introspectedDataMapper.map(rs, resultType);
} else {
Object v = columnIndexResultSetReader.readDynamic(rs, 1, preparedQuery.getResultDataType());
if (v == null) {
return null;
} else if (resultType.isInstance(v)) {
return (R) v;
} else {
return columnIndexResultSetReader.convertRequired(v, resultType);
}
}
}
}
} catch (SQLException e) {
throw new DataAccessException("Error executing SQL Query: " + e.getMessage(), e);
}
return null;
});
}
Aggregations