Skip to content

Fix queries on JSON fields #1987

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1323,10 +1323,25 @@ private static class MetaData implements ResultSetMetaData {

private final List<String> columns;
private final List<ColumnDescriptor> descriptors;
private final String[] typeNames;


public MetaData(List<String> columnNames, List<ColumnDescriptor> columnDescriptors) {
columns = columnNames;
descriptors = columnDescriptors;
typeNames = initTypeNames( columnDescriptors );
}

private static String[] initTypeNames(List<ColumnDescriptor> columnDescriptors) {
if ( columnDescriptors == null ) {
return null;
}
final String[] typeNames = new String[columnDescriptors.size()];
int i = 0;
for ( ColumnDescriptor columnDescriptor : columnDescriptors ) {
typeNames[i++] = columnDescriptor.typeName();
}
return typeNames;
}

@Override
Expand Down Expand Up @@ -1412,9 +1427,7 @@ public String getCatalogName(int column) {

@Override
public String getColumnTypeName(int column) {
// This information is in rows.columnDescriptors().get( column-1 ).dataType.name
// but does not appear to be accessible.
return null;
return typeNames[column - 1];
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.reactive.adaptor.impl.PreparedStatementAdaptor;
import org.hibernate.reactive.type.descriptor.jdbc.ReactiveArrayJdbcTypeConstructor;
import org.hibernate.reactive.type.descriptor.jdbc.ReactiveJsonJdbcType;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.BasicTypeRegistry;
import org.hibernate.type.SqlTypes;
import org.hibernate.type.descriptor.ValueBinder;
import org.hibernate.type.descriptor.ValueExtractor;
import org.hibernate.type.descriptor.WrapperOptions;
Expand Down Expand Up @@ -83,6 +85,7 @@ private void registerReactiveChanges(TypeContributions typeContributions, Servic

JdbcTypeRegistry jdbcTypeRegistry = typeConfiguration.getJdbcTypeRegistry();
jdbcTypeRegistry.addTypeConstructor( ReactiveArrayJdbcTypeConstructor.INSTANCE );
jdbcTypeRegistry.addDescriptor( SqlTypes.JSON, ReactiveJsonJdbcType.INSTANCE );

if ( dialect instanceof MySQLDialect || dialect instanceof DB2Dialect || dialect instanceof OracleDialect ) {
jdbcTypeRegistry.addDescriptor( TimestampAsLocalDateTimeJdbcType.INSTANCE );
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/* Hibernate, Relational Persistence for Idiomatic Java
*
* SPDX-License-Identifier: Apache-2.0
* Copyright: Red Hat Inc. and Hibernate Authors
*/
package org.hibernate.reactive.type.descriptor.jdbc;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.hibernate.metamodel.mapping.EmbeddableMappingType;
import org.hibernate.metamodel.spi.RuntimeModelCreationContext;
import org.hibernate.type.descriptor.ValueBinder;
import org.hibernate.type.descriptor.ValueExtractor;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.JavaType;
import org.hibernate.type.descriptor.jdbc.AggregateJdbcType;
import org.hibernate.type.descriptor.jdbc.BasicBinder;
import org.hibernate.type.descriptor.jdbc.BasicExtractor;
import org.hibernate.type.descriptor.jdbc.JsonJdbcType;

import io.vertx.core.json.JsonObject;

/**
* Map a JSON column as {@link JsonObject}
*/
public class ReactiveJsonJdbcType extends JsonJdbcType {

public static final ReactiveJsonJdbcType INSTANCE = new ReactiveJsonJdbcType( null );

protected ReactiveJsonJdbcType(EmbeddableMappingType embeddableMappingType) {
super( embeddableMappingType );
}

@Override
public AggregateJdbcType resolveAggregateJdbcType(
EmbeddableMappingType mappingType, String sqlType, RuntimeModelCreationContext creationContext) {
return new ReactiveJsonJdbcType( mappingType );
}

@Override
public <X> ValueBinder<X> getBinder(JavaType<X> javaType) {
return new BasicBinder<>( javaType, this ) {
@Override
protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options)
throws SQLException {
st.setObject( index, toJsonObject( value, javaType, options ) );
}

@Override
protected void doBind(CallableStatement st, X value, String name, WrapperOptions options)
throws SQLException {
st.setObject( name, toJsonObject( value, javaType, options ) );
}
};
}

protected <X> JsonObject toJsonObject(X value, JavaType<X> javaType, WrapperOptions options) {
return new JsonObject( this.toString( value, javaType, options ) );
}

@Override
public <X> ValueExtractor<X> getExtractor(JavaType<X> javaType) {
return new BasicExtractor<>( javaType, this ) {
@Override
protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException {
return fromString( toJsonString( rs.getObject( paramIndex ) ), getJavaType(), options );
}

@Override
protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException {
return fromString( toJsonString( statement.getObject( index ) ), getJavaType(), options );
}

@Override
protected X doExtract(CallableStatement statement, String name, WrapperOptions options)
throws SQLException {
return fromString( toJsonString( statement.getObject( name ) ), getJavaType(), options );
}
};
}

private static String toJsonString(Object value) {
if ( value == null ) {
return null;
}
// Value should be a JsonObject
return value.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
*/
package org.hibernate.reactive;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -60,6 +62,60 @@ protected Collection<Class<?>> annotatedEntities() {
return List.of( Book.class, Author.class );
}

private final static BigDecimal PIE = BigDecimal.valueOf( 3.1416 );
private final static BigDecimal TAO = BigDecimal.valueOf( 6.2832 );

@Test
public void testBigDecimalAsParameter(VertxTestContext context) {
Author author1 = new Author( "Iain M. Banks" );
Author author2 = new Author( "Neal Stephenson" );
Book book1 = new Book( "1-85723-235-6", "Feersum Endjinn", author1 );
book1.quantity = BigDecimal.valueOf( 11.2 );
Book book2 = new Book( "0-380-97346-4", "Cryptonomicon", author2 );
book2.quantity = PIE;
Book book3 = new Book( "0-553-08853-X", "Snow Crash", author2 );
book3.quantity = TAO;

author1.books.add( book1 );
author2.books.add( book2 );
author2.books.add( book3 );

test( context, getMutinySessionFactory()
.withTransaction( s -> s.persistAll( author1, author2 ) )
// HQL with named parameters
.chain( () -> getMutinySessionFactory().withTransaction( s -> s
.createSelectionQuery( "from Book where quantity > :quantity", Book.class )
.setParameter( "quantity", PIE )
.getResultList()
.invoke( result -> assertThat( result ).containsExactlyInAnyOrder( book1, book3 ) )
) )
// HQL with positional parameters
.chain( () -> getMutinySessionFactory().withTransaction( s -> s
.createSelectionQuery( "from Book where quantity > ?1", Book.class )
.setParameter( 1, PIE )
.getResultList()
.invoke( result -> assertThat( result ).containsExactlyInAnyOrder( book1, book3 ) )
) )
// Criteria
.call( () -> {
CriteriaBuilder builder = getSessionFactory().getCriteriaBuilder();
CriteriaQuery<Book> query = builder.createQuery( Book.class );
Root<Book> b = query.from( Book.class );
b.fetch( "author" );
query.where( builder.between(
b.get( "quantity" ),
BigDecimal.valueOf( 4.0 ),
BigDecimal.valueOf( 100.0 )
) );
return getMutinySessionFactory().withTransaction( s -> s
.createQuery( query )
.getResultList()
.invoke( result -> assertThat( result ).containsExactlyInAnyOrder( book1, book3 ) )
);
} )
);
}

@Test
public void testCriteriaEntityQuery(VertxTestContext context) {
Author author1 = new Author( "Iain M. Banks" );
Expand Down Expand Up @@ -711,6 +767,28 @@ static class Author {

Author() {
}

@Override
public String toString() {
return id + ":" + name;
}

@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Author author = (Author) o;
return Objects.equals( name, author.name );
}

@Override
public int hashCode() {
return Objects.hashCode( name );
}
}

@Entity(name = "Book")
Expand All @@ -729,6 +807,8 @@ static class Book {
@ManyToOne(fetch = LAZY)
Author author;

BigDecimal quantity;

Book(String isbn, String title, Author author) {
this.title = title;
this.isbn = isbn;
Expand All @@ -737,6 +817,31 @@ static class Book {

Book() {
}

@Override
public String toString() {
return id + ":" + title + ":" + isbn + ":" + quantity;
}

@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Book book = (Book) o;
return Objects.equals( isbn, book.isbn ) && Objects.equals(
title,
book.title
);
}

@Override
public int hashCode() {
return Objects.hash( isbn, title );
}
}

}
Loading
Loading