PosjsonHelper Library는 PostgreSQL JSON 기능에 대한 최대 절전 모드 쿼리 지원을 추가하는 오픈 소스 프로젝트입니다. 도서관은 또한 PostgreSQL 텍스트 검색 기능을 지원합니다. 텍스트 검색 구성 요소를 사용하는 방법에 대한 자세한 내용은 텍스트 모듈에 대한 지침을 확인하십시오. 도서관은 Java 프로그래밍 언어로 작성되었습니다. 이 순간에 대한 프로젝트는 버전 5 및 6의 최대 절전 모드를 지원합니다. Java의 필요한 버전은 최소한의 최소한 버전 8입니다.
이 프로젝트는 Central Maven 저장소에서 제공됩니다. 프로젝트 디스크립터 파일 (pom.xml)의 종속성으로 추가하여 사용할 수 있습니다.
최대 절전 모드 5 :
< dependency >
< groupId >com.github.starnowski.posjsonhelper</ groupId >
< artifactId >hibernate5</ artifactId >
< version >0.4.2</ version >
</ dependency >최대 절전 모드 6 :
< dependency >
< groupId >com.github.starnowski.posjsonhelper</ groupId >
< artifactId >hibernate6</ artifactId >
< version >0.4.2</ version >
</ dependency >PosjsonHelper 라이브러리는 최대 절전 모드에 일시적인 의존성이 없습니다. 따라서 다음과 같이 프로젝트에 최대 절전 모드 의존성을 별도로 추가해야합니다.
< dependency >
< groupId >org.hibernate</ groupId >
< artifactId >hibernate-core</ artifactId >
< version >????</ version >
</ dependency >최대 절전 모드 호환성 버전 매트릭스를 확인하여 올바른 버전을 확인하십시오.
JSON 작업과 관련된 일부 기능에 대한 기본 구현에는 org.json : json library가 필요합니다. 그러나 특정 인터페이스를 구현하는 방법이 있으며 라이브러리 아래에는 추가 할 필요가 없습니다.
< dependency >
< groupId >org.json</ groupId >
< artifactId >json</ artifactId >
< version >20240303</ version >
</ dependency >누군가가 소스에서 로컬로 프로젝트를 구축하려면 Contributing.md 파일을 참조하여 프로젝트를 로컬로 설정하는 방법을 확인하십시오.
중요한! 이 섹션은 Hibernate 5에만 유효합니다. 프로젝트에서 PosjsonHelper 라이브러리를 사용할 수 있으려면 정확한 최대 절전 모드 방언이 지정되어 있어야합니다. 도서관은 이미 존재하는 래퍼가 거의 없음을 구현합니다.
방언은 예를 들어 최대 절전 모드 구성 파일로 설정해야합니다.
<? 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 >
...또는 예를 들어 Spring Framework 구성 속성 파일 :
...
spring.jpa.properties.hibernate.dialect =com.github.starnowski.posjsonhelper.hibernate5.dialects.PostgreSQL95DialectWrapper
...최대 절전 모드 방언 유형을 확장하는 유형이있는 경우 프로젝트에 필요한 경우. 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 );
}
}중요한! 이 섹션은 Hibernate 6에만 유효합니다. Hibernate 6을 사용하는 프로젝트에서 PosjsonHelper 라이브러리를 사용하려면 지정된 org.hibernate.boot.model.functionContributor 구현이 있어야합니다. 라이브러리에는이 인터페이스 (com.github.starnowski.posjsonhelper.hibernate6.posjsonHelperFunctionContribor)가 구현됩니다.
이 구현을 사용하려면 "org.hibernate.boot.model.functioncontribor" "resources/meta-inf/services"디렉토리의 이름으로 파일을 만들어야합니다.
대체 솔루션은 응용 프로그램 시작 중에 com.github.starnowski.posjsonhelper.hibernate6.sqmfunctionregistryenricher 구성 요소를 사용하는 것입니다. 스프링 프레임 워크 사용과 함께 아래 예제에서와 마찬가지로.
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 ());
}
}PosjsonHelper 라이브러리를 사용하려면 JSON 연산자를 실행하는 몇 가지 SQL 기능을 작성해야합니다. 일부 JSON 운영자는 탈출해야하므로 최대 절전 모드로 실행할 수 없습니다. 기본 구성의 경우 라이브러리는 아래 기능을 작성해야합니다.
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;생성 된 DDL 문은 통합 테스트 중에 실행되거나 Liquibase 또는 Flyway와 같은 데이터베이스에 변경 사항을 적용하는 도구에서 사용할 수 있습니다. 중요한! 유사한 기능을 사용해야하지만 이름이 다른 경우 응용 프로그램 속성에 지정해야합니다. [ "PostgreSQL 방언을 첨부하는 방법"] (#how-to-attach-postgresql dialect) 섹션에서는 응용 프로그램 컨텍스트 (IOC)에 액세스 할 수 없을 수 있습니다. 그러나 그러한 속성이 다른 방식으로 전달되어야하는 경우 PostgreSqlDialeCtenRicher 유형에는 컨텍스트 객체를 전달하는 방법도 있습니다 (핵심 컨텍스트를 확인하고 최대 절전 모드 컨텍스트를 확인하십시오).
Context Class는 라이브러리에서 사용하는 기능 이름을 보유합니다. 방언 클래스는 시스템 속성을 기반으로 컨텍스트 객체를 생성하는 CoreconTextProperTiessUpplier 구성 요소를 사용합니다.
DatabaseOperationExecutorFacade 유형을 사용하여 프로그래밍 방식으로 DDL을 추가하는 것도 가능합니다. 아래에는 스프링 프레임 워크 컨텍스트로 응용 프로그램에 DDL 변경 사항을 적용하는 방법에 대한 예가 있습니다.
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 );
}
}
}DatabaseOperationExecutorFacade 객체에서 실행할 수있는 몇 가지 작업이 있습니다.
| 속성 이름 | 설명 |
|---|---|
| 만들다 | 데이터베이스에 DDL 변경을 적용합니다 |
| 검증 | DDL 변경이 데이터베이스에 적용되는지 확인합니다 |
| 떨어지다 | 데이터베이스의 DDL 변경을 삭제합니다 |
| log_all | 작업을 작성, 검증 및 삭제하기위한 DDL 스크립트를 표시합니다 |
더 쉬운 설명을 위해 JSONB 유형을 저장하는 하나의 열이있는 데이터베이스 테이블이 있다고 가정 해 봅시다.
create table item (
id int8 not null ,
jsonb_content jsonb,
primary key (id)
)이 테이블의 경우 아래의 예와 같이 JSON과 함께 행을 삽입 할 수 있습니다.
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"} ' );대부분의 술어 구성 요소는 최대 절전 모드 컨텍스트 객체를 사용합니다. 주로 프로젝트에 사용 된 최대 절전 모드 기능 이름의 이름을 가지고 있습니다. 방언 클래스 및 FunctionContripor 유형은 시스템 속성을 기반으로 HiberNateContext 객체를 생성하는 HiberNateContextProperTiessUpplier 구성 요소를 사용합니다. PSOJSONHELPER 연산자의 기본 HQL 기능 이름을 변경할 필요가없는 경우 아래와 같이 빌더 구성 요소에서 만든 HiberNateContext를 사용하는 것도 다음과 같습니다.
HibernateContext hibernateContext = HibernateContext . builder (). build ();"jsonb_extract_path"는 "text []"( #> 연산자와 동일)로 전달 된 경로 요소로 가리키는 JSONB 값을 반환하는 PostgreSQL 함수입니다. 많은 함수가 실행에 "jsonb"유형을 사용하기 때문에 유용합니다. 자세한 내용은 PostgreSQL 문서를 확인하십시오. Hibernate 5 예 : 아래에는 JSON 컨텐츠 속성 "top_element_with_set_of_values"에 정확한 값 세트가 포함 된 항목 객체 목록을 반환하는 메소드의 예가 있습니다. 이 예제는 jsonballarraystringsexistPredicate를 사용합니다.
@ 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 ();
}위의 방법의 경우 Hibernate는 HQL 쿼리를 실행합니다.
select
generatedAlias0
from
Item as generatedAlias0
where
jsonb_all_array_strings_exist( jsonb_extract_path( generatedAlias0 . jsonbContent , :param0 ) , json_function_json_array(:param1)) = TRUE네이티브 SQL은 아래 양식을 갖습니다.
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[?]) = true자세한 내용은 테스트에 사용 된 DAO를 확인하십시오.
최대 절전 모드 6 예 :
아래에는 위와 동일한 예가 있지만 최대 절전 모드 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 ();
}자세한 내용은 테스트에 사용 된 DAO를 확인하십시오.
"jsonb_extract_path_text"는 "text []"( #>> 연산자와 동일)로 전달 된 경로 요소에 의해 텍스트를 가리키면 JSON 값을 반환하는 PostgreSQL 함수입니다. 자세한 내용은 PostgreSQL 문서를 확인하십시오. 아래에는 "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 ();
}위의 방법의 경우 Hibernate는 HQL 쿼리를 실행합니다.
select
generatedAlias0
from
Item as generatedAlias0
where
jsonb_extract_path_text( generatedAlias0 . jsonbContent , :param0 ) like :param1네이티브 SQL은 아래 양식을 갖습니다.
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 ?IN 연산자와의 자세한 내용 및 예제 또는 숫자 값을 사용하는 방법은 테스트에 사용 된 DAO를 확인하십시오.
최대 절전 모드 6 예 :
아래에는 위와 동일한 예가 있지만 최대 절전 모드 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 ();
}자세한 내용은 테스트에 사용 된 DAO를 확인하십시오.
JSONBALLARRAYSTRINGEXISTPREDICAT 유형은 통과 된 문자열 배열이 JSON 어레이 속성에 존재하는지 확인한다는 술어를 나타냅니다. 이 술어에 대한 첫 번째 예는 "JSONBEXTRASTPATH -JSONB_EXTRANT_PATH"섹션에 소개했습니다. 이들은 "기본 이름 JSONB_ALL_ARRAY_STRINGS_EXIST의 SQL 기능이"DDL 변경 사항 적용 "섹션에 언급 된 것으로 가정합니다. 연산자와의 조합이있는 아래 예제는 검색 된 문자열이없는 항목을 제시하지 않습니다. 최대 절전 모드 5에만 유효합니다!
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 ();
}위의 방법의 경우 Hibernate는 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은 아래 양식을 갖습니다.
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[?,?]) = false최대 절전 모드 6 예 :
아래에는 위와 동일한 예가 있지만 최대 절전 모드 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 ();
}자세한 내용은 테스트에 사용 된 DAO를 확인하십시오.
JSONBANYARRAYSTRINGEXISTPREDICAT 유형은 전달 된 문자열 배열이 JSON 어레이 속성에 존재하는지 확인하는 술어를 나타냅니다. 이들은 "기본 이름 JSONB_ANY_ARRAY_STRINGS_EXIST의 SQL 함수가"DDL 변경 사항 적용 "섹션에 언급 된 것으로 가정합니다. 아래에는 배열을 보유하는 속성에 대한 모든 항목을 찾는 메소드의 예가 있습니다. 최대 절전 모드 5에만 유효합니다!
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 ();
}위의 방법의 경우 Hibernate는 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)) = TRUE네이티브 SQL은 아래 양식을 갖습니다.
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[?,?]) = true최대 절전 모드 6 예 :
아래에는 위와 동일한 예가 있지만 최대 절전 모드 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 ();
}IN 연산자와의 자세한 내용 및 예제 또는 숫자 값을 사용하는 방법은 테스트에 사용 된 DAO를 확인하십시오.
라이브러리는 JSON 수정 작업에도 사용될 수 있습니다. 기본적으로 최대 절전 모드에서는 전체 값을 설정하여 항상 JSON 컨텐츠로 열을 업데이트 할 수 있습니다. PosjsonHelper 라이브러리를 사용하면 전체 컨텐츠를 교체하지 않고 개별 JSON 속성을 설정, 교체 또는 제거하여 JSON 컨텐츠를 수정할 수 있습니다. 라이브러리에는 이러한 유형의 작업을 허용하는 여러 JSON 기능 및 연산자가 포함되어 있습니다.
JSONB_SET 함수 용 래퍼. 함수는 JSON 경로를 기준으로 JSON 속성의 값을 설정하거나 대체합니다. 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 ());다음과 같은 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 = ?이 함수는 다음 예에서와 같이 HQL 문에도 사용할 수 있습니다.
@ 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 ();
}연결 연산자를위한 래퍼. 래퍼는 두 개의 JSONB 값을 새로운 JSONB 값으로 연결합니다. 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 ());다음과 같은 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 = ?이 함수는 다음 예에서와 같이 HQL 문에도 사용할 수 있습니다.
@ 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 ();
}삭제하는 래퍼 운영자 '#-'. 래퍼는 지정된 경로에서 인덱스에 따라 필드 또는 어레이 요소를 삭제합니다. 여기서 경로 요소는 필드 키 또는 어레이 인덱스가 될 수 있습니다. 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 ());다음과 같은 SQL 업데이트 문이 생성됩니다.
update
item
set
jsonb_content = (jsonb_content # - ?::text[])
where
id = ?이 함수는 다음 예에서와 같이 HQL 문에도 사용할 수 있습니다.
@ 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 ();
}removejsonValuesfromjsonArrayFunction 유형은 PosjsonHelper 라이브러리에서 생성 된 SQL 기능을 호출하는 최대 절전 모드 연산자입니다. 기본적으로 생성 된 기능은 다음 예와 같습니다.
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;이 함수에는 두 개의 입력 매개 변수가 있습니다. 첫 번째는 JSON 배열이며, 결과는 함수가 반환되는 기본 배열입니다. 두 번째 매개 변수는 또한 결과 배열에서 제거 해야하는 요소를 나타내는 JSON 배열입니다. 아래는이 기능을 다른 연산자와 함께 사용하여 SQL 업데이트 문으로 JSON 열을 업데이트하는 방법에 대한 코드 예입니다.
// 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 " ]}" );동일한 예제이지만 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 " ]}" );이 두 예제는 아래 SQL 문을 생성 할 것입니다.
update
item
set
jsonb_content = jsonb_set(jsonb_content, ?:: text [], remove_values_from_json_array(jsonb_extract_path(jsonb_content, ?), ?::jsonb))
where
id = ?단일 JSONB_SET 함수를 사용하여 단일 업데이트 문으로 JSON의 단일 속성을 설정하는 것이 유용 할 수 있지만, 단일 업데이트 문으로 다른 수준의 JSON 트리에서 여러 속성을 설정할 수있는 것이 더 유용 할 수 있습니다.
아래 코드 예제 :
// 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 " }}" );위의 코드에서는 3 개의 JSON 속성 "child.birthday", "child.pets"및 "parents"를 설정하고 "Inventory.0"및 "Nicknames.childhood"를 삭제하고 싶습니다. "부모"속성은 배열이라고 가정하는 새로운 속성입니다. 일부 값이있는 새로운 배열 속성을 단일 작업으로 수행 할 수는 있지만 데모 목적을 위해 두 개의 작업을 사용합니다. 하나는 빈 JSON 배열을 값으로 사용하는 "부모"라는 새 속성을 설정하기위한 것입니다. 및 특정 인덱스에서 배열의 요소를 설정하는 또 다른 작업. 높은 속성이 존재하지 않으면 내부 속성 전에 생성되어야합니다. 다행히도 Hibernate6jsonupdatestatementBuilder 유형의 기본 인스턴스에는 올바른 작동 순서를 설정하는 데 도움이되는 적절한 정렬 및 필터링 구성 요소가 있습니다. 따라서 Create-Array 작업을 추가하기 전 또는 후에 Add-Array 요소 작업을 추가할지 여부는 중요하지 않습니다. 기본적으로 컨텐츠를 삭제하는 작업은 콘텐츠를 추가하거나 교체하는 작업 전에 추가됩니다. 물론 이러한 구성 요소를 NULL로 설정 하여이 동작을 비활성화 할 수 있습니다. 자세한 내용은 hibernate6jsonupdatestatementbuilder 유형에 대한 Javadoc을 확인하십시오.
이 코드는 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 = ?이 준비된 문의 가장 내부 JSONB_SET 함수 실행은 "부모"속성에 대한 빈 배열을 설정하는 것입니다.
빌더에는 값을 설정하는 방법이 있습니다.
속성 제거 :
AppendDeleteByspecificPath (JSONTEXTARRAY JSONTEXTARRAY)
배열 요소 추가
배열 요소를 제거합니다
기본적으로 JSON 배열의 수정과 관련된 일부 방법에는 org.json.json 라이브러리가 필요합니다 (선택적 종속성 확인). 그러나 "withCollectionToJsonArrayStringMapper (com.github.starnowski.posjsonHelper.HiberNATE6.Hibernate6jsonupDatestateMetmentBuilder.CollectionToJsonArrayStringMapper)를 사용하여 컬렉션 객체를 JSON 배열 값에 매핑하는 인터페이스 구현을 전달할 수 있습니다.
hibernate6jsonupdatestatementbuilder 유형은 일반적입니다. 두 번째 일반 유형은 Hibernate6jsonupdatestatementbuilder 컨텍스트에 추가 할 수있는 사용자 정의 값입니다. 아래는 유형이 배열 작업 (배열에서 추가하고 제거 해야하는 요소)을 나타내는 코드 예제입니다.
맞춤 가치 유형 :
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 ;
}
}사용 예 :
// 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 " ]}" );| 속성 이름 | 설명 |
|---|---|
| com.github.starnowski.posjsonhelper.core.functions.jsonb_all_array_strings_exist | 텍스트 []가 JSON 배열 속성에 존재하는지 확인하는 SQL 함수의 이름. 기본적으로 이름은 jsonb_all_array_strings_exist입니다 |
| com.github.starnowski.posjsonhelper.core.functions.jsonb_any_array_strings_exist | 텍스트 []가 JSON 배열 속성에 존재하는지 여부를 확인하는 SQL 함수의 이름. 기본적으로 이름은 jsonb_any_array_strings_exist입니다 |
| com.github.starnowski.posjsonhelper.core.functions.remove_values_from_json_array | JSONB 배열에서 요소를 삭제하여 JSONB 배열을 반환하는 SQL 기능의 이름은 기능의 입력으로 전달됩니다. 기본적으로 이름은 remove_values_from_json_array입니다 |
| com.github.starnowski.posjsonhelper.core.schema | SQL 기능을 생성 해야하는 데이터베이스 스키마 이름 |
| com.github.starnowski.posjsonhelper.core.hibernate.functions.jsonb_all_array_strings_exist | com.github.starnowski.posjsonhelper.core.functions.jsonb_all_array_strings_exist 속성에 의해 지정된 SQL 기능을 호출하는 HQL 함수의 이름. 기본적으로 이름은 jsonb_all_array_strings_exist입니다 |
| com.github.starnowski.posjsonhelper.core.hibernate.functions.jsonb_any_array_strings_exist | com.github.starnowski.posjsonhelper.core.functions.jsonb_any_array_strings_exist 속성에 의해 지정된 SQL 기능을 호출하는 HQL 함수의 이름. 기본적으로 이름은 jsonb_any_array_strings_exist입니다 |
| com.github.starnowski.posjsonhelper.core.hibernate.functions.json_function_json_array | 배열 연산자를 PostgreSQL로 랩핑하는 HQL 기능의 이름. 기본적으로 이름은 json_function_json_array입니다 |
| com.github.starnowski.posjsonhelper.core.hibernate.functions.remove_values_from_json_array | JSONB 배열에서 요소를 삭제하여 함수의 입력으로 전달 된 JSONB 배열을 반환하는 함수를 랩핑하는 HQL 기능의 이름. 기본적으로 이름은 remove_values_from_json_array입니다 |
| com.github.starnowski.posjsonhelper.core.hibernate.functions.sqldefinitioncontextfactory.types | com.github.starnowski.posjsonhelper.core.sql.isqldefinitionContextFactory 유형의 목록을 저장하는 시스템 속성. "com.github.starnowski.posjsonhelper"패키지의 클래스 경로에서 찾을 수있는로드 유형 대신. 목록의 유형은 쉼표 문자로 분리됩니다. ". |
| com.github.starnowski.posjsonhelper.hibernate6.FunctionDescriptorregisterFactory.Types | (Hibernate 6에서만 사용) com.github.starnowski.posjsonhelper.hibernate6.descriptor.functiondescriptorregisterFactoriessUpplier 유형의 목록을 저장하는 시스템 속성. "com.github.starnowski.posjsonhelper"패키지의 클래스 경로에서 찾을 수있는로드 유형 대신. 목록의 유형은 쉼표 문자로 분리됩니다. ". |
| com.github.starnowski.posjsonhelper.hibernate6.functiondescriptorregisterfactory.types.excluded | (Hibernate 6에서만 사용) com.github.starnowski.posjsonhelper.hibernate6.descriptor.functorregisterficiessupplier 유형의 com.github.starnowski.posjsonhelper.hibernate6.descriptor를 저장하는 시스템 속성. "com.github.starnowski.posjsonhelper.hibernate6.functiondescriptorregisterfactory.types"속성이 지정된 경우 "com.github.starnowski.posjsonhelper.hibernate6.functordescriptorregisterfictorfactory.typs.excluded"가 지정됩니다. 목록의 유형은 쉼표 문자로 분리됩니다. ". |
최대 절전 모드와 호환성 매트릭스 6.
| PosjsonHelper | 최대 절전 모드 6 |
|---|---|
| 0.3.0 | 6.4.0 |
| 0.2.0-0.2.1 | 6.1.5. 기본 |
최대 절전 모드 패키지, 버전 또는 클래스 등 문제
누락 된 메소드 정의 또는 유형과 관련하여 문제에 직면 한 경우 : 예 :
java.lang.NoSuchMethodError: 'org.hibernate.query.criteria.JpaExpression
그런 다음 먼저 프로젝트에 ClassPath에 최대 절전 모드 코어 라이브러리가 있는지 확인하십시오. 최대 절전 모드 코어는이 프로젝트의 선택적 종속성이며 프로젝트에 추가되었는지 확인해야합니다. 비슷한 문제 145를 확인하십시오. 최대 절전 모드 코어가 클래스 경로에 있고 문제가 여전히 존재하는 경우 문제를보고하십시오.