La Biblioteca Posjsonhelper es un proyecto de código abierto que agrega soporte de la consulta Hibernate para las funciones JSON PostgreSQL. La biblioteca también tiene soporte para las funciones de búsqueda de texto PostgreSQL. Para saber más sobre cómo usar los componentes de búsqueda de texto, verifique las instrucciones del módulo de texto. La biblioteca está escrita en un lenguaje de programación Java. El proyecto para este momento admite Hibernate con la Versión 5 y 6. La versión requerida de Java es al menos la versión 8 para Hibernate 5 Soporte y versión 11 para Hibernate 6.
El proyecto está disponible en el repositorio central de Maven. Puede usarlo simplemente agregándolo como una dependencia en el archivo de descriptor del proyecto (pom.xml).
Para Hibernate 5:
< dependency >
< groupId >com.github.starnowski.posjsonhelper</ groupId >
< artifactId >hibernate5</ artifactId >
< version >0.4.2</ version >
</ dependency >Para Hibernate 6:
< dependency >
< groupId >com.github.starnowski.posjsonhelper</ groupId >
< artifactId >hibernate6</ artifactId >
< version >0.4.2</ version >
</ dependency >La biblioteca Posjsonhelper no tiene dependencia transitoria para la biblioteca Hibernate. Así que tenga en cuenta que la dependencia hibernada debe agregarse separadas en su proyecto como a continuación:
< dependency >
< groupId >org.hibernate</ groupId >
< artifactId >hibernate-core</ artifactId >
< version >????</ version >
</ dependency >Verifique la matriz de versión de compatibilidad de Hibernate para verificar la versión correcta.
Implementación predeterminada para algunas funcionalidades relacionadas con las operaciones JSON requiere org.json: biblioteca JSON. Sin embargo, hay formas de implementar interfaces específicas y la biblioteca debajo podría no ser necesaria para agregar.
< dependency >
< groupId >org.json</ groupId >
< artifactId >json</ artifactId >
< version >20240303</ version >
</ dependency >Si alguien desea construir el proyecto localmente a partir de la fuente, consulte el archivo Contrabando.md para verificar cómo configurar el proyecto localmente.
¡Importante! Esta sección solo es válida para Hibernate 5. Para poder usar la biblioteca Posjsonhelper en el proyecto, debe especificarse el dialecto de Hibernate correcto. La biblioteca implementa pocos envoltorios que se extienden ya existían dialectos hibernados para PostgreSQL:
El dialecto debe establecerse en el archivo de configuración de hibernate, por ejemplo:
<? xml version = " 1.0 " encoding = " UTF-8 " ?>
< hibernate-configuration xmlns = " http://www.hibernate.org/xsd/orm/cfg " >
< session-factory >
< property name = " hibernate.dialect " >com.github.starnowski.posjsonhelper.hibernate5.dialects.PostgreSQL95DialectWrapper</ property >
...o, por ejemplo, en el archivo de propiedades de configuración del marco de Spring:
...
spring.jpa.properties.hibernate.dialect =com.github.starnowski.posjsonhelper.hibernate5.dialects.PostgreSQL95DialectWrapper
...En caso de que ya tenga un tipo que extienda el tipo de dialecto hibernado y se requiere para su proyecto. Agrega ajuste a su tipo para que use el componente PostgreSqlDialectenRicher.
import com . github . starnowski . posjsonhelper . hibernate5 . PostgreSQLDialectEnricher ;
import org . hibernate . dialect . PostgreSQL95Dialect ;
public class PostgreSQLDialectWithDifferentSchema extends PostgreSQL95Dialect {
public PostgreSQLDialectWithDifferentSchema () {
PostgreSQLDialectEnricher enricher = new PostgreSQLDialectEnricher ();
enricher . enrich ( this );
}
}¡Importante! Esta sección solo es válida para Hibernate 6. Para usar la biblioteca Posjsonhelper en el proyecto que usa Hibernate 6, debe haber una Org.Hibernate.Boot.Model.Model.FunctionContributor Implementación. La biblioteca tiene la implementación de esta interfaz, es decir, com.github.starnowski.posjsonhelper.Hibernate6.posjsonhelperfunctionCributor.
Para usar esta implementación, se requiere crear el archivo con el nombre "org.hibernate.boot.model.functionContributor" en "Recursos/metainf/servicios".
La solución alternativa es usar com.github.starnowski.posjsonhelper.Hibernate6.SQMFunctionRegistryEnricher Component durante el inicio de la aplicación. Como en el siguiente ejemplo con el uso del marco de primavera.
import com . github . starnowski . posjsonhelper . hibernate6 . SqmFunctionRegistryEnricher ;
import jakarta . persistence . EntityManager ;
import org . hibernate . query . sqm . NodeBuilder ;
import org . springframework . beans . factory . annotation . Autowired ;
import org . springframework . context . ApplicationListener ;
import org . springframework . context . annotation . Configuration ;
import org . springframework . context . event . ContextRefreshedEvent ;
@ Configuration
public class FunctionDescriptorConfiguration implements
ApplicationListener < ContextRefreshedEvent > {
@ Autowired
private EntityManager entityManager ;
@ Override
public void onApplicationEvent ( ContextRefreshedEvent event ) {
NodeBuilder nodeBuilder = ( NodeBuilder ) entityManager . getCriteriaBuilder ();
SqmFunctionRegistryEnricher sqmFunctionRegistryEnricher = new SqmFunctionRegistryEnricher ();
sqmFunctionRegistryEnricher . enrich ( nodeBuilder . getQueryEngine (). getSqmFunctionRegistry ());
}
}Para usar la biblioteca Posjsonhelper, se requiere crear algunas funciones SQL que ejecuten operadores JSON. Hibernate no pueden ejecutar algunos operadores JSON porque deben ser escapados. Para una configuración predeterminada, la biblioteca requiere que se creen las siguientes funciones.
CREATE OR REPLACE FUNCTION jsonb_all_array_strings_exist (jsonb, text []) RETURNS boolean AS $$
SELECT $ 1 ?& $ 2 ;
$$ LANGUAGE SQL;
CREATE OR REPLACE FUNCTION jsonb_any_array_strings_exist (jsonb, text []) RETURNS boolean AS $$
SELECT $ 1 ?| $ 2 ;
$$ LANGUAGE SQL;La instrucción DDL generada se puede ejecutar durante las pruebas de integración o utilizado por herramientas que aplican cambios en la base de datos, como Liquibase o Flyway. ¡Importante! Si hubiera requerimiento de usar una función similar pero con diferentes nombres, entonces esto debe especificarse en las propiedades de la aplicación. Se requiere porque los tipos extienden el tipo de dialecto hibernado, mencionado en la sección ["Cómo adjuntar el dialecto PostgreSQL"] (#dialecto de to-to-attach-postgresql) puede no tener acceso al contexto de la aplicación (COI). Sin embargo, en caso de que si tales propiedades se pasen de manera diferente, el tipo PostgreSQDialectenRicher también tiene el método para aprobar objetos de contexto (verifique el contexto central y el contexto de hibernación)
La clase de contexto contiene nombres de funciones utilizadas por la biblioteca. Las clases de dialecto utilizan el componente de CoreContextPropertiesSsupplier que genera objeto de contexto basado en la propiedad del sistema.
También es posible agregar DDL mediante el tipo de DatabaseOperationExecutorFacade. A continuación hay un ejemplo sobre cómo aplicar los cambios de DDL en la aplicación con el contexto del marco de Spring.
import com . github . starnowski . posjsonhelper . core . Context ;
import com . github . starnowski . posjsonhelper . core . DatabaseOperationExecutorFacade ;
import com . github . starnowski . posjsonhelper . core . DatabaseOperationType ;
import org . springframework . beans . factory . annotation . Autowired ;
import org . springframework . context . ApplicationListener ;
import org . springframework . context . annotation . Configuration ;
import org . springframework . context . event . ContextRefreshedEvent ;
import javax . sql . DataSource ;
@ Configuration
public class SQLFunctionsConfiguration implements
ApplicationListener < ContextRefreshedEvent > {
@ Autowired
private Context context ;
@ Autowired
private DataSource dataSource ;
@ Override
public void onApplicationEvent ( ContextRefreshedEvent contextRefreshedEvent ) {
DatabaseOperationExecutorFacade facade = new DatabaseOperationExecutorFacade ();
try {
facade . execute ( dataSource , context , DatabaseOperationType . LOG_ALL );
facade . execute ( dataSource , context , DatabaseOperationType . CREATE );
facade . execute ( dataSource , context , DatabaseOperationType . VALIDATE );
} catch ( Exception e ) {
throw new RuntimeException ( "Error during initialization of sql functions for jsonb type operations" , e );
}
}
}Hay algunas operaciones que pueden ser ejecutadas por el objeto DatabaseOperationExecutorFacade
| Nombre de propiedad | Descripción |
|---|---|
| CREAR | Aplica los cambios de DDL en la base de datos |
| VALIDAR | Valida si los cambios DDL se aplicaron a la base de datos |
| GOTA | Deja los cambios de DDL en la base de datos |
| Log_all | Muestra scripts DDL para las operaciones Crear, Validar y Drop. |
Para una explicación más fácil, supongamos que tenemos una tabla de base de datos con una columna que almacena el tipo JSONB.
create table item (
id int8 not null ,
jsonb_content jsonb,
primary key (id)
)Para esta tabla, podemos insertar fila con cualquier JSON, como en el ejemplo a continuación:
INSERT INTO item (id, jsonb_content) VALUES ( 1 , ' {"top_element_with_set_of_values":["TAG1","TAG2","TAG11","TAG12","TAG21","TAG22"]} ' );
INSERT INTO item (id, jsonb_content) VALUES ( 2 , ' {"top_element_with_set_of_values":["TAG3"]} ' );
-- item without any properties, just an empty json
INSERT INTO item (id, jsonb_content) VALUES ( 6 , ' {} ' );
-- int values
INSERT INTO item (id, jsonb_content) VALUES ( 7 , ' {"integer_value": 132} ' );
-- double values
INSERT INTO item (id, jsonb_content) VALUES ( 10 , ' {"double_value": 353.01} ' );
INSERT INTO item (id, jsonb_content) VALUES ( 11 , ' {"double_value": -1137.98} ' );
-- enum values
INSERT INTO item (id, jsonb_content) VALUES ( 13 , ' {"enum_value": "SUPER"} ' );
-- string values
INSERT INTO item (id, jsonb_content) VALUES ( 18 , ' {"string_value": "the end of records"} ' );La mayoría de los componentes predicados usan objeto de contexto hibernado. Sostiene principalmente los nombres de los nombres de funciones hibernados utilizados en el proyecto. Las clases de dialecto y el tipo de Contributor usan el componente HibernateContextPropertiesSupplier que genera objeto HibernateContext en función de la propiedad del sistema. Si no es necesario cambiar los nombres de funciones HQL predeterminados para los operadores de PSOJSONHELPER, incluso es usar HibernateContext creado por el componente de construcción como a continuación:
HibernateContext hibernateContext = HibernateContext . builder (). build ();La "jsonb_extract_path" es la función PostgreSQL que devuelve el valor de JSONB apuntado por los elementos de ruta pasados como "texto []" (equivalente a #> operador). Es útil porque muchas funciones usan el tipo "JSONB" para la ejecución. Consulte la documentación de PostgreSQL para obtener más información. Hibernate 5 Ejemplo : a continuación hay un ejemplo de un método que devuelve una lista de objeto de elementos para el cual la propiedad de contenido JSON "top_element_with_set_of_values" contiene un conjunto exacto de valores. El ejemplo usa JSONBasLArrayStringsexistPredicate.
@ Autowired
private HibernateContext hibernateContext ;
@ Autowired
private EntityManager entityManager ;
public List < Item > findAllByAllMatchingTags ( Set < String > tags ) {
CriteriaBuilder cb = entityManager . getCriteriaBuilder ();
CriteriaQuery < Item > query = cb . createQuery ( Item . class );
Root < Item > root = query . from ( Item . class );
query . select ( root );
query . where ( new JsonbAllArrayStringsExistPredicate ( hibernateContext , ( CriteriaBuilderImpl ) cb , new JsonBExtractPath (( CriteriaBuilderImpl ) cb , singletonList ( "top_element_with_set_of_values" ), root . get ( "jsonbContent" )), tags . toArray ( new String [ 0 ])));
return entityManager . createQuery ( query ). getResultList ();
}Para el método anterior, Hibernate ejecutará la consulta HQL:
select
generatedAlias0
from
Item as generatedAlias0
where
jsonb_all_array_strings_exist( jsonb_extract_path( generatedAlias0 . jsonbContent , :param0 ) , json_function_json_array(:param1)) = TRUESQL nativo tendrá el siguiente formulario:
select
item0_ . id as id1_0_,
item0_ . jsonb_content as jsonb_co2_0_
from
item item0_
where
jsonb_all_array_strings_exist(jsonb_extract_path( item0_ . jsonb_content ,?), array[?]) = truePara obtener más detalles, consulte el DAO utilizado en las pruebas.
Hibernate 6 Ejemplo :
A continuación hay el mismo ejemplo que el anterior pero para Hibernate 6.
import org . hibernate . query . sqm . NodeBuilder ;
....
@ Autowired
private HibernateContext hibernateContext ;
@ Autowired
private EntityManager entityManager ;
public List < Item > findAllByAllMatchingTags ( Set < String > tags ) {
CriteriaBuilder cb = entityManager . getCriteriaBuilder ();
CriteriaQuery < Item > query = cb . createQuery ( Item . class );
Root < Item > root = query . from ( Item . class );
query . select ( root );
query . where ( new JsonbAllArrayStringsExistPredicate ( hibernateContext , ( NodeBuilder ) cb , new JsonBExtractPath ( root . get ( "jsonbContent" ), ( NodeBuilder ) cb , singletonList ( "top_element_with_set_of_values" )), tags . toArray ( new String [ 0 ])));
return entityManager . createQuery ( query ). getResultList ();
}Para obtener más detalles, consulte el DAO utilizado en las pruebas.
La "jsonb_extract_path_text" es la función PostgreSQL que devuelve el valor de JSON como el texto apuntado por los elementos de ruta pasados como "texto []" (equivalente al operador #>>). Consulte la documentación de PostgreSQL para obtener más información. A continuación hay un ejemplo para Hibernate 5 de un método que busca elementos que contienen valores de cadena específicos coincidentes por el operador "Like".
public List < Item > findAllByStringValueAndLikeOperator ( String expression ) {
CriteriaBuilder cb = entityManager . getCriteriaBuilder ();
CriteriaQuery < Item > query = cb . createQuery ( Item . class );
Root < Item > root = query . from ( Item . class );
query . select ( root );
query . where ( cb . like ( new JsonBExtractPathText (( CriteriaBuilderImpl ) cb , singletonList ( "string_value" ), root . get ( "jsonbContent" )), expression ));
return entityManager . createQuery ( query ). getResultList ();
}Para el método anterior, Hibernate ejecutará la consulta HQL:
select
generatedAlias0
from
Item as generatedAlias0
where
jsonb_extract_path_text( generatedAlias0 . jsonbContent , :param0 ) like :param1SQL nativo tendrá el siguiente formulario:
select
item0_ . id as id1_0_,
item0_ . jsonb_content as jsonb_co2_0_
from
item item0_
where
jsonb_extract_path_text( item0_ . jsonb_content ,?) like ?Para obtener más detalles y ejemplos con el operador in o cómo usar valores numéricos, verifique el DAO utilizado en las pruebas.
Hibernate 6 Ejemplo :
A continuación hay el mismo ejemplo que el anterior pero para Hibernate 6.
....
public List < Item > findAllByStringValueAndLikeOperator ( String expression ) {
CriteriaBuilder cb = entityManager . getCriteriaBuilder ();
CriteriaQuery < Item > query = cb . createQuery ( Item . class );
Root < Item > root = query . from ( Item . class );
query . select ( root );
query . where ( cb . like ( new JsonBExtractPathText ( root . get ( "jsonbContent" ), singletonList ( "string_value" ), ( NodeBuilder ) cb ), expression ));
return entityManager . createQuery ( query ). getResultList ();
}Para obtener más detalles, consulte el DAO utilizado en las pruebas.
El tipo JSONBallArrayStringSexistPredicate representa un predicado que las verificaciones si se pasan las matrices de cadenas existen en la propiedad de la matriz JSON. El primer ejemplo de este predicado fue introducido en la sección "JSONBEXTROTPATH - JSONB_EXTRACT_PATH". Estos predicados suponen que existe la función SQL con el nombre predeterminado JSONB_ALL_ARRAY_STRINGS_EXIST, mencionada en la sección "Aplicar los cambios DDL". El siguiente ejemplo con una combinación con el operador no presenta elementos que no tienen todas las cadenas buscadas. ¡Ejemplo válido para Hibernate 5 solamente!
public List < Item > findAllThatDoNotMatchByAllMatchingTags ( Set < String > tags ) {
CriteriaBuilder cb = entityManager . getCriteriaBuilder ();
CriteriaQuery < Item > query = cb . createQuery ( Item . class );
Root < Item > root = query . from ( Item . class );
query . select ( root );
Predicate notAllMatchingTags = cb . not ( new JsonbAllArrayStringsExistPredicate ( hibernateContext , ( CriteriaBuilderImpl ) cb , new JsonBExtractPath (( CriteriaBuilderImpl ) cb , singletonList ( "top_element_with_set_of_values" ), root . get ( "jsonbContent" )), tags . toArray ( new String [ 0 ])));
Predicate withoutSetOfValuesProperty = cb . isNull ( new JsonBExtractPath (( CriteriaBuilderImpl ) cb , singletonList ( "top_element_with_set_of_values" ), root . get ( "jsonbContent" )));
query . where ( cb . or ( withoutSetOfValuesProperty , notAllMatchingTags ));
return entityManager . createQuery ( query ). getResultList ();
}Para el método anterior, Hibernate ejecutará la consulta HQL:
select
generatedAlias0
from
Item as generatedAlias0
where
(
jsonb_extract_path( generatedAlias0 . jsonbContent , :param0 ) is null
)
or (
jsonb_all_array_strings_exist( jsonb_extract_path( generatedAlias0 . jsonbContent , :param1 ) , json_function_json_array(:param2, :param3)) = FALSE
)SQL nativo tendrá el siguiente formulario:
select
item0_ . id as id1_0_,
item0_ . jsonb_content as jsonb_co2_0_
from
item item0_
where
jsonb_extract_path( item0_ . jsonb_content ,?) is null
or jsonb_all_array_strings_exist(jsonb_extract_path( item0_ . jsonb_content ,?), array[?,?]) = falseHibernate 6 Ejemplo :
A continuación hay el mismo ejemplo que el anterior pero para Hibernate 6.
public List < Item > findAllThatDoNotMatchByAllMatchingTags ( Set < String > tags ) {
CriteriaBuilder cb = entityManager . getCriteriaBuilder ();
CriteriaQuery < Item > query = cb . createQuery ( Item . class );
Root < Item > root = query . from ( Item . class );
query . select ( root );
Predicate notAllMatchingTags = cb . not ( new JsonbAllArrayStringsExistPredicate ( hibernateContext , ( NodeBuilder ) cb , new JsonBExtractPath ( root . get ( "jsonbContent" ), ( NodeBuilder ) cb , singletonList ( "top_element_with_set_of_values" )), tags . toArray ( new String [ 0 ])));
Predicate withoutSetOfValuesProperty = cb . isNull ( new JsonBExtractPath ( root . get ( "jsonbContent" ), ( NodeBuilder ) cb , singletonList ( "top_element_with_set_of_values" )));
query . where ( cb . or ( withoutSetOfValuesProperty , notAllMatchingTags ));
return entityManager . createQuery ( query ). getResultList ();
}Para obtener más detalles, consulte el DAO utilizado en las pruebas.
El tipo jsonbanyArrayStringsexistPredicate representa un predicado que las verificaciones si se pasan las matrices de cadenas existen en la propiedad de la matriz JSON. Estos predicados suponen que existe la función SQL con el nombre predeterminado JSONB_AY_Array_strings_Exist, mencionado en la sección "Aplicar los cambios DDL". A continuación hay un ejemplo de un método que busca todos los elementos que la propiedad que posee la matriz contiene al menos una cadena pasada de la matriz aprobada como argumento del método. ¡Ejemplo válido para Hibernate 5 solamente!
public List < Item > findAllByAnyMatchingTags ( HashSet < String > tags ) {
CriteriaBuilder cb = entityManager . getCriteriaBuilder ();
CriteriaQuery < Item > query = cb . createQuery ( Item . class );
Root < Item > root = query . from ( Item . class );
query . select ( root );
query . where ( new JsonbAnyArrayStringsExistPredicate ( hibernateContext , ( CriteriaBuilderImpl ) cb , new JsonBExtractPath (( CriteriaBuilderImpl ) cb , singletonList ( "top_element_with_set_of_values" ), root . get ( "jsonbContent" )), tags . toArray ( new String [ 0 ])));
return entityManager . createQuery ( query ). getResultList ();
}Para el método anterior, Hibernate ejecutará la consulta HQL:
select
generatedAlias0
from
Item as generatedAlias0
where
jsonb_any_array_strings_exist( jsonb_extract_path( generatedAlias0 . jsonbContent , :param0 ) , json_function_json_array(:param1, :param2)) = TRUESQL nativo tendrá el siguiente formulario:
select
item0_ . id as id1_0_,
item0_ . jsonb_content as jsonb_co2_0_
from
item item0_
where
jsonb_any_array_strings_exist(jsonb_extract_path( item0_ . jsonb_content ,?), array[?,?]) = trueHibernate 6 Ejemplo :
A continuación hay el mismo ejemplo que el anterior pero para Hibernate 6.
public List < Item > findAllByAnyMatchingTags ( HashSet < String > tags ) {
CriteriaBuilder cb = entityManager . getCriteriaBuilder ();
CriteriaQuery < Item > query = cb . createQuery ( Item . class );
Root < Item > root = query . from ( Item . class );
query . select ( root );
query . where ( new JsonbAnyArrayStringsExistPredicate ( hibernateContext , ( NodeBuilder ) cb , new JsonBExtractPath ( root . get ( "jsonbContent" ), ( NodeBuilder ) cb , singletonList ( "top_element_with_set_of_values" )), tags . toArray ( new String [ 0 ])));
return entityManager . createQuery ( query ). getResultList ();
}Para obtener más detalles y ejemplos con el operador in o cómo usar valores numéricos, verifique el DAO utilizado en las pruebas.
La biblioteca también se puede utilizar para operaciones de modificación JSON. Por defecto, en Hibernate, siempre podemos actualizar una columna con contenido JSON configurando todo su valor. La biblioteca Posjsonhelper también le permite modificar el contenido de JSON configurando, reemplazando o eliminando las propiedades JSON individuales sin reemplazar su contenido completo. La biblioteca contiene varias funciones y operadores de JSON que permiten este tipo de operación.
Envoltura para la función JSONB_SET. La función establece o reemplaza el valor de la propiedad JSON en función de la ruta JSON. Consulte el siguiente ejemplo de cómo se puede usar con el componente CriteriaUpdate:
// GIVEN
Long itemId = 19L ;
String property = "birthday" ;
String value = "1970-01-01" ;
String expectedJson = "{ " child " : { " pets " : [ " dog " ], " birthday " : " 1970-01-01 " }}" ;
// when
CriteriaUpdate < Item > criteriaUpdate = entityManager . getCriteriaBuilder (). createCriteriaUpdate ( Item . class );
Root < Item > root = criteriaUpdate . from ( Item . class );
// Set the property you want to update and the new value
criteriaUpdate . set ( "jsonbContent" , new JsonbSetFunction (( NodeBuilder ) entityManager . getCriteriaBuilder (), root . get ( "jsonbContent" ), new JsonTextArrayBuilder (). append ( "child" ). append ( property ). build (). toString (), JSONObject . quote ( value ), hibernateContext ));
// Add any conditions to restrict which entities will be updated
criteriaUpdate . where ( entityManager . getCriteriaBuilder (). equal ( root . get ( "id" ), itemId ));
// Execute the update
entityManager . createQuery ( criteriaUpdate ). executeUpdate ();
// then
Item item = tested . findById ( itemId );
assertThat (( String ) JsonPath . read ( item . getJsonbContent (), "$.child." + property )). isEqualTo ( value );
JSONObject jsonObject = new JSONObject ( expectedJson );
DocumentContext document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$" ));
assertThat ( document . jsonString ()). isEqualTo ( jsonObject . toString ());Esto generaría la siguiente declaración de actualización de SQL:
update
item
set
jsonb_content = jsonb_set(jsonb_content, ?:: text [], ?::jsonb)
where
id = ?
Hibernate:
select
i1_0 . id ,
i1_0 . jsonb_content
from
item i1_0
where
i1_0 . id = ?La función también se puede usar en las declaraciones HQL, como en el siguiente ejemplo:
@ Transactional
public void updateJsonBySettingPropertyForItemByHQL ( Long itemId , String property , String value ) {
// Execute the update
String hqlUpdate = "UPDATE Item SET jsonbContent = jsonb_set(jsonbContent, %s(:path, 'text[]'), %s(:json, 'jsonb' ) ) WHERE id = :id" . formatted ( hibernateContext . getCastFunctionOperator (), hibernateContext . getCastFunctionOperator ());
int updatedEntities = entityManager . createQuery ( hqlUpdate )
. setParameter ( "id" , itemId )
. setParameter ( "path" , new JsonTextArrayBuilder (). append ( "child" ). append ( property ). build (). toString ())
. setParameter ( "json" , JSONObject . quote ( value ))
. executeUpdate ();
}Envoltura para el operador de concatenación. La envoltura concatene dos valores de JSONB en un nuevo valor JSONB. Consulte el siguiente ejemplo de cómo se puede usar con el componente CriteriaUpdate:
// GIVEN
Long itemId = 19l ;
String property = "birthday" ;
String value = "1970-01-01" ;
// WHEN
CriteriaUpdate < Item > criteriaUpdate = entityManager . getCriteriaBuilder (). createCriteriaUpdate ( Item . class );
Root < Item > root = criteriaUpdate . from ( Item . class );
JSONObject jsonObject = new JSONObject ();
jsonObject . put ( "child" , new JSONObject ());
jsonObject . getJSONObject ( "child" ). put ( property , value );
criteriaUpdate . set ( "jsonbContent" , new ConcatenateJsonbOperator (( NodeBuilder ) entityManager . getCriteriaBuilder (), root . get ( "jsonbContent" ), jsonObject . toString (), hibernateContext ));
criteriaUpdate . where ( entityManager . getCriteriaBuilder (). equal ( root . get ( "id" ), itemId ));
entityManager . createQuery ( criteriaUpdate ). executeUpdate ();
// THEN
Item item = tested . findById ( itemId );
assertThat (( String ) JsonPath . read ( item . getJsonbContent (), "$.child." + property )). isEqualTo ( value );
JSONObject expectedJsonObject = new JSONObject (). put ( property , value );
DocumentContext document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$.child" ));
assertThat ( document . jsonString ()). isEqualTo ( expectedJsonObject . toString ());Esto generaría la siguiente declaración de actualización de SQL:
update
item
set
jsonb_content = jsonb_content || ?::jsonb
where
id = ?
Hibernate:
select
i1_0 . id ,
i1_0 . jsonb_content
from
item i1_0
where
i1_0 . id = ?La función también se puede usar en las declaraciones HQL, como en el siguiente ejemplo:
@ Transactional
public void updateJsonPropertyForItemByHQL ( Long itemId , String property , String value ) throws JSONException {
JSONObject jsonObject = new JSONObject ();
jsonObject . put ( "child" , new JSONObject ());
jsonObject . getJSONObject ( "child" ). put ( property , value );
String hqlUpdate = "UPDATE Item SET jsonbContent = %s(jsonbContent, %s(:json, 'jsonb' ) ) WHERE id = :id" . formatted ( hibernateContext . getConcatenateJsonbOperator (), hibernateContext . getCastFunctionOperator ());
int updatedEntities = entityManager . createQuery ( hqlUpdate )
. setParameter ( "id" , itemId )
. setParameter ( "json" , jsonObject . toString ())
. executeUpdate ();
}Envoltura para el operador de eliminación '#-'. El contenedor elimina el campo o el elemento de matriz en función del índice en la ruta especificada, donde los elementos de ruta pueden ser teclas de campo o índices de matriz. Consulte el siguiente ejemplo de cómo se puede usar con el componente CriteriaUpdate:
// GIVEN
Item item = tested . findById ( 19L );
JSONObject jsonObject = new JSONObject ( "{ " child " : { " pets " : [ " dog " ]}}" );
DocumentContext document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$" ));
assertThat ( document . jsonString ()). isEqualTo ( jsonObject . toString ());
// WHEN
CriteriaUpdate < Item > criteriaUpdate = entityManager . getCriteriaBuilder (). createCriteriaUpdate ( Item . class );
Root < Item > root = criteriaUpdate . from ( Item . class );
// Set the property you want to update and the new value
criteriaUpdate . set ( "jsonbContent" , new DeleteJsonbBySpecifiedPathOperator (( NodeBuilder ) entityManager . getCriteriaBuilder (), root . get ( "jsonbContent" ), new JsonTextArrayBuilder (). append ( "child" ). append ( "pets" ). build (). toString (), hibernateContext ));
// Add any conditions to restrict which entities will be updated
criteriaUpdate . where ( entityManager . getCriteriaBuilder (). equal ( root . get ( "id" ), 19L ));
// Execute the update
entityManager . createQuery ( criteriaUpdate ). executeUpdate ();
// THEN
entityManager . refresh ( item );
jsonObject = new JSONObject ( "{ " child " : {}}" );
document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$" ));
assertThat ( document . jsonString ()). isEqualTo ( jsonObject . toString ());Esto generaría la siguiente declaración de actualización de SQL:
update
item
set
jsonb_content = (jsonb_content # - ?::text[])
where
id = ?La función también se puede usar en las declaraciones HQL, como en el siguiente ejemplo:
@ Transactional
public void updateJsonByDeletingSpecificPropertyForItemByHql ( Long itemId , String property ) {
// Execute the update
String hqlUpdate = "UPDATE Item SET jsonbContent = %s(jsonbContent, %s(:path, 'text[]') ) WHERE id = :id" . formatted ( hibernateContext . getDeleteJsonBySpecificPathOperator (), hibernateContext . getCastFunctionOperator ());
int updatedEntities = entityManager . createQuery ( hqlUpdate )
. setParameter ( "id" , itemId )
. setParameter ( "path" , new JsonTextArrayBuilder (). append ( "child" ). append ( property ). build (). toString ())
. executeUpdate ();
}El tipo de eliminación del tipo de Function de Media es un operador hibernado que invoca la función SQL generada por la biblioteca Posjsonhelper. Por defecto, la función generada se parece al siguiente ejemplo:
CREATE OR REPLACE FUNCTION {{schema}}.remove_values_from_json_array(input_json jsonb, values_to_remove jsonb) RETURNS jsonb AS $$
DECLARE
result jsonb;
BEGIN
IF jsonb_typeof(values_to_remove) <> ' array ' THEN
RAISE EXCEPTION ' values_to_remove must be a JSON array ' ;
END IF;
result : = (
SELECT jsonb_agg(element)
FROM jsonb_array_elements(input_json) AS element
WHERE NOT (element IN ( SELECT jsonb_array_elements(values_to_remove)))
);
RETURN COALESCE(result, ' [] ' ::jsonb);
END;
$$ LANGUAGE plpgsql;La función tiene dos parámetros de entrada. Primero está la matriz JSON, que es una matriz base para el resultado que la función volverá. El segundo parámetro también es una matriz JSON que representa un elemento que debe eliminarse de la matriz de resultados. A continuación se muestra un ejemplo de código de cómo esta función se puede usar con otro operador para actualizar las columnas JSON con la instrucción SQL Actualy.
// GIVEN
Item item = tested . findById ( 24L );
DocumentContext document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$" ));
assertThat ( document . jsonString ()). isEqualTo ( "{ " child " :{ " pets " :[ " crab " , " chameleon " ]}, " inventory " :[ " mask " , " fins " , " compass " ]}" );
CriteriaUpdate < Item > criteriaUpdate = entityManager . getCriteriaBuilder (). createCriteriaUpdate ( Item . class );
Root < Item > root = criteriaUpdate . from ( Item . class );
NodeBuilder nodeBuilder = ( NodeBuilder ) entityManager . getCriteriaBuilder ();
JSONArray toRemoveJSONArray = new JSONArray ( Arrays . asList ( "mask" , "compass" ));
RemoveJsonValuesFromJsonArrayFunction deleteOperator = new RemoveJsonValuesFromJsonArrayFunction ( nodeBuilder , new JsonBExtractPath ( root . get ( "jsonbContent" ), nodeBuilder , Arrays . asList ( "inventory" )), toRemoveJSONArray . toString (), hibernateContext );
JsonbSetFunction jsonbSetFunction = new JsonbSetFunction ( nodeBuilder , ( SqmTypedNode ) root . get ( "jsonbContent" ), new JsonTextArrayBuilder (). append ( "inventory" ). build (). toString (), deleteOperator , hibernateContext );
// Set the property you want to update and the new value
criteriaUpdate . set ( "jsonbContent" , jsonbSetFunction );
// Add any conditions to restrict which entities will be updated
criteriaUpdate . where ( entityManager . getCriteriaBuilder (). equal ( root . get ( "id" ), 24L ));
// WHEN
entityManager . createQuery ( criteriaUpdate ). executeUpdate ();
// THEN
entityManager . refresh ( item );
document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$" ));
assertThat ( document . jsonString ()). isEqualTo ( "{ " child " :{ " pets " :[ " crab " , " chameleon " ]}, " inventory " :[ " fins " ]}" );El mismo ejemplo pero con el ejemplo de la consulta HQL:
// GIVEN
Item item = tested . findById ( 24L );
DocumentContext document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$" ));
assertThat ( document . jsonString ()). isEqualTo ( "{ " child " :{ " pets " :[ " crab " , " chameleon " ]}, " inventory " :[ " mask " , " fins " , " compass " ]}" );
CriteriaUpdate < Item > criteriaUpdate = entityManager . getCriteriaBuilder (). createCriteriaUpdate ( Item . class );
Root < Item > root = criteriaUpdate . from ( Item . class );
JSONArray toRemoveJSONArray = new JSONArray ( Arrays . asList ( "mask" , "compass" ));
String hqlUpdate = "UPDATE Item SET jsonbContent = %s(jsonbContent, %s(:path, 'text[]'), %s(jsonb_extract_path( jsonbContent , 'inventory' ), %s(:to_remove, 'jsonb')) ) WHERE id = :id" . formatted ( JSONB_SET_FUNCTION_NAME , hibernateContext . getCastFunctionOperator (), hibernateContext . getRemoveJsonValuesFromJsonArrayFunction (), hibernateContext . getCastFunctionOperator ());
// WHEN
entityManager . createQuery ( hqlUpdate )
. setParameter ( "id" , 24L )
. setParameter ( "path" , new JsonTextArrayBuilder (). append ( "inventory" ). build (). toString ())
. setParameter ( "to_remove" , toRemoveJSONArray . toString ())
. executeUpdate ();
// THEN
entityManager . refresh ( item );
document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$" ));
assertThat ( document . jsonString ()). isEqualTo ( "{ " child " :{ " pets " :[ " crab " , " chameleon " ]}, " inventory " :[ " fins " ]}" );Esos dos ejemplos generarán a continuación la declaración SQL:
update
item
set
jsonb_content = jsonb_set(jsonb_content, ?:: text [], remove_values_from_json_array(jsonb_extract_path(jsonb_content, ?), ?::jsonb))
where
id = ?El uso de una sola función JSONB_SET para establecer una sola propiedad para JSON con una sola instrucción de actualización puede ser útil, sin embargo, puede ser más útil poder establecer múltiples propiedades en diferentes niveles del árbol JSON con una sola instrucción de actualización.
Para no verificar el ejemplo del código:
// GIVEN
Item item = tested . findById ( 23L );
DocumentContext document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$" ));
assertThat ( document . jsonString ()). isEqualTo ( "{ " child " :{ " pets " :[ " dog " ]}, " inventory " :[ " mask " , " fins " ], " nicknames " :{ " school " : " bambo " , " childhood " : " bob " }}" );
CriteriaUpdate < Item > criteriaUpdate = entityManager . getCriteriaBuilder (). createCriteriaUpdate ( Item . class );
Root < Item > root = criteriaUpdate . from ( Item . class );
Hibernate6JsonUpdateStatementBuilder hibernate6JsonUpdateStatementBuilder = new Hibernate6JsonUpdateStatementBuilder ( root . get ( "jsonbContent" ), ( NodeBuilder ) entityManager . getCriteriaBuilder (), hibernateContext );
hibernate6JsonUpdateStatementBuilder . appendJsonbSet ( new JsonTextArrayBuilder (). append ( "child" ). append ( "birthday" ). build (), quote ( "2021-11-23" ));
hibernate6JsonUpdateStatementBuilder . appendJsonbSet ( new JsonTextArrayBuilder (). append ( "child" ). append ( "pets" ). build (), "[ " cat " ]" );
hibernate6JsonUpdateStatementBuilder . appendDeleteBySpecificPath ( new JsonTextArrayBuilder (). append ( "inventory" ). append ( "0" ). build ());
hibernate6JsonUpdateStatementBuilder . appendJsonbSet ( new JsonTextArrayBuilder (). append ( "parents" ). append ( 0 ). build (), "{ " type " : " mom " , " name " : " simone " }" );
hibernate6JsonUpdateStatementBuilder . appendJsonbSet ( new JsonTextArrayBuilder (). append ( "parents" ). build (), "[]" );
hibernate6JsonUpdateStatementBuilder . appendDeleteBySpecificPath ( new JsonTextArrayBuilder (). append ( "nicknames" ). append ( "childhood" ). build ());
// Set the property you want to update and the new value
criteriaUpdate . set ( "jsonbContent" , hibernate6JsonUpdateStatementBuilder . build ());
// Add any conditions to restrict which entities will be updated
criteriaUpdate . where ( entityManager . getCriteriaBuilder (). equal ( root . get ( "id" ), 23L ));
// WHEN
entityManager . createQuery ( criteriaUpdate ). executeUpdate ();
// THEN
entityManager . refresh ( item );
document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$" ));
assertThat ( document . jsonString ()). isEqualTo ( "{ " child " :{ " pets " :[ " cat " ], " birthday " : " 2021-11-23 " }, " parents " :[{ " name " : " simone " , " type " : " mom " }], " inventory " :[ " fins " ], " nicknames " :{ " school " : " bambo " }}" );En el código anterior, queremos establecer tres propiedades JSON "Child.birthday", "Child.pets" y "Padres" y eliminar otros dos, "Inventory.0" y "Nicknames.Childhood". La propiedad de "padres" es una nueva propiedad que se supone que es una matriz. Aunque la configuración de una nueva propiedad de matriz con algunos valores podría realizarse con una operación única, sin embargo, para fines de demostración usamos dos operaciones. Una es para establecer una nueva propiedad llamada "Padres" con una matriz JSON vacía como valor. Y otra operación que estableció un elemento de una matriz en un índice específico. Si no existe una propiedad más alta, entonces debe crearse antes de las propiedades internas. Afortunadamente, la instancia predeterminada del tipo Hibernate6JSONUPDateStatementBuilder tiene componentes de clasificación y filtrado adecuados para ayudarlo a establecer el orden correcto de operaciones. Por lo tanto, no importa si agregamos la operación de elemento de matriz adicional antes o después de agregar la operación de matriz de creación. Por defecto, las operaciones que eliminan el contenido se agregarán antes de las que agregan o reemplazan el contenido. Por supuesto, es posible deshabilitar este comportamiento estableciendo estos componentes en NULL. Para obtener más detalles, consulte Javadoc para ver el tipo de Hibernate6JSONUPDateStatementBuilder.
Este código genera a continuación la declaración SQL:
update
item
set
jsonb_content =
jsonb_set(
jsonb_set(
jsonb_set(
jsonb_set(
(
(jsonb_content # - ?::text[]) -- the most nested #- operator
# - ?::text[])
, ?:: text [], ?::jsonb) -- the most nested jsonb_set operation
, ?:: text [], ?::jsonb)
, ?:: text [], ?::jsonb)
, ?:: text [], ?::jsonb)
where
id = ?La ejecución de la función JSONB_SET más interna para esta declaración preparada establecerá una matriz vacía para la propiedad "Padres".
El constructor tiene métodos para establecer valores:
Eliminación de propiedades:
appendDeleteBySpecificPath (JSontextArray JSontextArray)
Agregar elementos de matriz
Eliminar elementos de matriz
Algunos métodos relacionados con la modificación en la matriz JSON por defecto requieren la biblioteca org.json.json (verifique las dependencias opcionales). Sin embargo, es posible aprobar la implementación personalizada de la interfaz que mapea el objeto de recolección al valor de la matriz JSON con "WithCollectionToJsonArrayStringMapper (com.github.starnowski.posjsonhelper.Hibernate6.Hibernate6JsonupDatementBuilder.CollectionToJsonArraystringMapper)" Builder Method Method Method Methodicser) "Builder Method Methodicser Butilder)" Builder.
El tipo Hibernate6JSONUPDatEtatementBuilder es genérico. Un segundo tipo genérico es un valor personalizado que se puede agregar al contexto Hibernate6JSONUPDateStatementBuilder. A continuación se muestra un ejemplo de código cuyo tipo representa las operaciones de matriz (elementos que deben agregarse y eliminarse de una matriz).
Tipo de valor personalizado:
private static class JsonArrayOperations {
private final List < String > toDelete ;
private final List < String > toAdd ;
public JsonArrayOperations ( List < String > toDelete , List < String > toAdd ) {
this . toDelete = toDelete ;
this . toAdd = toAdd ;
}
public List < String > getToDelete () {
return toDelete ;
}
public List < String > getToAdd () {
return toAdd ;
}
}Ejemplo de uso:
// GIVEN
Item item = tested . findById ( 24L );
DocumentContext document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$" ));
assertThat ( document . jsonString ()). isEqualTo ( "{ " child " :{ " pets " :[ " crab " , " chameleon " ]}, " inventory " :[ " mask " , " fins " , " compass " ]}" );
CriteriaUpdate < Item > criteriaUpdate = entityManager . getCriteriaBuilder (). createCriteriaUpdate ( Item . class );
Root < Item > root = criteriaUpdate . from ( Item . class );
Hibernate6JsonUpdateStatementBuilder < Object , JsonArrayOperations > hibernate6JsonUpdateStatementBuilder = new Hibernate6JsonUpdateStatementBuilder ( root . get ( "jsonbContent" ), ( NodeBuilder ) entityManager . getCriteriaBuilder (), hibernateContext );
hibernate6JsonUpdateStatementBuilder . appendJsonbSet ( new JsonTextArrayBuilder (). append ( "child" ). append ( "pets" ). build (), null , new JsonArrayOperations ( Arrays . asList ( "crab" , "ant" ), Arrays . asList ( "lion" , "dolphin" )));
hibernate6JsonUpdateStatementBuilder . appendJsonbSet ( new JsonTextArrayBuilder (). append ( "name" ). build (), JSONObject . quote ( "Simon" ));
hibernate6JsonUpdateStatementBuilder . appendJsonbSet ( new JsonTextArrayBuilder (). append ( "inventory" ). build (), null , new JsonArrayOperations ( Arrays . asList ( "compass" , "mask" ), Arrays . asList ( "knife" )));
hibernate6JsonUpdateStatementBuilder . withJsonbSetFunctionFactory ( new Hibernate6JsonUpdateStatementBuilder . DefaultJsonbSetFunctionFactory < Object , JsonArrayOperations >() {
public JsonbSetFunction build ( NodeBuilder nodeBuilder , Path < Object > rootPath , JsonUpdateStatementConfiguration . JsonUpdateStatementOperation < JsonArrayOperations > operation , HibernateContext hibernateContext ) {
if ( operation . getCustomValue () != null ) {
JSONArray toAddJSONArray = new JSONArray ( operation . getCustomValue (). getToAdd ());
ConcatenateJsonbOperator concatenateOperator = new ConcatenateJsonbOperator ( nodeBuilder , new JsonBExtractPath ( rootPath , nodeBuilder , operation . getJsonTextArray (). getPath (). stream (). map ( ob -> ob . toString ()). collect ( Collectors . toList ())), toAddJSONArray . toString (), hibernateContext );
JSONArray toRemoveJSONArray = new JSONArray ( operation . getCustomValue (). getToDelete ());
RemoveJsonValuesFromJsonArrayFunction deleteOperator = new RemoveJsonValuesFromJsonArrayFunction ( nodeBuilder , concatenateOperator , toRemoveJSONArray . toString (), hibernateContext );
return new JsonbSetFunction ( nodeBuilder , ( SqmTypedNode ) rootPath , operation . getJsonTextArray (). toString (), deleteOperator , hibernateContext );
} else {
return super . build ( nodeBuilder , rootPath , operation , hibernateContext );
}
}
@ Override
public JsonbSetFunction build ( NodeBuilder nodeBuilder , SqmTypedNode sqmTypedNode , JsonUpdateStatementConfiguration . JsonUpdateStatementOperation < JsonArrayOperations > operation , HibernateContext hibernateContext ) {
if ( operation . getCustomValue () != null ) {
JSONArray toAddJSONArray = new JSONArray ( operation . getCustomValue (). getToAdd ());
ConcatenateJsonbOperator concatenateOperator = new ConcatenateJsonbOperator ( nodeBuilder , new JsonBExtractPath ( root . get ( "jsonbContent" ), nodeBuilder , operation . getJsonTextArray (). getPath (). stream (). map ( ob -> ob . toString ()). collect ( Collectors . toList ())), toAddJSONArray . toString (), hibernateContext );
JSONArray toRemoveJSONArray = new JSONArray ( operation . getCustomValue (). getToDelete ());
RemoveJsonValuesFromJsonArrayFunction deleteOperator = new RemoveJsonValuesFromJsonArrayFunction ( nodeBuilder , concatenateOperator , toRemoveJSONArray . toString (), hibernateContext );
return new JsonbSetFunction ( nodeBuilder , sqmTypedNode , operation . getJsonTextArray (). toString (), deleteOperator , hibernateContext );
} else {
return super . build ( nodeBuilder , sqmTypedNode , operation , hibernateContext );
}
}
});
// Set the property you want to update and the new value
criteriaUpdate . set ( "jsonbContent" , hibernate6JsonUpdateStatementBuilder . build ());
// Add any conditions to restrict which entities will be updated
criteriaUpdate . where ( entityManager . getCriteriaBuilder (). equal ( root . get ( "id" ), 24L ));
// WHEN
entityManager . createQuery ( criteriaUpdate ). executeUpdate ();
// THEN
entityManager . refresh ( item );
document = JsonPath . parse (( Object ) JsonPath . read ( item . getJsonbContent (), "$" ));
assertThat ( document . jsonString ()). isEqualTo ( "{ " name " : " Simon " , " child " :{ " pets " :[ " chameleon " , " lion " , " dolphin " ]}, " inventory " :[ " fins " , " knife " ]}" );| Nombre de propiedad | Descripción |
|---|---|
| com.github.starnowski.posjsonhelper.core.functions.jsonb_all_array_strings_exist | Nombre de la función SQL que verifica si todos los elementos aprobados como el texto [] existen en la propiedad de la matriz JSON. Por defecto, el nombre es JSONB_ALL_Array_strings_Exist |
| com.github.starnowski.posjsonhelper.core.functions.jsonb_any_array_strings_exist | Nombre de la función SQL que verifica si alguno de los elementos aprobados ya que el texto [] existe en la propiedad de la matriz JSON. Por defecto, el nombre es JSONB_Any_Array_strings_Exist |
| com.github.starnowski.posjsonhelper.core.functions.remove_values_from_json_array | Nombre de la función SQL que devuelve la matriz JSONB al eliminar elementos de la matriz JSONB pasó como entrada para la función. Por defecto, el nombre es el remove_values_from_json_array |
| com.github.starnowski.posjsonhelper.core.schema | Nombre del esquema de la base de datos donde se deben crear las funciones SQL |
| com.github.starnowski.posjsonhelper.core.hibernate.functions.jsonb_all_array_strings_exist | Nombre de la función HQL que invoca la función SQL especificada por el com.github.starnowski.posjsonhelper.core.functions.jsonb_all_array_strings_exist. Por defecto, el nombre es JSONB_ALL_Array_strings_Exist |
| com.github.starnowski.posjsonhelper.core.hibernate.functions.jsonb_any_array_strings_exist | Nombre de la función HQL que invoca la función SQL especificada por el com.github.starnowski.posjsonhelper.core.functions.jsonb_any_array_strings_exist. Por defecto, el nombre es JSONB_Any_Array_strings_Exist |
| com.github.starnowski.posjsonhelper.core.hibernate.functions.json_function_json_array | Nombre de la función HQL que envuelve el operador de matriz en PostgreSQL. Por defecto, el nombre es el json_function_json_array |
| com.github.starnowski.posjsonhelper.core.hibernate.functions.remove_values_from_json_array | Nombre de la función HQL que envuelve la función que devuelve la matriz JSONB al eliminar elementos de la matriz JSONB pasó como entrada para la función. Por defecto, el nombre es el remove_values_from_json_array |
| com.github.starnowski.posjsonhelper.core.hibernate.functions.sqlDefinitionContextFactory.types | Propiedad del sistema que almacena la lista de com.github.starnowski.posjsonhelper.core.sql.isqlDefinitionContextFactory tipos que deben cargarse. En lugar de cargar tipos que se pueden encontrar en el ClassPath para el paquete "com.github.starnowski.posjsonhelper". Los tipos en la lista están separados por el carácter de coma ".". |
| com.github.starnowski.posjsonhelper.Hibernate6.FunctionDescriptorRegisterFactory.Types | (Se usa solo en la propiedad del sistema Hibernate 6) que almacena la lista de com.github.starnowski.posjsonhelper.Hibernate6.descriptor.functionDescriptorRegisterFactorIessupplier tipos que deben cargarse. En lugar de cargar tipos que se pueden encontrar en el ClassPath para el paquete "com.github.starnowski.posjsonhelper". Los tipos en la lista están separados por el carácter de coma ".". |
| com.github.starnowski.posjsonhelper.Hibernate6.FunctionDescriptorRegisterFactory.Types.excluded | (Se usa solo en la propiedad del sistema Hibernate 6) que almacena la lista de com.github.starnowski.posjsonhelper.Hibernate6.descriptor.functionDescriptorRegisterFactoriessupplier tipos que deben excluir la carga. Si "com.github.starnowski.posjsonhelper.hibernate6.functionDescriptorRegisterFactory.types" también se especifica luego "com.github.sternowski.posjsonhelper.hibernate6.functionDescriptorgisterFactory.types.types.types.sexclar" tiene prioridad. Ha priorizado. Los tipos en la lista están separados por el carácter de coma ".". |
Matriz de compatibilidad con Hibernate 6.
| Posjsonhelper | Hibernate 6 |
|---|---|
| 0.3.0 | 6.4.0. final |
| 0.2.0 - 0.2.1 | 6.1.5. Final |
Problema con paquete, versión o clases de hibernación, etc.
Si enfrenta un problema relacionado con la definición o tipo de método faltante como por ejemplo:
java.lang.NoSuchMethodError: 'org.hibernate.query.criteria.JpaExpression
Luego, primero, verifique si su proyecto tiene biblioteca de núcleo hibernado en classpath. El núcleo hibernado es una dependencia opcional para este proyecto y debe asegurarse de que se haya agregado en su proyecto. Consulte el problema similar 145. Si su núcleo hibernado está en classpath y el problema aún existe, informe, por favor informe.