From ad414f36aead1bd59110115c64d97349bda05bbe Mon Sep 17 00:00:00 2001 From: Vlad Mihalcea Date: Thu, 20 Jun 2024 17:30:57 +0300 Subject: [PATCH] Remove hypersistence-utils-hibernate-52 module #726 --- README.md | 10 +- hypersistence-utils-hibernate-52/pom.xml | 205 ------ .../hibernate/id/BatchSequenceGenerator.java | 432 ----------- .../utils/hibernate/id/TsidGenerator.java | 92 --- .../CamelCaseToSnakeCaseNamingStrategy.java | 80 -- .../query/ListResultTransformer.java | 33 - .../hibernate/query/MapResultTransformer.java | 95 --- .../query/QueryStackTraceLogger.java | 82 --- .../utils/hibernate/query/SQLExtractor.java | 39 - .../hibernate/type/AbstractHibernateType.java | 51 -- .../type/HibernateTypesContributor.java | 176 ----- .../type/ImmutableCompositeType.java | 392 ---------- .../utils/hibernate/type/ImmutableType.java | 330 --------- .../type/array/BooleanArrayType.java | 47 -- .../hibernate/type/array/DateArrayType.java | 45 -- .../type/array/DecimalArrayType.java | 47 -- .../hibernate/type/array/DoubleArrayType.java | 48 -- .../hibernate/type/array/EnumArrayType.java | 76 -- .../hibernate/type/array/FloatArrayType.java | 49 -- .../hibernate/type/array/IntArrayType.java | 44 -- .../hibernate/type/array/ListArrayType.java | 41 -- .../type/array/LocalDateArrayType.java | 50 -- .../type/array/LocalDateTimeArrayType.java | 50 -- .../hibernate/type/array/LongArrayType.java | 47 -- .../hibernate/type/array/StringArrayType.java | 45 -- .../type/array/TimestampArrayType.java | 45 -- .../hibernate/type/array/UUIDArrayType.java | 46 -- .../array/internal/AbstractArrayType.java | 44 -- .../internal/AbstractArrayTypeDescriptor.java | 107 --- .../internal/ArraySqlTypeDescriptor.java | 70 -- .../type/array/internal/ArrayUtil.java | 392 ---------- .../internal/BooleanArrayTypeDescriptor.java | 18 - .../internal/DateArrayTypeDescriptor.java | 18 - .../internal/DecimalArrayTypeDescriptor.java | 18 - .../internal/DoubleArrayTypeDescriptor.java | 18 - .../internal/EnumArrayTypeDescriptor.java | 28 - .../internal/FloatArrayTypeDescriptor.java | 19 - .../internal/IntArrayTypeDescriptor.java | 17 - .../internal/ListArrayTypeDescriptor.java | 164 ----- .../LocalDateArrayTypeDescriptor.java | 17 - .../LocalDateTimeArrayTypeDescriptor.java | 17 - .../internal/LongArrayTypeDescriptor.java | 17 - .../internal/StringArrayTypeDescriptor.java | 18 - .../TimestampArrayTypeDescriptor.java | 18 - .../internal/UUIDArrayTypeDescriptor.java | 19 - .../utils/hibernate/type/basic/Inet.java | 59 -- .../type/basic/Iso8601MonthType.java | 45 -- .../type/basic/MonthDayDateType.java | 38 - .../type/basic/MonthDayIntegerType.java | 37 - .../type/basic/NullableCharacterType.java | 47 -- .../type/basic/PostgreSQLCITextType.java | 40 - .../type/basic/PostgreSQLEnumType.java | 90 --- .../type/basic/PostgreSQLHStoreType.java | 45 -- .../type/basic/PostgreSQLInetType.java | 51 -- .../type/basic/PostgreSQLLTreeType.java | 41 -- .../type/basic/YearMonthDateType.java | 45 -- .../type/basic/YearMonthEpochType.java | 44 -- .../type/basic/YearMonthIntegerType.java | 45 -- .../type/basic/YearMonthTimestampType.java | 44 -- .../utils/hibernate/type/basic/YearType.java | 45 -- .../hibernate/type/basic/ZoneIdType.java | 43 -- .../Iso8601MonthMonthTypeDescriptor.java | 59 -- .../internal/MonthDayTypeDescriptor.java | 83 --- .../YearMonthEpochTypeDescriptor.java | 75 -- .../internal/YearMonthTypeDescriptor.java | 88 --- .../basic/internal/YearTypeDescriptor.java | 66 -- .../basic/internal/ZoneIdTypeDescriptor.java | 64 -- .../type/binary/MySQLBinaryType.java | 35 - .../OracleIntervalDayToSecondType.java | 89 --- .../type/interval/PostgreSQLIntervalType.java | 74 -- .../type/interval/PostgreSQLPeriodType.java | 63 -- .../hibernate/type/json/JsonBinaryType.java | 94 --- .../hibernate/type/json/JsonBlobType.java | 94 --- .../type/json/JsonNodeBinaryType.java | 63 -- .../type/json/JsonNodeStringType.java | 64 -- .../hibernate/type/json/JsonStringType.java | 105 --- .../utils/hibernate/type/json/JsonType.java | 125 ---- .../AbstractJsonSqlTypeDescriptor.java | 60 -- .../type/json/internal/JacksonUtil.java | 32 - .../internal/JsonBinarySqlTypeDescriptor.java | 34 - .../internal/JsonBlobSqlTypeDescriptor.java | 31 - .../internal/JsonBytesSqlTypeDescriptor.java | 98 --- .../json/internal/JsonNodeTypeDescriptor.java | 90 --- .../json/internal/JsonSqlTypeDescriptor.java | 130 ---- .../internal/JsonStringSqlTypeDescriptor.java | 52 -- .../json/internal/JsonTypeDescriptor.java | 226 ------ .../type/money/CurrencyUnitType.java | 39 - .../type/money/MonetaryAmountType.java | 115 --- .../internal/CurrencyUnitTypeDescriptor.java | 50 -- .../type/range/PostgreSQLRangeType.java | 140 ---- .../utils/hibernate/type/range/Range.java | 680 ----------------- .../range/guava/PostgreSQLGuavaRangeType.java | 531 -------------- .../type/search/PostgreSQLTSVectorType.java | 35 - .../PostgreSQLTSVectorSqlTypeDescriptor.java | 70 -- .../PostgreSQLTSVectorTypeDescriptor.java | 88 --- .../type/util/ClassImportIntegrator.java | 89 --- .../hibernate/type/util/Configuration.java | 270 ------- .../type/util/JsonConfiguration.java | 73 -- .../hibernate/type/util/JsonSerializer.java | 20 - .../type/util/JsonSerializerSupplier.java | 19 - .../type/util/ObjectMapperJsonSerializer.java | 81 -- .../type/util/ObjectMapperSupplier.java | 21 - .../type/util/ObjectMapperWrapper.java | 189 ----- .../type/util/ParameterTypeUtils.java | 103 --- .../type/util/ParameterizedParameterType.java | 55 -- .../hibernate/util/ClassLoaderUtils.java | 77 -- .../utils/hibernate/util/LogUtils.java | 15 - .../utils/hibernate/util/ReflectionUtils.java | 677 ----------------- .../utils/hibernate/util/StringUtils.java | 64 -- .../SQLStatementCountMismatchException.java | 31 - .../validator/SQLStatementCountValidator.java | 72 -- .../utils/jdbc/validator/StatementType.java | 85 --- .../utils/spring/annotation/Retry.java | 30 - .../utils/spring/aop/RetryAspect.java | 110 --- .../spring/repository/BaseJpaRepository.java | 172 ----- .../repository/BaseJpaRepositoryImpl.java | 174 ----- .../repository/HibernateRepository.java | 181 ----- .../repository/HibernateRepositoryImpl.java | 174 ----- .../org.hibernate.boot.model.TypeContributor | 1 - .../AbstractBatchSequenceGeneratorTest.java | 128 ---- .../id/H2BatchSequenceGeneratorTest.java | 17 - .../id/OracleBatchSequenceGeneratorTest.java | 16 - .../PostgreSQLBatchSequenceGeneratorTest.java | 16 - .../SQLServerBatchSequenceGeneratorTest.java | 16 - .../hibernate/id/TsidIdentifierTest.java | 119 --- ...amelCaseToSnakeCaseNamingStrategyTest.java | 160 ---- .../query/ListResultTransformerTest.java | 212 ------ .../query/MapResultTransformerTest.java | 219 ------ .../query/QueryStackTraceLoggerTest.java | 151 ---- .../hibernate/query/SQLExtractorTest.java | 164 ----- .../type/array/ArrayTypeNativeQueryTest.java | 159 ---- .../hibernate/type/array/ArrayTypeTest.java | 332 --------- .../BindArrayTypeQueryParameterTest.java | 206 ------ .../array/DefaultEmptyListArrayTypeTest.java | 189 ----- .../type/array/EhcacheListArrayTypeTest.java | 351 --------- .../type/array/HSQLDBArrayTypeTest.java | 201 ----- .../type/array/ListArrayTypeTest.java | 689 ------------------ .../MappedSuperclassListArrayTypeTest.java | 106 --- .../type/array/MatrixArrayTypeTest.java | 125 ---- .../array/MultiDimensionalArrayTypeTest.java | 182 ----- .../MultiDimensionalIntegerArrayTypeTest.java | 147 ---- .../MultiDimensionalStringArrayTypeTest.java | 148 ---- .../type/array/PostgreSQL95ArrayDialect.java | 16 - .../array/PostgreSQLEnumArrayTypeTest.java | 177 ----- .../PostgreSQLMultipleEnumArrayTypeTest.java | 179 ----- .../type/array/SimpleArrayTypeTest.java | 176 ----- .../type/array/WrapperArrayTypeTest.java | 174 ----- .../type/basic/Iso8601MonthTest.java | 124 ---- .../type/basic/MySQLMonthDayDateTest.java | 150 ---- .../type/basic/MySQLMonthDayIntegerTest.java | 136 ---- .../type/basic/MySQLYearMonthDateTest.java | 147 ---- .../type/basic/MySQLYearMonthIntegerTest.java | 132 ---- .../type/basic/NullableCharacterTypeTest.java | 82 --- .../type/basic/OracleBinaryDoubleTest.java | 114 --- .../type/basic/OracleBinaryFloatTest.java | 114 --- .../type/basic/PostgreSQLCITextTypeTest.java | 164 ----- .../type/basic/PostgreSQLEnumTest.java | 160 ---- .../type/basic/PostgreSQLHStoreTypeTest.java | 105 --- .../type/basic/PostgreSQLInetTypeTest.java | 145 ---- .../type/basic/PostgreSQLLTreeTypeTest.java | 159 ---- .../basic/PostgreSQLMonthDayDateTest.java | 135 ---- .../basic/PostgreSQLMonthDayIntegerTest.java | 132 ---- .../basic/PostgreSQLYearMonthDateTest.java | 132 ---- .../basic/PostgreSQLYearMonthEpochTest.java | 189 ----- .../basic/PostgreSQLYearMonthIntegerTest.java | 190 ----- ...QLYearMonthIntegerTypeContributorTest.java | 122 ---- .../PostgreSQLYearMonthTimestampTest.java | 136 ---- .../type/basic/YearAndMonthTest.java | 115 --- .../hibernate/type/basic/ZoneIdTest.java | 98 --- .../type/binary/MySQLBinaryTypeTest.java | 83 --- .../OracleIntervalDayToSecondTypeTest.java | 59 -- .../interval/PostgreSQLIntervalTypeTest.java | 60 -- .../interval/PostgreSQLPeriodTypeTest.java | 59 -- .../json/EhcacheMySQLJsonBinaryTypeTest.java | 125 ---- .../hibernate/type/json/HbmJsonTypeTest.java | 68 -- .../type/json/MySQLJsonNodePropertyTest.java | 112 --- .../json/MySQLJsonStringPropertyTest.java | 143 ---- .../type/json/MySQLJsonTypeSetTest.java | 194 ----- .../type/json/MySQLJsonTypeTest.java | 158 ---- .../json/MySQLParametrizedJsonTypeTest.java | 248 ------- .../type/json/OracleJsonBinaryTypeTest.java | 188 ----- .../json/OracleJsonStringPropertyTest.java | 165 ----- .../PostgreSQLGenericJsonBinaryTypeTest.java | 138 ---- ...PostgreSQLJsonBinaryTypeLazyGroupTest.java | 70 -- ...ypeNestedCollectionExplicitEqualsTest.java | 129 ---- ...inaryTypeNestedCollectionNoEqualsTest.java | 115 --- .../json/PostgreSQLJsonBinaryTypeSetTest.java | 194 ----- .../json/PostgreSQLJsonBinaryTypeTest.java | 191 ----- .../type/json/PostgreSQLJsonListEnumTest.java | 95 --- .../type/json/PostgreSQLJsonListPojoTest.java | 122 ---- .../type/json/PostgreSQLJsonMapTest.java | 101 --- .../PostgreSQLJsonNodeBinaryTypeTest.java | 135 ---- .../type/json/PostgreSQLJsonNodeTypeTest.java | 252 ------- ...stgreSQLJsonParameterizedPropertyTest.java | 167 ----- .../PostgreSQLJsonStringPropertyTest.java | 189 ----- .../json/PostgreSQLJsonStringTypeTest.java | 141 ---- .../json/SQLServerJsonStringPropertyTest.java | 163 ----- .../configuration/CustomJsonSerializer.java | 26 - .../CustomJsonSerializerSupplier.java | 15 - .../CustomObjectMapperSupplier.java | 24 - .../json/configuration/MoneySerializer.java | 25 - ...sonBinaryTypeConfigurationJvmForkTest.java | 113 --- ...sonSerializerConfigurationJvmForkTest.java | 123 ---- ...ProgrammaticConfigurationSupplierTest.java | 136 ---- ...naryTypeProgrammaticConfigurationTest.java | 127 ---- .../json/generic/GenericH2JsonMapTest.java | 108 --- .../json/generic/GenericMySQLJsonMapTest.java | 102 --- .../generic/GenericMySQLJsonTypeTest.java | 155 ---- .../GenericOffsetDateTimeJsonTest.java | 156 ---- .../generic/GenericOracleJsonMapTest.java | 104 --- ...nTypeBlobPropertyParameterSettingTest.java | 162 ---- ...GenericOracleJsonTypeBlobPropertyTest.java | 164 ----- .../GenericOracleJsonTypePropertyTest.java | 164 ----- ...ericOracleJsonTypeVarcharPropertyTest.java | 166 ----- .../generic/GenericPostgreSQLJsonMapTest.java | 102 --- .../GenericPostgreSQLJsonStringTest.java | 147 ---- .../GenericPostgreSQLJsonTypeTest.java | 157 ---- .../generic/GenericSQLServerJsonMapTest.java | 102 --- .../type/json/internal/JacksonUtilTest.java | 168 ----- .../json/internal/JsonTypeDescriptorTest.java | 192 ----- ...eSQLJsonPolymorphicListCustomTypeTest.java | 229 ------ ...SQLJsonPolymorphicListJacksonTypeTest.java | 229 ------ .../hibernate/type/model/BaseEntity.java | 54 -- .../utils/hibernate/type/model/Event.java | 26 - .../utils/hibernate/type/model/Location.java | 52 -- .../hibernate/type/model/Participant.java | 37 - .../utils/hibernate/type/model/Ticket.java | 44 -- .../type/money/MySQLCurrencyUnitTypeTest.java | 118 --- ...netaryAmountTypeElementCollectionTest.java | 129 ---- .../MySQLMonetaryAmountTypeEmbeddedTest.java | 176 ----- .../money/MySQLMonetaryAmountTypeTest.java | 204 ------ .../money/PostgreSQLCurrencyUnitTypeTest.java | 118 --- ...netaryAmountTypeElementCollectionTest.java | 129 ---- ...tgreSQLMonetaryAmountTypeEmbeddedTest.java | 166 ----- .../PostgreSQLMonetaryAmountTypeTest.java | 167 ----- .../range/PostgreSQLRangeTypeDSTTest.java | 80 -- .../type/range/PostgreSQLRangeTypeTest.java | 241 ------ .../utils/hibernate/type/range/RangeTest.java | 156 ---- .../range/ZonedDateTimeMilliSecondTest.java | 107 --- .../guava/PostgreSQLGuavaRangeTypeTest.java | 238 ------ .../search/PostgreSQLTSVectorTypeTest.java | 92 --- .../type/util/ConfigurationTest.java | 26 - .../util/ObjectMapperJsonSerializerTest.java | 300 -------- .../DTOProjectionImportRelativePathTest.java | 149 ---- .../util/dto/DTOProjectionImportTest.java | 148 ---- .../hibernate/type/util/dto/PostDTO.java | 24 - .../util/AbstractMySQLIntegrationTest.java | 17 - .../util/AbstractOracleIntegrationTest.java | 17 - .../AbstractPostgreSQLIntegrationTest.java | 17 - .../AbstractSQLServerIntegrationTest.java | 17 - .../utils/hibernate/util/AbstractTest.java | 533 -------------- .../hibernate/util/DataSourceProxyType.java | 32 - .../utils/hibernate/util/EntityProvider.java | 14 - .../utils/hibernate/util/ExceptionUtil.java | 129 ---- .../util/PersistenceUnitInfoImpl.java | 134 ---- .../utils/hibernate/util/StringUtilsTest.java | 19 - .../AbstractContainerDataSourceProvider.java | 48 -- .../util/providers/DataSourceProvider.java | 21 - .../hibernate/util/providers/Database.java | 90 --- .../util/providers/H2DataSourceProvider.java | 45 -- .../providers/HSQLDBDataSourceProvider.java | 45 -- .../providers/MySQLDataSourceProvider.java | 125 ---- .../providers/OracleDataSourceProvider.java | 73 -- .../PostgreSQLDataSourceProvider.java | 46 -- .../SQLServerDataSourceProvider.java | 52 -- .../util/transaction/ConnectionCallable.java | 12 - .../transaction/ConnectionVoidCallable.java | 12 - .../HibernateTransactionConsumer.java | 19 - .../HibernateTransactionFunction.java | 19 - .../transaction/JPATransactionFunction.java | 18 - .../JPATransactionVoidFunction.java | 18 - .../util/transaction/VoidCallable.java | 17 - .../logging/InlineQueryLogEntryCreator.java | 85 --- .../spring/aop/RetryAspectConfiguration.java | 22 - .../utils/spring/aop/RetryAspectTest.java | 78 -- .../utils/spring/aop/service/BaseService.java | 8 - .../spring/aop/service/BaseServiceImpl.java | 21 - .../spring/aop/service/CustomerService.java | 22 - .../utils/spring/aop/service/ItemService.java | 23 - .../spring/aop/service/ProductService.java | 16 - .../aop/service/ProductServiceImpl.java | 15 - .../AbstractSpringDataJPAConfiguration.java | 116 --- .../utils/spring/domain/Post.java | 50 -- .../spring/repo/base/PostRepository.java | 13 - .../base/SpringDataJPABaseConfiguration.java | 36 - .../repo/base/SpringDataJPABaseTest.java | 136 ---- .../spring/repo/hibernate/PostRepository.java | 14 - .../SpringDataJPAHibernateConfiguration.java | 37 - .../hibernate/SpringDataJPAHibernateTest.java | 120 --- .../repo/projection/PostRepository.java | 33 - .../SpringDataProjectionConfiguration.java | 45 -- .../projection/SpringDataProjectionTest.java | 75 -- ...JsonBinaryTypeConfigurationTest.properties | 1 - ...JsonSerializerConfigurationTest.properties | 1 - .../src/test/resources/application.properties | 1 - .../hbm/type/json/HbmJsonTypeTest.hbm.xml | 21 - .../test/resources/hibernate-types.properties | 1 - .../src/test/resources/hibernate.properties | 3 - .../src/test/resources/logback-test.xml | 23 - pom.xml | 1 - 300 files changed, 1 insertion(+), 31402 deletions(-) delete mode 100644 hypersistence-utils-hibernate-52/pom.xml delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/id/BatchSequenceGenerator.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/id/TsidGenerator.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/naming/CamelCaseToSnakeCaseNamingStrategy.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/ListResultTransformer.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/MapResultTransformer.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/QueryStackTraceLogger.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/SQLExtractor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/AbstractHibernateType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/HibernateTypesContributor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/ImmutableCompositeType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/ImmutableType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/BooleanArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DateArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DecimalArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DoubleArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/EnumArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/FloatArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/IntArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/ListArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LocalDateArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LocalDateTimeArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LongArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/StringArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/TimestampArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/UUIDArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/AbstractArrayType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/AbstractArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ArraySqlTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ArrayUtil.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/BooleanArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DateArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DecimalArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DoubleArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/EnumArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/FloatArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/IntArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ListArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LocalDateArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LocalDateTimeArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LongArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/StringArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/TimestampArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/UUIDArrayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/Inet.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/Iso8601MonthType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/MonthDayDateType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/MonthDayIntegerType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/NullableCharacterType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLCITextType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLEnumType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLHStoreType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLInetType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLLTreeType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthDateType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthEpochType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthIntegerType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthTimestampType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/ZoneIdType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/Iso8601MonthMonthTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/MonthDayTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearMonthEpochTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearMonthTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/ZoneIdTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/binary/MySQLBinaryType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/OracleIntervalDayToSecondType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLIntervalType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLPeriodType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonBinaryType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonBlobType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonNodeBinaryType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonNodeStringType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonStringType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/AbstractJsonSqlTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JacksonUtil.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBinarySqlTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBlobSqlTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBytesSqlTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonNodeTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonSqlTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonStringSqlTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/CurrencyUnitType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/MonetaryAmountType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/internal/CurrencyUnitTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/Range.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/guava/PostgreSQLGuavaRangeType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/PostgreSQLTSVectorType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/internal/PostgreSQLTSVectorSqlTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/internal/PostgreSQLTSVectorTypeDescriptor.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ClassImportIntegrator.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/Configuration.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonConfiguration.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonSerializer.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonSerializerSupplier.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperJsonSerializer.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperSupplier.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperWrapper.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ParameterTypeUtils.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ParameterizedParameterType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/ClassLoaderUtils.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/LogUtils.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/ReflectionUtils.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/StringUtils.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/SQLStatementCountMismatchException.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/SQLStatementCountValidator.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/StatementType.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/annotation/Retry.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/aop/RetryAspect.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/BaseJpaRepository.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/BaseJpaRepositoryImpl.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/HibernateRepository.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/HibernateRepositoryImpl.java delete mode 100644 hypersistence-utils-hibernate-52/src/main/resources/META-INF/services/org.hibernate.boot.model.TypeContributor delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/AbstractBatchSequenceGeneratorTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/H2BatchSequenceGeneratorTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/OracleBatchSequenceGeneratorTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/PostgreSQLBatchSequenceGeneratorTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/SQLServerBatchSequenceGeneratorTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/TsidIdentifierTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/naming/CamelCaseToSnakeCaseNamingStrategyTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/ListResultTransformerTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/MapResultTransformerTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/QueryStackTraceLoggerTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/SQLExtractorTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ArrayTypeNativeQueryTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/BindArrayTypeQueryParameterTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/DefaultEmptyListArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/EhcacheListArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/HSQLDBArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ListArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MappedSuperclassListArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MatrixArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalIntegerArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalStringArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQL95ArrayDialect.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQLEnumArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQLMultipleEnumArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/SimpleArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/WrapperArrayTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/Iso8601MonthTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLMonthDayDateTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLMonthDayIntegerTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLYearMonthDateTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLYearMonthIntegerTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/NullableCharacterTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/OracleBinaryDoubleTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/OracleBinaryFloatTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLCITextTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLEnumTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLHStoreTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLInetTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLLTreeTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLMonthDayDateTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLMonthDayIntegerTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthDateTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthEpochTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthIntegerTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthIntegerTypeContributorTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthTimestampTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/YearAndMonthTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/ZoneIdTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/binary/MySQLBinaryTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/OracleIntervalDayToSecondTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLIntervalTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLPeriodTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/EhcacheMySQLJsonBinaryTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/HbmJsonTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonNodePropertyTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonStringPropertyTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonTypeSetTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLParametrizedJsonTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/OracleJsonBinaryTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/OracleJsonStringPropertyTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLGenericJsonBinaryTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeLazyGroupTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeNestedCollectionExplicitEqualsTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeNestedCollectionNoEqualsTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeSetTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonListEnumTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonListPojoTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonMapTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonNodeBinaryTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonNodeTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonParameterizedPropertyTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonStringPropertyTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonStringTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/SQLServerJsonStringPropertyTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomJsonSerializer.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomJsonSerializerSupplier.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomObjectMapperSupplier.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/MoneySerializer.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeConfigurationJvmForkTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeCustomJsonSerializerConfigurationJvmForkTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeProgrammaticConfigurationSupplierTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeProgrammaticConfigurationTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericH2JsonMapTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericMySQLJsonMapTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericMySQLJsonTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOffsetDateTimeJsonTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonMapTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeBlobPropertyParameterSettingTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeBlobPropertyTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypePropertyTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeVarcharPropertyTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonMapTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonStringTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericSQLServerJsonMapTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/internal/JacksonUtilTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/internal/JsonTypeDescriptorTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/polymorphic/PostgreSQLJsonPolymorphicListCustomTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/polymorphic/PostgreSQLJsonPolymorphicListJacksonTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/BaseEntity.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Event.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Location.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Participant.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Ticket.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLCurrencyUnitTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeElementCollectionTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeEmbeddedTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLCurrencyUnitTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeElementCollectionTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeEmbeddedTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeTypeDSTTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/RangeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/ZonedDateTimeMilliSecondTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/guava/PostgreSQLGuavaRangeTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/search/PostgreSQLTSVectorTypeTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/ConfigurationTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperJsonSerializerTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/DTOProjectionImportRelativePathTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/DTOProjectionImportTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/PostDTO.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractMySQLIntegrationTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractOracleIntegrationTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractPostgreSQLIntegrationTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractSQLServerIntegrationTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/DataSourceProxyType.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/EntityProvider.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/ExceptionUtil.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/PersistenceUnitInfoImpl.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/StringUtilsTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/AbstractContainerDataSourceProvider.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/DataSourceProvider.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/Database.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/H2DataSourceProvider.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/HSQLDBDataSourceProvider.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/MySQLDataSourceProvider.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/OracleDataSourceProvider.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/PostgreSQLDataSourceProvider.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/SQLServerDataSourceProvider.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/ConnectionCallable.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/ConnectionVoidCallable.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/HibernateTransactionConsumer.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/HibernateTransactionFunction.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/JPATransactionFunction.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/JPATransactionVoidFunction.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/VoidCallable.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/logging/InlineQueryLogEntryCreator.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/RetryAspectConfiguration.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/RetryAspectTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/BaseService.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/BaseServiceImpl.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/CustomerService.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ItemService.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ProductService.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ProductServiceImpl.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/config/AbstractSpringDataJPAConfiguration.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/domain/Post.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/PostRepository.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/SpringDataJPABaseConfiguration.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/SpringDataJPABaseTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/PostRepository.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/SpringDataJPAHibernateConfiguration.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/SpringDataJPAHibernateTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/PostRepository.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/SpringDataProjectionConfiguration.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/SpringDataProjectionTest.java delete mode 100644 hypersistence-utils-hibernate-52/src/test/resources/PostgreSQLJsonBinaryTypeConfigurationTest.properties delete mode 100644 hypersistence-utils-hibernate-52/src/test/resources/PostgreSQLJsonBinaryTypeCustomJsonSerializerConfigurationTest.properties delete mode 100644 hypersistence-utils-hibernate-52/src/test/resources/application.properties delete mode 100644 hypersistence-utils-hibernate-52/src/test/resources/hbm/type/json/HbmJsonTypeTest.hbm.xml delete mode 100644 hypersistence-utils-hibernate-52/src/test/resources/hibernate-types.properties delete mode 100644 hypersistence-utils-hibernate-52/src/test/resources/hibernate.properties delete mode 100644 hypersistence-utils-hibernate-52/src/test/resources/logback-test.xml diff --git a/README.md b/README.md index 6e6645ff4..8e9695bdb 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ That's it! The Hypersistence Utils project gives you general-purpose utilities for both Spring and Hibernate. -The main advantage of this project is that it supports a broad range of Hibernate versions, spanning from **Hibernate ORM 6.5**, **6.4**, **6.3** to **6.2**, **6.1**, **6.0**, **5.6**, **5.5**, **5.4**, **5.3**, and Hibernate **5.2**. +The main advantage of this project is that it supports a broad range of Hibernate versions, spanning from **Hibernate ORM 6.5**, **6.4**, **6.3** to **6.2**, **6.1**, **6.0**, **5.6**, and Hibernate **5.5**. ### Installation Guide @@ -58,14 +58,6 @@ Depending on the Hibernate version you are using, you need to add the following 3.7.6 -#### Hibernate 5.4, 5.3 and 5.2 - - - io.hypersistence - hypersistence-utils-hibernate-52 - 3.7.6 - - #### Optional Maven Dependencies The Hypersistence Utils project defines a list of optional dependencies that you will have to declare explicitly in your project in order to use them. diff --git a/hypersistence-utils-hibernate-52/pom.xml b/hypersistence-utils-hibernate-52/pom.xml deleted file mode 100644 index 37137558e..000000000 --- a/hypersistence-utils-hibernate-52/pom.xml +++ /dev/null @@ -1,205 +0,0 @@ - - - - io.hypersistence - hypersistence-utils-parent - 3.7.7-SNAPSHOT - - - 4.0.0 - - hypersistence-utils-hibernate-52 - 3.7.7-SNAPSHOT - jar - - hypersistence-utils-hibernate-52 - Utilities for Spring and Hibernate ORM 5.2 to 5.4 - - - - - net.ttddyy - datasource-proxy - ${datasource-proxy.version} - provided - true - - - - org.hibernate - hibernate-core - ${hibernate.version} - provided - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - provided - true - - - - com.fasterxml.jackson.module - jackson-module-jaxb-annotations - ${jackson-module-jaxb-annotation} - provided - true - - - - com.google.guava - guava - ${guava.version} - provided - true - - - - org.javamoney - moneta - ${moneta.version} - pom - provided - true - - - - org.hibernate - hibernate-ehcache - ${hibernate.version} - test - - - - com.zaxxer - HikariCP - ${hikari.version} - - - org.slf4j - slf4j-api - - - provided - true - - - - org.aspectj - aspectjrt - ${aspectj.version} - provided - true - - - - org.aspectj - aspectjweaver - ${aspectj.version} - provided - true - - - - org.springframework - spring-beans - ${spring.version} - provided - true - - - - org.springframework - spring-context - ${spring.version} - provided - true - - - - org.springframework - spring-tx - ${spring.version} - provided - true - - - - org.springframework - spring-orm - ${spring.version} - provided - true - - - - org.springframework.data - spring-data-jpa - ${spring-data.version} - provided - true - - - - - - org.hibernate - hibernate-envers - ${hibernate.version} - test - - - - org.springframework - spring-test - ${spring.version} - jar - test - - - - - - 5.4.33.Final - - - 8.0.28 - 2.12.7.1 - 2.12.6 - 32.0.0-jre - 1.4.2 - - 4.0.3 - 1.9.19 - 5.3.18 - 2.6.0 - - - - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven-jar-plugin.version} - - - - io.hypersistence.utils.hibernate.type - - - - - - - test-jar - - - - - - - - diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/id/BatchSequenceGenerator.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/id/BatchSequenceGenerator.java deleted file mode 100644 index abbefadca..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/id/BatchSequenceGenerator.java +++ /dev/null @@ -1,432 +0,0 @@ -package io.hypersistence.utils.hibernate.id; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import org.hibernate.HibernateException; -import org.hibernate.MappingException; -import org.hibernate.boot.model.relational.Database; -import org.hibernate.boot.model.relational.QualifiedNameParser; -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.hibernate.engine.jdbc.spi.JdbcCoordinator; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.id.BulkInsertionCapableIdentifierGenerator; -import org.hibernate.id.Configurable; -import org.hibernate.id.IdentifierGenerationException; -import org.hibernate.id.PersistentIdentifierGenerator; -import org.hibernate.id.enhanced.DatabaseStructure; -import org.hibernate.id.enhanced.SequenceStructure; -import org.hibernate.internal.util.config.ConfigurationHelper; -import org.hibernate.service.ServiceRegistry; -import org.hibernate.type.Type; - -/** - * A sequence generator that uses a recursive query to fetch multiple - * values from a sequence in a single database access. - * - *

Parameters

- * The following configuration parameters are supported: - *
- *
{@value #SEQUENCE_PARAM}
- *
mandatory, name of the sequence to use
- *
{@value #FETCH_SIZE_PARAM}
- *
optional, how many sequence numbers should be fetched at a time, - * default is {@value #DEFAULT_FETCH_SIZE}
- *
- * - *

SQL

- * Per default the generated SELECT will look something like this - *

- * WITH RECURSIVE t(n) AS (
- *   SELECT 1
- *     UNION ALL
- *   SELECT n + 1
- *   FROM t
- *   WHERE n < ?)
- * SELECT nextval(seq_xxx)
- *   FROM t;
- * 
- * - *

DB2

- * For DB2 the generated SELECT will look something like this - *

- * WITH t(n) AS (
- *   SELECT 1 AS n
- *     FROM (VALUES 1)
- *       UNION ALL
- *     SELECT n + 1 AS n
- *       FROM t
- *      WHERE n < ?)
- * SELECT next value for SEQ_CHILD_ID AS n
- *   FROM t;
- * 
- * - *

HSQLDB

- * For HSQLDB the generated SELECT will look something like this - *

- * SELECT next value for seq_parent_id
- *   FROM UNNEST(SEQUENCE_ARRAY(1, ?, 1));
- * 
- * - *

Oracle

- * For Oracle the generated SELECT will look something like this - * because Oracle does not support using recursive common table - * expressions to fetch multiple values from a sequence. - *

- * SELECT seq_xxx.nextval
- * FROM dual
- * CONNECT BY rownum <= ?
- * 
- * - *

SQL Server

- * For SQL Server the generated SELECT will look something like this - *

- * WITH t(n) AS (
- *   SELECT 1 AS n
- *     UNION ALL
- *   SELECT n + 1 AS n
- *     FROM t
- *    WHERE n < ?)
- * SELECT NEXT VALUE FOR seq_xxx AS n
- *   FROM t
- * 
- * - *

Firebird

- * For Firebird the generated SELECT will look something like this - *

- * WITH RECURSIVE t(n, level_num) AS (
- *   SELECT NEXT VALUE FOR seq_xxx AS n, 1 AS level_num
- *   FROM rdb$database
- *     UNION ALL
- *   SELECT NEXT VALUE FOR seq_xxx AS n, level_num + 1 AS level_num
- *     FROM t
- *    WHERE level_num < ?)
- * SELECT n
- *   FROM t
- * 
- * - *

Database Support

- * The following RDBMS have been verified to work - * - *

- * In theory any RDBMS that supports {@code WITH RECURSIVE} and - * sequences is supported. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Philippe Marschall - * @since 2.14.0 - */ -public class BatchSequenceGenerator implements BulkInsertionCapableIdentifierGenerator, PersistentIdentifierGenerator, Configurable { - - /** - * Indicates the name of the sequence to use, mandatory. - */ - public static final String SEQUENCE_PARAM = "sequence"; - - /** - * Indicates how many sequence values to fetch at once. The default value is {@link #DEFAULT_FETCH_SIZE}. - */ - public static final String FETCH_SIZE_PARAM = "fetch_size"; - - /** - * The default value for {@link #FETCH_SIZE_PARAM}. - */ - public static final int DEFAULT_FETCH_SIZE = 10; - - private final Lock lock = new ReentrantLock(); - - private String select; - private int fetchSize; - private IdentifierPool identifierPool; - private IdentifierExtractor identifierExtractor; - private DatabaseStructure databaseStructure; - - @Override - public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) - throws MappingException { - - JdbcEnvironment jdbcEnvironment = serviceRegistry.getService(JdbcEnvironment.class); - Dialect dialect = jdbcEnvironment.getDialect(); - String sequenceName = determineSequenceName(params); - this.fetchSize = determineFetchSize(params); - - this.select = buildSelect(sequenceName, dialect); - this.identifierExtractor = IdentifierExtractor.getIdentifierExtractor(type.getReturnedClass()); - this.identifierPool = IdentifierPool.empty(); - - this.databaseStructure = this.buildDatabaseStructure(type, sequenceName, jdbcEnvironment); - } - - private static String buildSelect(String sequenceName, Dialect dialect) { - if (dialect instanceof org.hibernate.dialect.Oracle8iDialect) { - return "SELECT " + dialect.getSelectSequenceNextValString(sequenceName) + " FROM dual CONNECT BY rownum <= ?"; - } - if (dialect instanceof org.hibernate.dialect.SQLServerDialect) { - // No RECURSIVE - return "WITH t(n) AS ( " - + "SELECT 1 AS n " - + "UNION ALL " - +"SELECT n + 1 AS n FROM t WHERE n < ?) " - // sequence generation outside of WITH - + "SELECT " + dialect.getSelectSequenceNextValString(sequenceName) + " AS n FROM t"; - } - if (dialect instanceof org.hibernate.dialect.DB2Dialect) { - // No RECURSIVE - return "WITH t(n) AS ( " - + "SELECT 1 AS n " - // difference - + "FROM (VALUES 1) " - + "UNION ALL " - +"SELECT n + 1 AS n FROM t WHERE n < ?) " - // sequence generation outside of WITH - + "SELECT " + dialect.getSelectSequenceNextValString(sequenceName) + " AS n FROM t"; - } - if (dialect instanceof org.hibernate.dialect.HSQLDialect) { - // https://stackoverflow.com/questions/44472280/cte-based-sequence-generation-with-hsqldb/52329862 - return "SELECT " + dialect.getSelectSequenceNextValString(sequenceName) + " FROM UNNEST(SEQUENCE_ARRAY(1, ?, 1))"; - } - if(dialect instanceof org.hibernate.dialect.PostgreSQL81Dialect) { - return "SELECT " + dialect.getSelectSequenceNextValString(sequenceName) + " FROM generate_series(1, ?)"; - } - if (dialect instanceof org.hibernate.dialect.FirebirdDialect) { - return "WITH RECURSIVE t(n, level_num) AS (" - + "SELECT " + dialect.getSelectSequenceNextValString(sequenceName) + " AS n, 1 AS level_num " - // difference - + " FROM rdb$database " - + "UNION ALL " - + "SELECT " + dialect.getSelectSequenceNextValString(sequenceName) + " AS n, level_num + 1 AS level_num " - + " FROM t " - + " WHERE level_num < ?) " - + "SELECT n FROM t"; - } - return "WITH RECURSIVE t(n) AS (" - + "SELECT 1 " - + "UNION ALL " - + "SELECT n + 1" - + " FROM t " - + " WHERE n < ?) " - + "SELECT " + dialect.getSelectSequenceNextValString(sequenceName) + " FROM t"; - } - - private SequenceStructure buildDatabaseStructure(Type type, String sequenceName, JdbcEnvironment jdbcEnvironment) { - return new SequenceStructure(jdbcEnvironment, - QualifiedNameParser.INSTANCE.parse(sequenceName), 1, 1, type.getReturnedClass()); - } - - private static String determineSequenceName(Properties params) { - String sequenceName = params.getProperty(SEQUENCE_PARAM); - if (sequenceName == null) { - throw new MappingException("no squence name specified"); - } - return sequenceName; - } - - private static int determineFetchSize(Properties params) { - int fetchSize = ConfigurationHelper.getInt(FETCH_SIZE_PARAM, params, DEFAULT_FETCH_SIZE); - if (fetchSize <= 0) { - throw new MappingException("fetch size must be positive"); - } - return fetchSize; - } - - @Override - public boolean supportsBulkInsertionIdentifierGeneration() { - return true; - } - - @Override - public String determineBulkInsertionIdentifierGenerationSelectFragment(Dialect dialect) { - return dialect.getSelectSequenceNextValString(this.getSequenceName()); - } - - @Override - public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException { - this.lock.lock(); - try { - if (this.identifierPool.isEmpty()) { - this.identifierPool = this.replenishIdentifierPool(session); - } - return this.identifierPool.next(); - } finally { - this.lock.unlock(); - } - } - - @Override - public Object generatorKey() { - return this.getSequenceName(); - } - - private String getSequenceName() { - return this.databaseStructure.getName(); - } - - @Override - @Deprecated - public String[] sqlCreateStrings(Dialect dialect) { - return this.databaseStructure.sqlCreateStrings(dialect); - } - - @Override - @Deprecated - public String[] sqlDropStrings(Dialect dialect) { - return this.databaseStructure.sqlDropStrings(dialect); - } - - @Override - public void registerExportables(Database database) { - this.databaseStructure.registerExportables(database); - } - - private IdentifierPool replenishIdentifierPool(SharedSessionContractImplementor session) - throws HibernateException { - JdbcCoordinator coordinator = session.getJdbcCoordinator(); - List identifiers = new ArrayList<>(this.fetchSize); - try (PreparedStatement statement = coordinator.getStatementPreparer().prepareStatement(this.select)) { - statement.setFetchSize(this.fetchSize); - statement.setInt(1, this.fetchSize); - try (ResultSet resultSet = coordinator.getResultSetReturn().extract(statement)) { - while (resultSet.next()) { - identifiers.add(this.identifierExtractor.extractIdentifier(resultSet)); - } - } - } catch (SQLException e) { - throw session.getJdbcServices().getSqlExceptionHelper().convert( - e, "could not get next sequence value", this.select); - } - if (identifiers.size() != this.fetchSize) { - throw new IdentifierGenerationException("expected " + this.fetchSize + " values from " + this.getSequenceName() - + " but got " + identifiers.size()); - } - return IdentifierPool.forList(identifiers); - } - - /** - * Holds a number of prefetched identifiers. - */ - static final class IdentifierPool { - - private final Iterator iterator; - - private IdentifierPool (List identifiers) { - this.iterator = identifiers.iterator(); - } - - static IdentifierPool forList(List identifiers) { - return new IdentifierPool(identifiers); - } - - static IdentifierPool empty() { - return new IdentifierPool(Collections.emptyList()); - } - - boolean isEmpty() { - return !this.iterator.hasNext(); - } - - Serializable next() { - return this.iterator.next(); - } - - } - - /** - * Extracts a {@link Serializable} identifier from a {@link ResultSet}. - * - * @see org.hibernate.id.IntegralDataTypeHolder - */ - enum IdentifierExtractor { - - INTEGER_IDENTIFIER_EXTRACTOR { - @Override - Serializable extractIdentifier(ResultSet resultSet) throws SQLException { - int intValue = resultSet.getInt(1); - if (resultSet.wasNull()) { - throw new IdentifierGenerationException("sequence returned null"); - } - return intValue; - } - }, - - LONG_IDENTIFIER_EXTRACTOR { - @Override - Serializable extractIdentifier(ResultSet resultSet) throws SQLException { - long longValue = resultSet.getLong(1); - if (resultSet.wasNull()) { - throw new IdentifierGenerationException("sequence returned null"); - } - return longValue; - } - }, - - BIG_INTEGER_IDENTIFIER_EXTRACTOR { - @Override - Serializable extractIdentifier(ResultSet resultSet) throws SQLException { - BigDecimal bigDecimal = resultSet.getBigDecimal(1); - if (resultSet.wasNull()) { - throw new IdentifierGenerationException("sequence returned null"); - } - return bigDecimal.setScale(0, BigDecimal.ROUND_UNNECESSARY).toBigInteger(); - } - }, - - BIG_DECIMAL_IDENTIFIER_EXTRACTOR { - @Override - Serializable extractIdentifier(ResultSet resultSet) throws SQLException { - BigDecimal bigDecimal = resultSet.getBigDecimal(1); - if (resultSet.wasNull()) { - throw new IdentifierGenerationException("sequence returned null"); - } - return bigDecimal; - } - }; - - abstract Serializable extractIdentifier(ResultSet resultSet) throws SQLException; - - static IdentifierExtractor getIdentifierExtractor(Class integralType) { - if ((integralType == Integer.class) || (integralType == int.class)) { - return INTEGER_IDENTIFIER_EXTRACTOR; - } - if ((integralType == Long.class) || (integralType == long.class)) { - return LONG_IDENTIFIER_EXTRACTOR; - } - if (integralType == BigInteger.class) { - return BIG_INTEGER_IDENTIFIER_EXTRACTOR; - } - if (integralType == BigDecimal.class) { - return BIG_DECIMAL_IDENTIFIER_EXTRACTOR; - } - throw new IdentifierGenerationException("unsupported integral type: " + integralType); - } - - } - - @Override - public String toString() { - // for debugging only - return this.getClass().getSimpleName() + '(' + this.getSequenceName() + ')'; - } - -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/id/TsidGenerator.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/id/TsidGenerator.java deleted file mode 100644 index 3ee1d6e62..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/id/TsidGenerator.java +++ /dev/null @@ -1,92 +0,0 @@ -package io.hypersistence.utils.hibernate.id; - -import io.hypersistence.tsid.TSID; -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import org.hibernate.HibernateException; -import org.hibernate.MappingException; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.id.Configurable; -import org.hibernate.id.IdentifierGenerator; -import org.hibernate.internal.util.config.ConfigurationHelper; -import org.hibernate.service.ServiceRegistry; -import org.hibernate.type.Type; - -import java.io.Serializable; -import java.util.Properties; -import java.util.function.Supplier; - -/** - * @author Vlad Mihalcea - */ -public class TsidGenerator implements IdentifierGenerator, Configurable { - - private TSID.Factory DEFAULT_TSID_FACTORY = TSID.Factory.builder() - .withRandomFunction(TSID.Factory.THREAD_LOCAL_RANDOM_FUNCTION) - .build(); - - /** - * Indicates the name of the TSID.Factory Supplier. - */ - public static final String TSID_FACTORY_SUPPLIER_PARAM = "tsid_factory_supplier"; - - private TSID.Factory tsidFactory = DEFAULT_TSID_FACTORY; - - private AttributeType idType; - - @Override - public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) - throws MappingException { - idType = AttributeType.valueOf(type.getReturnedClass()); - - String tsidSupplierClass = ConfigurationHelper.getString(TSID_FACTORY_SUPPLIER_PARAM, params); - if (tsidSupplierClass != null) { - Supplier factorySupplier = ReflectionUtils.newInstance(tsidSupplierClass); - tsidFactory = factorySupplier.get(); - } - } - - @Override - public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException { - return idType.cast(tsidFactory.generate()); - } - - enum AttributeType { - LONG { - @Override - public Serializable cast(TSID tsid) { - return tsid.toLong(); - } - }, - STRING { - @Override - public Serializable cast(TSID tsid) { - return tsid.toString(); - } - }, - TSID { - @Override - public Serializable cast(TSID tsid) { - return tsid; - } - }; - - public abstract Serializable cast(TSID tsid); - - static AttributeType valueOf(Class clazz) { - if(Long.class.isAssignableFrom(clazz)) { - return LONG; - } else if (String.class.isAssignableFrom(clazz)) { - return STRING; - } else if (TSID.class.isAssignableFrom(clazz)) { - return TSID; - } else { - throw new HibernateException( - String.format( - "The @Tsid annotation on [%s] can only be placed on a Long or String entity attribute!", - clazz - ) - ); - } - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/naming/CamelCaseToSnakeCaseNamingStrategy.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/naming/CamelCaseToSnakeCaseNamingStrategy.java deleted file mode 100644 index 5afe974e5..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/naming/CamelCaseToSnakeCaseNamingStrategy.java +++ /dev/null @@ -1,80 +0,0 @@ -package io.hypersistence.utils.hibernate.naming; - -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; - -/** - * Maps the JPA camelCase properties to snake_case database identifiers. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class CamelCaseToSnakeCaseNamingStrategy extends PhysicalNamingStrategyStandardImpl { - - public static final CamelCaseToSnakeCaseNamingStrategy INSTANCE = new CamelCaseToSnakeCaseNamingStrategy(); - - public static final String CAMEL_CASE_REGEX = "([a-z]+)([A-Z]+)"; - - public static final String SNAKE_CASE_PATTERN = "$1\\_$2"; - - private final Configuration configuration; - - /** - * Initialization constructor taking the default {@link Configuration} object. - */ - public CamelCaseToSnakeCaseNamingStrategy() { - this.configuration = Configuration.INSTANCE; - } - - /** - * Initialization constructor taking the {@link Class} and {@link Configuration} objects. - * - * @param configuration custom {@link Configuration} object. - */ - public CamelCaseToSnakeCaseNamingStrategy(Configuration configuration) { - this.configuration = configuration; - } - - @Override - public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment context) { - return formatIdentifier(super.toPhysicalCatalogName(name, context)); - } - - @Override - public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment context) { - return formatIdentifier(super.toPhysicalSchemaName(name, context)); - } - - @Override - public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) { - return formatIdentifier(super.toPhysicalTableName(name, context)); - } - - @Override - public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment context) { - return formatIdentifier(super.toPhysicalSequenceName(name, context)); - } - - @Override - public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) { - return formatIdentifier(super.toPhysicalColumnName(name, context)); - } - - private Identifier formatIdentifier(Identifier identifier) { - if (identifier != null) { - String name = identifier.getText(); - - String formattedName = name.replaceAll(CAMEL_CASE_REGEX, SNAKE_CASE_PATTERN).toLowerCase(); - - return !formattedName.equals(name) ? - Identifier.toIdentifier(formattedName, identifier.isQuoted()) : - identifier; - } else { - return null; - } - - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/ListResultTransformer.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/ListResultTransformer.java deleted file mode 100644 index b3af6b495..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/ListResultTransformer.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.hypersistence.utils.hibernate.query; - -import org.hibernate.transform.ResultTransformer; - -import java.util.List; - -/** - * The {@link ListResultTransformer} simplifies the way - * we can use a ResultTransformer by defining a default implementation for the - * {@link ResultTransformer#transformList(List)} method. - *

- * This way, the {@link ListResultTransformer} can be used - * as a functional interface. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - * @since 2.9.0 - */ -@FunctionalInterface -public interface ListResultTransformer extends ResultTransformer { - - /** - * Default implementation returning the tuples list as-is. - * - * @param tuples tuples list - * @return tuples list - */ - @Override - default List transformList(List tuples) { - return tuples; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/MapResultTransformer.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/MapResultTransformer.java deleted file mode 100644 index 44a6c3497..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/MapResultTransformer.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.hypersistence.utils.hibernate.query; - -import org.hibernate.HibernateException; -import org.hibernate.transform.ResultTransformer; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * The {@link MapResultTransformer} allows us to return - * a {@link Map} from a JPA {@link javax.persistence.Query}. - *

- * If there are aliases named as {@code key} or {@code value}, - * then those will be used. - *

- * Otherwise, the first column value is the key while the second one is the Map value. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - * @since 2.9.0 - */ -public class MapResultTransformer implements ResultTransformer { - - public static final String KEY_ALIAS = "map_key"; - - public static final String VALUE_ALIAS = "map_value"; - - private Map result = new HashMap<>(); - - /** - * Transform the tuple into a key/value pair. - *

- * If there are aliases named as {@code key} or {@code value}, - * then those will be used. - *

- * Otherwise, the first column value is the key while the second one is the Map value. - * - * @param tuple tuple to be transformed to a key/value pair - * @param aliases column aliases - * @return unmodified tuple - */ - @Override - public Object transformTuple(Object[] tuple, String[] aliases) { - int keyOrdinal = -1; - int valueOrdinal = -1; - - for (int i = 0; i < aliases.length; i++) { - String alias = aliases[i]; - if (KEY_ALIAS.equalsIgnoreCase(alias)) { - keyOrdinal = i; - } else if (VALUE_ALIAS.equalsIgnoreCase(alias)) { - valueOrdinal = i; - } - } - - if (keyOrdinal >= 0) { - if (valueOrdinal < 0) { - throw new HibernateException( - new IllegalArgumentException("A key column alias was given but no value column alias was found!") - ); - } - } else { - if (valueOrdinal >= 0) { - throw new HibernateException( - new IllegalArgumentException("A value column alias was given but no key column alias was found!") - ); - } else { - keyOrdinal = 0; - valueOrdinal = 1; - } - } - - @SuppressWarnings("unchecked") - K key = (K) tuple[keyOrdinal]; - @SuppressWarnings("unchecked") - V value = (V) tuple[valueOrdinal]; - result.put(key, value); - - return tuple; - } - - /** - * Return the {@link Map} instead of the default {@link List}. - * - * @param tuples tuples - * @return the {@link Map} result set - */ - @Override - public List transformList(List tuples) { - return Collections.singletonList(result); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/QueryStackTraceLogger.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/QueryStackTraceLogger.java deleted file mode 100644 index 34ce193b4..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/QueryStackTraceLogger.java +++ /dev/null @@ -1,82 +0,0 @@ -package io.hypersistence.utils.hibernate.query; - -import org.hibernate.resource.jdbc.spi.StatementInspector; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -/** - * The {@link QueryStackTraceLogger} allows you to log the stack trace that - * executed a given SQL query. - * - * @author Vlad Mihalcea - * @since 3.5.3 - */ -public class QueryStackTraceLogger implements StatementInspector { - - public static final String ORG_HIBERNATE ="org.hibernate"; - - public static String TAB = "\t"; - public static String NEW_LINE = System.getProperty("line.separator"); - - private static final Logger LOGGER = LoggerFactory.getLogger(QueryStackTraceLogger.class); - - private final String packageNamePrefix; - - public QueryStackTraceLogger(String packageNamePrefix) { - this.packageNamePrefix = packageNamePrefix; - } - - @Override - public String inspect(String sql) { - LOGGER.debug( - "This SQL query: [\n\t{}\n]\nwas generated by Hibernate like this: [\n{}\n]", - sql, - String.join( - NEW_LINE, - stackTraceElementsUpTo(packageNamePrefix) - .stream() - .map(e -> TAB + e.toString()) - .collect(Collectors.toList()) - ) - ); - return null; - } - - /** - * Filter the stack trace based up to the provided package name prefix - * - * @param endPackageNamePrefix package name to match the {@link StackTraceElement} - * @return the {@link StackTraceElement} up to the matching the provided package name - */ - private List stackTraceElementsUpTo(String endPackageNamePrefix) { - StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); - List filteredStackTraceElements = new ArrayList<>(); - boolean startPackageMatched = false; - boolean endPackageMatched = false; - for (StackTraceElement stackTraceElement : stackTraceElements) { - String className = stackTraceElement.getClassName(); - if(!startPackageMatched) { - if(className.startsWith(ORG_HIBERNATE)) { - startPackageMatched = true; - } else { - continue; - } - } - if(!className.contains(endPackageNamePrefix)) { - if(!endPackageMatched) { - filteredStackTraceElements.add(stackTraceElement); - } else { - break; - } - } else if(!endPackageMatched) { - endPackageMatched = true; - filteredStackTraceElements.add(stackTraceElement); - } - } - return filteredStackTraceElements; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/SQLExtractor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/SQLExtractor.java deleted file mode 100644 index dd245c0a0..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/query/SQLExtractor.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.hypersistence.utils.hibernate.query; - -import org.hibernate.query.internal.AbstractProducedQuery; - -import javax.persistence.Query; -import java.util.Collections; - -/** - * The {@link SQLExtractor} allows you to extract the - * underlying SQL query generated by a JPQL or JPA Criteria API query. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - * @since 2.9.11 - */ -public class SQLExtractor { - - protected SQLExtractor() { - } - - /** - * Get the underlying SQL generated by the provided JPA query. - * - * @param query JPA query - * @return the underlying SQL generated by the provided JPA query - */ - public static String from(Query query) { - AbstractProducedQuery abstractProducedQuery = query.unwrap(AbstractProducedQuery.class); - String[] sqls = abstractProducedQuery - .getProducer() - .getFactory() - .getQueryPlanCache() - .getHQLQueryPlan(abstractProducedQuery.getQueryString(), false, Collections.emptyMap()) - .getSqlStrings(); - - return sqls.length > 0 ? sqls[0] : null; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/AbstractHibernateType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/AbstractHibernateType.java deleted file mode 100644 index 7038cee22..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/AbstractHibernateType.java +++ /dev/null @@ -1,51 +0,0 @@ -package io.hypersistence.utils.hibernate.type; - -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.AbstractSingleColumnStandardBasicType; -import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; - -/** - * Very convenient base class for implementing object types using Hibernate Java and SQL descriptors. - * - * @author Vlad Mihalcea - */ -public abstract class AbstractHibernateType extends AbstractSingleColumnStandardBasicType { - - private final Configuration configuration; - - /** - * Initialization constructor taking the {@link SqlTypeDescriptor} and {@link JavaTypeDescriptor} objects, - * and using the default {@link Configuration} object. - * - * @param sqlTypeDescriptor the {@link SqlTypeDescriptor} to be used - * @param javaTypeDescriptor the {@link JavaTypeDescriptor} to be used - */ - protected AbstractHibernateType( - SqlTypeDescriptor sqlTypeDescriptor, - JavaTypeDescriptor javaTypeDescriptor) { - super(sqlTypeDescriptor, javaTypeDescriptor); - this.configuration = Configuration.INSTANCE; - } - - /** - * Initialization constructor taking the {@link SqlTypeDescriptor}, {@link JavaTypeDescriptor}, - * and {@link Configuration} objects. - * - * @param sqlTypeDescriptor the {@link SqlTypeDescriptor} to be used - * @param javaTypeDescriptor the {@link JavaTypeDescriptor} to be used - * @param configuration custom {@link Configuration} object. - */ - protected AbstractHibernateType(SqlTypeDescriptor sqlTypeDescriptor, JavaTypeDescriptor javaTypeDescriptor, Configuration configuration) { - super(sqlTypeDescriptor, javaTypeDescriptor); - this.configuration = configuration; - } - - /** - * Get the current {@link Configuration} object. - * @return the current {@link Configuration} object. - */ - protected Configuration getConfiguration() { - return configuration; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/HibernateTypesContributor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/HibernateTypesContributor.java deleted file mode 100644 index b573de120..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/HibernateTypesContributor.java +++ /dev/null @@ -1,176 +0,0 @@ -package io.hypersistence.utils.hibernate.type; - -import io.hypersistence.utils.hibernate.type.array.*; -import io.hypersistence.utils.hibernate.type.basic.*; -import io.hypersistence.utils.hibernate.type.interval.OracleIntervalDayToSecondType; -import io.hypersistence.utils.hibernate.type.interval.PostgreSQLIntervalType; -import io.hypersistence.utils.hibernate.type.interval.PostgreSQLPeriodType; -import io.hypersistence.utils.hibernate.type.json.*; -import io.hypersistence.utils.hibernate.type.money.CurrencyUnitType; -import io.hypersistence.utils.hibernate.type.money.MonetaryAmountType; -import io.hypersistence.utils.hibernate.type.range.PostgreSQLRangeType; -import io.hypersistence.utils.hibernate.type.range.guava.PostgreSQLGuavaRangeType; -import io.hypersistence.utils.hibernate.type.search.PostgreSQLTSVectorType; -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import org.hibernate.HibernateException; -import org.hibernate.boot.model.TypeContributions; -import org.hibernate.boot.model.TypeContributor; -import org.hibernate.dialect.*; -import org.hibernate.engine.config.spi.ConfigurationService; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.service.ServiceRegistry; -import org.hibernate.type.BasicType; -import org.hibernate.usertype.CompositeUserType; -import org.hibernate.usertype.UserType; - -import java.util.function.Predicate; - -/** - * The {@link HibernateTypesContributor} registers various types automatically. - * - * @author Vlad Mihalcea - * @since 2.15.0 - */ -public class HibernateTypesContributor implements TypeContributor { - - public static final String ENABLE_TYPES_CONTRIBUTOR = "hypersistence.utils.enable_types_contributor"; - - public static final String TYPES_CONTRIBUTOR_FILTER = "hypersistence.utils.types_contributor_filter"; - - @Override - public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { - ConfigurationService configurationService = serviceRegistry.getService(ConfigurationService.class); - Boolean enableTypesContributor = (Boolean) configurationService.getSetting(ENABLE_TYPES_CONTRIBUTOR, value -> { - if(value instanceof Boolean) { - return value; - } - if(value instanceof String) { - return Boolean.getBoolean((String) value); - } - throw new HibernateException( - String.format("The value [%s] of the [%s] setting is not supported!", value, ENABLE_TYPES_CONTRIBUTOR) - ); - }); - if(Boolean.FALSE.equals(enableTypesContributor)) { - return; - } - @SuppressWarnings("unchecked") - Predicate typeFilter = (Predicate) configurationService.getSetting(TYPES_CONTRIBUTOR_FILTER, value -> { - if(value instanceof Predicate) { - return value; - } - if(value instanceof Class) { - return ReflectionUtils.newInstance((Class) value); - } - if(value instanceof String) { - return ReflectionUtils.newInstance( - ReflectionUtils.getClass((String) value) - ); - } - throw new HibernateException( - String.format("The value of the [%s] setting is not supported!", TYPES_CONTRIBUTOR_FILTER) - ); - }); - if(typeFilter == null) { - typeFilter = o -> true; - } - - JdbcServices jdbcServices = serviceRegistry.getService(JdbcServices.class); - Dialect dialect = jdbcServices.getDialect(); - - boolean enableJson = ReflectionUtils.getClassOrNull("com.fasterxml.jackson.databind.ObjectMapper") != null; - - if(dialect instanceof PostgreSQL82Dialect) { - /* Arrays */ - this - .contributeType(typeContributions, BooleanArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, DateArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, DecimalArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, DoubleArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, EnumArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, IntArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, ListArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, LocalDateArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, LocalDateTimeArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, LongArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, StringArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, TimestampArrayType.INSTANCE, typeFilter) - .contributeType(typeContributions, UUIDArrayType.INSTANCE, typeFilter) - /* Date/Time */ - .contributeType(typeContributions, PostgreSQLIntervalType.INSTANCE, typeFilter) - .contributeType(typeContributions, PostgreSQLPeriodType.INSTANCE, typeFilter) - /* Specific-types */ - .contributeType(typeContributions, PostgreSQLTSVectorType.INSTANCE, typeFilter) - .contributeType(typeContributions, PostgreSQLEnumType.INSTANCE, typeFilter) - .contributeType(typeContributions, PostgreSQLHStoreType.INSTANCE, typeFilter) - .contributeType(typeContributions, PostgreSQLInetType.INSTANCE, typeFilter) - .contributeType(typeContributions, PostgreSQLRangeType.INSTANCE, typeFilter) - .contributeType(typeContributions, PostgreSQLCITextType.INSTANCE, typeFilter); - - if(ReflectionUtils.getClassOrNull("com.google.common.collect.Range") != null) { - this.contributeType(typeContributions, PostgreSQLGuavaRangeType.INSTANCE, typeFilter); - } - if(enableJson) { - /* JSON */ - this.contributeType(typeContributions, JsonBinaryType.INSTANCE, typeFilter); - } - } else if(dialect instanceof MySQLDialect) { - /* JSON */ - if (enableJson) { - this.contributeType(typeContributions, JsonStringType.INSTANCE, typeFilter) - .contributeType(typeContributions, JsonNodeStringType.INSTANCE, typeFilter); - } - } else if(dialect instanceof SQLServer2005Dialect) { - /* JSON */ - if (enableJson) { - this.contributeType(typeContributions, JsonStringType.INSTANCE, typeFilter); - } - } else if(dialect instanceof Oracle8iDialect) { - /* Date/Time */ - this - .contributeType(typeContributions, OracleIntervalDayToSecondType.INSTANCE, typeFilter); - /* JSON */ - if (enableJson) { - this.contributeType(typeContributions, JsonStringType.INSTANCE, typeFilter) - .contributeType(typeContributions, JsonBlobType.INSTANCE, typeFilter); - } - } - - /* Basic */ - this.contributeType(typeContributions, NullableCharacterType.INSTANCE, typeFilter) - /* Date/Time */ - .contributeType(typeContributions, Iso8601MonthType.INSTANCE, typeFilter) - .contributeType(typeContributions, MonthDayDateType.INSTANCE, typeFilter) - .contributeType(typeContributions, MonthDayIntegerType.INSTANCE, typeFilter) - .contributeType(typeContributions, YearMonthDateType.INSTANCE, typeFilter) - .contributeType(typeContributions, YearMonthEpochType.INSTANCE, typeFilter) - .contributeType(typeContributions, YearMonthIntegerType.INSTANCE, typeFilter) - .contributeType(typeContributions, YearMonthTimestampType.INSTANCE, typeFilter); - /* JSON */ - if (enableJson) { - this.contributeType(typeContributions, JsonType.INSTANCE, typeFilter); - } - /* Money and Currency API */ - if(ReflectionUtils.getClassOrNull("org.javamoney.moneta.Money") != null) { - this.contributeType(typeContributions, CurrencyUnitType.INSTANCE, typeFilter) - .contributeType(typeContributions, MonetaryAmountType.INSTANCE, typeFilter); - } - } - - private HibernateTypesContributor contributeType(TypeContributions typeContributions, Object type, Predicate typeFilter) { - if (typeFilter.test(type)) { - if (type instanceof BasicType) { - typeContributions.contributeType((BasicType) type); - } else if (type instanceof UserType) { - typeContributions.contributeType((UserType) type, type.getClass().getSimpleName()); - } else if (type instanceof CompositeUserType) { - typeContributions.contributeType((CompositeUserType) type, type.getClass().getSimpleName()); - } else { - throw new UnsupportedOperationException( - String.format("The [%s] is not supported!", type.getClass()) - ); - } - } - return this; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/ImmutableCompositeType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/ImmutableCompositeType.java deleted file mode 100644 index 7a728bb17..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/ImmutableCompositeType.java +++ /dev/null @@ -1,392 +0,0 @@ -package io.hypersistence.utils.hibernate.type; - -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.EntityMode; -import org.hibernate.FetchMode; -import org.hibernate.HibernateException; -import org.hibernate.MappingException; -import org.hibernate.engine.jdbc.Size; -import org.hibernate.engine.spi.*; -import org.hibernate.internal.util.collections.ArrayHelper; -import org.hibernate.type.BasicType; -import org.hibernate.type.CompositeType; -import org.hibernate.type.ForeignKeyDirection; -import org.hibernate.type.Type; -import org.hibernate.type.descriptor.java.IncomparableComparator; -import org.hibernate.usertype.CompositeUserType; - -import java.io.Serializable; -import java.lang.reflect.Method; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.*; -import java.util.stream.Collectors; - -/** - * Very convenient base class for implementing immutable object types using Hibernate {@link CompositeUserType}. - *

- * The {@link ImmutableCompositeType} implements the {@link Type} interface too, so you can pass all - * types extending the {@link ImmutableCompositeType} to the {@link org.hibernate.query.NativeQuery#addScalar(String, Type)} - * method to fix the No Dialect mapping for JDBC type issues. - * - * @author Vlad Mihalcea - */ -public abstract class ImmutableCompositeType implements CompositeUserType, CompositeType, BasicType { - - private final Configuration configuration; - - private final Class clazz; - - private final List clazzMethods; - - /** - * Initialization constructor taking the {@link Class} - * and using the default {@link Configuration} object. - * - * @param clazz the entity attribute {@link Class} type to be handled - */ - protected ImmutableCompositeType(Class clazz) { - this(clazz, Configuration.INSTANCE); - } - - /** - * Initialization constructor taking the {@link Class} and {@link Configuration} objects. - * - * @param clazz the entity attribute {@link Class} type to be handled - * @param configuration custom {@link Configuration} object. - */ - protected ImmutableCompositeType(Class clazz, Configuration configuration) { - this.clazz = clazz; - this.configuration = configuration; - this.clazzMethods = Collections.unmodifiableList(Arrays.asList(clazz.getMethods())); - } - - /** - * Get the current {@link Configuration} object. - * - * @return the current {@link Configuration} object. - */ - protected Configuration getConfiguration() { - return configuration; - } - - /** - * Get the column value from the JDBC {@link ResultSet}. - * - * @param rs JDBC {@link ResultSet} - * @param names database column name - * @param session current Hibernate {@link org.hibernate.Session} - * @param owner current Hibernate {@link SessionFactoryImplementor} - * @return column value - * @throws SQLException in case of failure - */ - protected abstract T get(ResultSet rs, String[] names, - SharedSessionContractImplementor session, Object owner) throws SQLException; - - /** - * Set the column value on the provided JDBC {@link PreparedStatement}. - * - * @param st JDBC {@link PreparedStatement} - * @param value database column value - * @param index database column index - * @param session current Hibernate {@link org.hibernate.Session} - * @throws SQLException in case of failure - */ - protected abstract void set(PreparedStatement st, T value, int index, - SharedSessionContractImplementor session) throws SQLException; - - /* Methods inherited from the {@link UserType} interface */ - - @Override - public Object nullSafeGet(ResultSet rs, String[] names, - SharedSessionContractImplementor session, Object owner) throws SQLException { - return get(rs, names, session, owner); - } - - @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, - SharedSessionContractImplementor session) throws SQLException { - set(st, clazz.cast(value), index, session); - } - - @Override - public Class returnedClass() { - return clazz; - } - - @Override - public boolean equals(Object x, Object y) { - return (x == y) || (x != null && x.equals(y)); - } - - @Override - public int hashCode(Object x) { - return x.hashCode(); - } - - @Override - public Object deepCopy(Object value) { - return value; - } - - @Override - public boolean isMutable() { - return false; - } - - @Override - public Serializable disassemble(Object o, SharedSessionContractImplementor session) { - return (Serializable) o; - } - - @Override - public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return cached; - } - - @Override - public Object replace(Object o, Object target, SharedSessionContractImplementor session, Object owner) { - return o; - } - - /* Methods inherited from the {@link Type} interface */ - - @Override - public boolean isAssociationType() { - return false; - } - - @Override - public boolean isCollectionType() { - return false; - } - - @Override - public boolean isEntityType() { - return false; - } - - @Override - public boolean isAnyType() { - return false; - } - - @Override - public boolean isComponentType() { - return true; - } - - @Override - public int getColumnSpan(Mapping mapping) throws MappingException { - return getPropertyTypes().length; - } - - @Override - public int[] sqlTypes(Mapping mapping) throws MappingException { - List sqlTypes= new ArrayList<>(); - Type[] types = getPropertyTypes(); - for (int i = 0; i < types.length; i++) { - sqlTypes.addAll( - Arrays.stream(types[i].sqlTypes(mapping)).boxed().collect(Collectors.toList()) - ); - } - return sqlTypes.stream().mapToInt(i->i).toArray(); - } - - @Override - public Size[] dictatedSizes(Mapping mapping) throws MappingException { - return new Size[]{new Size()}; - } - - @Override - public Size[] defaultSizes(Mapping mapping) throws MappingException { - return dictatedSizes(mapping); - } - - @Override - public Class getReturnedClass() { - return returnedClass(); - } - - @Override - public boolean isSame(Object x, Object y) throws HibernateException { - return equals(x, y); - } - - @Override - public boolean isEqual(Object x, Object y) throws HibernateException { - return equals(x, y); - } - - @Override - public boolean isEqual(Object x, Object y, SessionFactoryImplementor factory) throws HibernateException { - return equals(x, y); - } - - @Override - public int getHashCode(Object x) throws HibernateException { - return hashCode(x); - } - - @Override - public int getHashCode(Object x, SessionFactoryImplementor factory) throws HibernateException { - return hashCode(x); - } - - @Override - public int compare(Object x, Object y) { - return IncomparableComparator.INSTANCE.compare(x, y); - } - - @Override - public final boolean isDirty(Object old, Object current, SharedSessionContractImplementor session) { - return isDirty(old, current); - } - - @Override - public final boolean isDirty(Object old, Object current, boolean[] checkable, SharedSessionContractImplementor session) { - return checkable[0] && isDirty(old, current); - } - - protected final boolean isDirty(Object old, Object current) { - return !isSame(old, current); - } - - @Override - public boolean isModified(Object dbState, Object currentState, boolean[] checkable, SharedSessionContractImplementor session) throws HibernateException { - return isDirty(dbState, currentState); - } - - @Override - public Object nullSafeGet(ResultSet rs, String name, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - return get(rs, new String[]{name}, session, owner); - } - - @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, boolean[] settable, SharedSessionContractImplementor session) throws HibernateException, SQLException { - set(st, returnedClass().cast(value), index, session); - } - - @Override - public String toLoggableString(Object value, SessionFactoryImplementor factory) throws HibernateException { - return String.valueOf(value); - } - - @Override - public String getName() { - return getClass().getSimpleName(); - } - - @Override - public Object deepCopy(Object value, SessionFactoryImplementor factory) throws HibernateException { - return deepCopy(value); - } - - @Override - public Serializable disassemble(Object value, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return disassemble(value, session); - } - - @Override - public void beforeAssemble(Serializable cached, SharedSessionContractImplementor session) { - - } - - @Override - public Object hydrate(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - return nullSafeGet(rs, names, session, owner); - } - - @Override - public Object resolve(Object value, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return value; - } - - @Override - public Object semiResolve(Object value, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return value; - } - - @Override - public Type getSemiResolvedType(SessionFactoryImplementor factory) { - return this; - } - - @Override - public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner, Map copyCache) throws HibernateException { - return replace(original, target, session, owner); - } - - @Override - public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner, Map copyCache, ForeignKeyDirection foreignKeyDirection) throws HibernateException { - return replace(original, target, session, owner); - } - - @Override - public boolean[] toColumnNullness(Object value, Mapping mapping) { - return value == null ? ArrayHelper.FALSE : ArrayHelper.TRUE; - } - - @Override - public String[] getRegistrationKeys() { - return new String[]{ - getName() - }; - } - - @Override - public Type[] getSubtypes() { - return getPropertyTypes(); - } - - @Override - public boolean[] getPropertyNullability() { - return new boolean[]{false, false}; - } - - @Override - public Object[] getPropertyValues(Object component, SharedSessionContractImplementor session) throws HibernateException { - return new Object[]{getPropertyValue(component, 0), getPropertyValue(component, 1)}; - } - - @Override - public Object[] getPropertyValues(Object component, EntityMode entityMode) throws HibernateException { - return new Object[]{getPropertyValue(component, 0), getPropertyValue(component, 1)}; - } - - @Override - public Object getPropertyValue(Object component, int index, SharedSessionContractImplementor session) throws HibernateException { - return getPropertyValue(component, index); - } - - @Override - public void setPropertyValues(Object component, Object[] values, EntityMode entityMode) throws HibernateException { - throw new HibernateException("Calling setPropertyValues is illegal on on " + clazz.getName() + " because it's an immutable object!"); - } - - @Override - public CascadeStyle getCascadeStyle(int index) { - return CascadeStyles.NONE; - } - - @Override - public FetchMode getFetchMode(int index) { - return FetchMode.DEFAULT; - } - - @Override - public boolean isMethodOf(Method method) { - return clazzMethods.contains(method); - } - - @Override - public boolean isEmbedded() { - return false; - } - - @Override - public boolean hasNotNullProperty() { - return true; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/ImmutableType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/ImmutableType.java deleted file mode 100644 index 0bb03e277..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/ImmutableType.java +++ /dev/null @@ -1,330 +0,0 @@ -package io.hypersistence.utils.hibernate.type; - -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.HibernateException; -import org.hibernate.MappingException; -import org.hibernate.engine.jdbc.Size; -import org.hibernate.engine.spi.Mapping; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.internal.util.collections.ArrayHelper; -import org.hibernate.type.BasicType; -import org.hibernate.type.ForeignKeyDirection; -import org.hibernate.type.Type; -import org.hibernate.type.descriptor.java.IncomparableComparator; -import org.hibernate.usertype.UserType; - -import java.io.Serializable; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Map; - -/** - * Very convenient base class for implementing immutable object types using Hibernate {@link UserType}. - *

- * The {@link ImmutableType} implements the {@link Type} interface too, so you can pass all - * types extending the {@link ImmutableType} to the {@link org.hibernate.query.NativeQuery#addScalar(String, Type)} - * method to fix the No Dialect mapping for JDBC type issues. - * - * @author Vlad Mihalcea - */ -public abstract class ImmutableType implements UserType, BasicType { - - private final Configuration configuration; - - private final Class clazz; - - /** - * Initialization constructor taking the {@link Class} - * and using the default {@link Configuration} object. - * - * @param clazz the entity attribute {@link Class} type to be handled - */ - protected ImmutableType(Class clazz) { - this.clazz = clazz; - this.configuration = Configuration.INSTANCE; - } - - /** - * Initialization constructor taking the {@link Class} and {@link Configuration} objects. - * - * @param clazz the entity attribute {@link Class} type to be handled - * @param configuration custom {@link Configuration} object. - */ - protected ImmutableType(Class clazz, Configuration configuration) { - this.clazz = clazz; - this.configuration = configuration; - } - - /** - * Get the current {@link Configuration} object. - * - * @return the current {@link Configuration} object. - */ - protected Configuration getConfiguration() { - return configuration; - } - - /** - * Get the column value from the JDBC {@link ResultSet}. - * - * @param rs JDBC {@link ResultSet} - * @param names database column name - * @param session current Hibernate {@link org.hibernate.Session} - * @param owner current Hibernate {@link SessionFactoryImplementor} - * @return column value - * @throws SQLException in case of failure - */ - protected abstract T get(ResultSet rs, String[] names, - SharedSessionContractImplementor session, Object owner) throws SQLException; - - /** - * Set the column value on the provided JDBC {@link PreparedStatement}. - * - * @param st JDBC {@link PreparedStatement} - * @param value database column value - * @param index database column index - * @param session current Hibernate {@link org.hibernate.Session} - * @throws SQLException in case of failure - */ - protected abstract void set(PreparedStatement st, T value, int index, - SharedSessionContractImplementor session) throws SQLException; - - /* Methods inherited from the {@link UserType} interface */ - - @Override - public Object nullSafeGet(ResultSet rs, String[] names, - SharedSessionContractImplementor session, Object owner) throws SQLException { - return get(rs, names, session, owner); - } - - @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, - SharedSessionContractImplementor session) throws SQLException { - set(st, clazz.cast(value), index, session); - } - - @Override - public Class returnedClass() { - return clazz; - } - - @Override - public boolean equals(Object x, Object y) { - return (x == y) || (x != null && x.equals(y)); - } - - @Override - public int hashCode(Object x) { - return x.hashCode(); - } - - @Override - public Object deepCopy(Object value) { - return value; - } - - @Override - public boolean isMutable() { - return false; - } - - @Override - public Serializable disassemble(Object o) { - return (Serializable) o; - } - - @Override - public Object assemble(Serializable cached, Object owner) { - return cached; - } - - @Override - public Object replace(Object o, Object target, Object owner) { - return o; - } - - /* Methods inherited from the {@link Type} interface */ - - @Override - public boolean isAssociationType() { - return false; - } - - @Override - public boolean isCollectionType() { - return false; - } - - @Override - public boolean isEntityType() { - return false; - } - - @Override - public boolean isAnyType() { - return false; - } - - @Override - public boolean isComponentType() { - return false; - } - - @Override - public int getColumnSpan(Mapping mapping) throws MappingException { - return 1; - } - - @Override - public int[] sqlTypes(Mapping mapping) throws MappingException { - return sqlTypes(); - } - - @Override - public Size[] dictatedSizes(Mapping mapping) throws MappingException { - return new Size[]{new Size()}; - } - - @Override - public Size[] defaultSizes(Mapping mapping) throws MappingException { - return dictatedSizes(mapping); - } - - @Override - public Class getReturnedClass() { - return returnedClass(); - } - - @Override - public boolean isSame(Object x, Object y) throws HibernateException { - return equals(x, y); - } - - @Override - public boolean isEqual(Object x, Object y) throws HibernateException { - return equals(x, y); - } - - @Override - public boolean isEqual(Object x, Object y, SessionFactoryImplementor factory) throws HibernateException { - return equals(x, y); - } - - @Override - public int getHashCode(Object x) throws HibernateException { - return hashCode(x); - } - - @Override - public int getHashCode(Object x, SessionFactoryImplementor factory) throws HibernateException { - return hashCode(x); - } - - @Override - public int compare(Object x, Object y) { - return IncomparableComparator.INSTANCE.compare(x, y); - } - - @Override - public final boolean isDirty(Object old, Object current, SharedSessionContractImplementor session) { - return isDirty(old, current); - } - - @Override - public final boolean isDirty(Object old, Object current, boolean[] checkable, SharedSessionContractImplementor session) { - return checkable[0] && isDirty(old, current); - } - - protected final boolean isDirty(Object old, Object current) { - return !isSame(old, current); - } - - @Override - public boolean isModified(Object dbState, Object currentState, boolean[] checkable, SharedSessionContractImplementor session) throws HibernateException { - return isDirty(dbState, currentState); - } - - @Override - public Object nullSafeGet(ResultSet rs, String name, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - return get(rs, new String[]{name}, session, owner); - } - - @Override - public void nullSafeSet(PreparedStatement st, Object value, int index, boolean[] settable, SharedSessionContractImplementor session) throws HibernateException, SQLException { - set(st, returnedClass().cast(value), index, session); - } - - @Override - public String toLoggableString(Object value, SessionFactoryImplementor factory) throws HibernateException { - return String.valueOf(value); - } - - @Override - public String getName() { - return getClass().getSimpleName(); - } - - @Override - public Object deepCopy(Object value, SessionFactoryImplementor factory) throws HibernateException { - return deepCopy(value); - } - - @Override - public Serializable disassemble(Object value, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return disassemble(value); - } - - @Override - public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return assemble(cached, session); - } - - @Override - public void beforeAssemble(Serializable cached, SharedSessionContractImplementor session) { - - } - - @Override - public Object hydrate(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { - return nullSafeGet(rs, names, session, owner); - } - - @Override - public Object resolve(Object value, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return value; - } - - @Override - public Object semiResolve(Object value, SharedSessionContractImplementor session, Object owner) throws HibernateException { - return value; - } - - @Override - public Type getSemiResolvedType(SessionFactoryImplementor factory) { - return this; - } - - @Override - public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner, Map copyCache) throws HibernateException { - return replace(original, target, owner); - } - - @Override - public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner, Map copyCache, ForeignKeyDirection foreignKeyDirection) throws HibernateException { - return replace(original, target, owner); - } - - @Override - public boolean[] toColumnNullness(Object value, Mapping mapping) { - return value == null ? ArrayHelper.FALSE : ArrayHelper.TRUE; - } - - @Override - public String[] getRegistrationKeys() { - return new String[]{ - getName() - }; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/BooleanArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/BooleanArrayType.java deleted file mode 100644 index 3561de0aa..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/BooleanArrayType.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.BooleanArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; - -/** - * Maps a {@code boolean[]} array on a PostgreSQL ARRAY column type. - * For more details about how to use it, check out this article. - * - * @author jeet.choudhary7@gmail.com - * @version 2.9.13 - */ -public class BooleanArrayType extends AbstractArrayType { - - public static final BooleanArrayType INSTANCE = new BooleanArrayType(); - - public BooleanArrayType(Configuration configuration) { - super( - new BooleanArrayTypeDescriptor(), - configuration - ); - } - - public BooleanArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - public BooleanArrayType() { - super( - new BooleanArrayTypeDescriptor() - ); - } - - @Override - public String getName() { - return "boolean-array"; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DateArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DateArrayType.java deleted file mode 100644 index aee55f54f..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DateArrayType.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.DateArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Date; -import java.util.Properties; - -/** - * Maps an {@code Date[]} array on a PostgreSQL date[] ARRAY type. Multidimensional arrays are supported as well, as explained in this article. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Guillaume Briand - */ -public class DateArrayType extends AbstractArrayType { - - public static final DateArrayType INSTANCE = new DateArrayType(); - - public DateArrayType() { - super( - new DateArrayTypeDescriptor() - ); - } - - public DateArrayType(Configuration configuration) { - super( - new DateArrayTypeDescriptor(), configuration - ); - } - - public DateArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - public String getName() { - return "date-array"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DecimalArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DecimalArrayType.java deleted file mode 100644 index f56d15cc7..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DecimalArrayType.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.DecimalArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.math.BigDecimal; -import java.util.Properties; - -/** - * Maps a {@code decimal[]} array on a PostgreSQL ARRAY column type. - * For more details about how to use it, check out this article. - * - * @author Moritz Kobel - */ -public class DecimalArrayType extends AbstractArrayType { - - public static final DecimalArrayType INSTANCE = new DecimalArrayType(); - - public DecimalArrayType(Configuration configuration) { - super( - new DecimalArrayTypeDescriptor(), - configuration - ); - } - - public DecimalArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - public DecimalArrayType() { - super( - new DecimalArrayTypeDescriptor() - ); - } - - @Override - public String getName() { - return "decimal-array"; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DoubleArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DoubleArrayType.java deleted file mode 100644 index 103fd87d8..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/DoubleArrayType.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.DoubleArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; - -/** - * Maps a {@code double[]} array on a PostgreSQL ARRAY type. Multidimensional arrays are supported as well, as explained in this article. - *

- * For more details about how to use it, check out this - * article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class DoubleArrayType extends AbstractArrayType { - - public static final DoubleArrayType INSTANCE = new DoubleArrayType(); - - public DoubleArrayType() { - super( - new DoubleArrayTypeDescriptor() - ); - } - - public DoubleArrayType(Configuration configuration) { - super( - new DoubleArrayTypeDescriptor(), - configuration - ); - } - - public DoubleArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - @Override - public String getName() { - return "double-array"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/EnumArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/EnumArrayType.java deleted file mode 100644 index dce8b99f3..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/EnumArrayType.java +++ /dev/null @@ -1,76 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.array.internal.EnumArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.annotations.Type; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.lang.annotation.Annotation; -import java.util.Properties; - -/** - * Maps an {@code Enum[]} array on a database ARRAY type. Multidimensional arrays are supported as well, as explained in this article. - *

- * The {@code SQL_ARRAY_TYPE} parameter is used to define the enum type name in the database. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Nazir El-Kayssi - * @author Vlad Mihalcea - */ -public class EnumArrayType extends AbstractArrayType { - - public static final EnumArrayType INSTANCE = new EnumArrayType(); - private static final String DEFAULT_TYPE_NAME = "%s_enum_array_type"; - - private String name; - - public EnumArrayType() { - super( - new EnumArrayTypeDescriptor() - ); - } - - public EnumArrayType(Configuration configuration) { - super( - new EnumArrayTypeDescriptor(), - configuration - ); - } - - public EnumArrayType(Class arrayClass, String sqlArrayType) { - this(); - Properties parameters = new Properties(); - parameters.setProperty(SQL_ARRAY_TYPE, sqlArrayType); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - public String getName() { - return name; - } - - @Override - public void setParameterValues(Properties parameters) { - DynamicParameterizedType.ParameterType parameterType = (ParameterType) parameters.get(DynamicParameterizedType.PARAMETER_TYPE); - Annotation[] annotations = parameterType.getAnnotationsMethod(); - if (annotations != null) { - for (int i = 0; i < annotations.length; i++) { - Annotation annotation = annotations[i]; - if (Type.class.isAssignableFrom(annotation.annotationType())) { - Type type = (Type) annotation; - name = type.type(); - break; - } - } - } - if (name == null) { - name = String.format(DEFAULT_TYPE_NAME, parameters.getProperty(SQL_ARRAY_TYPE)); - } - ((AbstractArrayTypeDescriptor) getJavaTypeDescriptor()).setParameterValues(parameters); - } - -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/FloatArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/FloatArrayType.java deleted file mode 100644 index d230911ff..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/FloatArrayType.java +++ /dev/null @@ -1,49 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.FloatArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; - -/** - * Maps a {@code float[]} array on a PostgreSQL ARRAY type. Multidimensional arrays are supported as well, as explained in this article. - *

- * For more details about how to use it, check out this - * article on vladmihalcea.com. - * - * @author Vlad Mihalcea - * @author Andreas Eberle - */ -public class FloatArrayType extends AbstractArrayType { - - public static final FloatArrayType INSTANCE = new FloatArrayType(); - - public FloatArrayType() { - super( - new FloatArrayTypeDescriptor() - ); - } - - public FloatArrayType(Configuration configuration) { - super( - new FloatArrayTypeDescriptor(), - configuration - ); - } - - public FloatArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - @Override - public String getName() { - return "float-array"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/IntArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/IntArrayType.java deleted file mode 100644 index d415bf197..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/IntArrayType.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.IntArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; - -/** - * Maps an {@code int[]} array on a PostgreSQL ARRAY type. Multidimensional arrays are supported as well, as explained in this article. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class IntArrayType extends AbstractArrayType { - - public static final IntArrayType INSTANCE = new IntArrayType(); - - public IntArrayType() { - super( - new IntArrayTypeDescriptor() - ); - } - - public IntArrayType(Configuration configuration) { - super( - new IntArrayTypeDescriptor(), configuration - ); - } - - public IntArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - public String getName() { - return "int-array"; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/ListArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/ListArrayType.java deleted file mode 100644 index 07c4d7144..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/ListArrayType.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.ListArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; - -/** - * Maps an {@link java.util.List} entity attribute on a PostgreSQL ARRAY column type. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class ListArrayType extends AbstractArrayType implements DynamicParameterizedType { - - public static final ListArrayType INSTANCE = new ListArrayType(); - - public ListArrayType() { - super( - new ListArrayTypeDescriptor() - ); - } - - public ListArrayType(Configuration configuration) { - super( - new ListArrayTypeDescriptor(), configuration - ); - } - - public String getName() { - return "list-array"; - } - - @Override - public void setParameterValues(Properties parameters) { - ((DynamicParameterizedType) getJavaTypeDescriptor()).setParameterValues(parameters); - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LocalDateArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LocalDateArrayType.java deleted file mode 100644 index 33d5d09f2..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LocalDateArrayType.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.LocalDateArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; - -/** - * Maps a {@code java.Time.LocalDate[]} array on a PostgreSQL date[] ARRAY type. Multidimensional arrays are - * supported as well, as - * explained in this article. - *

- * For more details about how to use it, check out - * this - * article on vladmihalcea.com. - * - * @author Andrew Lazarus, based on DateArrayType by Guillaume Briand - */ - -public class LocalDateArrayType extends AbstractArrayType { - - public static final LocalDateArrayType INSTANCE = - new LocalDateArrayType(); - - public LocalDateArrayType() { - super( - new LocalDateArrayTypeDescriptor() - ); - } - - public LocalDateArrayType(Configuration configuration) { - super( - new LocalDateArrayTypeDescriptor(), configuration - ); - } - - public LocalDateArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - public String getName() { - return "localdate-array"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LocalDateTimeArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LocalDateTimeArrayType.java deleted file mode 100644 index 51b9f8ba6..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LocalDateTimeArrayType.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.LocalDateTimeArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; - -/** - * Maps a {@code java.Time.LocalDateTime[]} array on a PostgreSQL timestamp[] ARRAY type. Multidimensional arrays are - * supported as well, as - * explained in this article. - *

- * For more details about how to use it, check out - * this - * article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ - -public class LocalDateTimeArrayType extends AbstractArrayType { - - public static final LocalDateTimeArrayType INSTANCE = - new LocalDateTimeArrayType(); - - public LocalDateTimeArrayType() { - super( - new LocalDateTimeArrayTypeDescriptor() - ); - } - - public LocalDateTimeArrayType(Configuration configuration) { - super( - new LocalDateTimeArrayTypeDescriptor(), configuration - ); - } - - public LocalDateTimeArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - public String getName() { - return "localdatetime-array"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LongArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LongArrayType.java deleted file mode 100644 index 7bcef1622..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/LongArrayType.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.LongArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; - -/** - * Maps an {@code long[]} array on a PostgreSQL ARRAY type. Multidimensional arrays are supported as well, as explained in this article. - *

- * For more details about how to use it, check out this - * article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class LongArrayType extends AbstractArrayType { - - public static final LongArrayType INSTANCE = new LongArrayType(); - - public LongArrayType() { - super( - new LongArrayTypeDescriptor() - ); - } - - public LongArrayType(Configuration configuration) { - super( - new LongArrayTypeDescriptor(), - configuration - ); - } - - public LongArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - @Override - public String getName() { - return "long-array"; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/StringArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/StringArrayType.java deleted file mode 100644 index dddb7e54b..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/StringArrayType.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.StringArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; - -/** - * Maps an {@code String[]} array on a PostgreSQL ARRAY type. Multidimensional arrays are supported as well, as explained in this article. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class StringArrayType extends AbstractArrayType { - - public static final StringArrayType INSTANCE = new StringArrayType(); - - public StringArrayType() { - super( - new StringArrayTypeDescriptor() - ); - } - - public StringArrayType(Configuration configuration) { - super( - new StringArrayTypeDescriptor(), - configuration - ); - } - - public StringArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - public String getName() { - return "string-array"; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/TimestampArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/TimestampArrayType.java deleted file mode 100644 index 8596c81f1..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/TimestampArrayType.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.TimestampArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Date; -import java.util.Properties; - -/** - * Maps an {@code Date[]} array on a PostgreSQL timestamp[] ARRAY type. Multidimensional arrays are supported as well, as explained in this article. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class TimestampArrayType extends AbstractArrayType { - - public static final TimestampArrayType INSTANCE = new TimestampArrayType(); - - public TimestampArrayType() { - super( - new TimestampArrayTypeDescriptor() - ); - } - - public TimestampArrayType(Configuration configuration) { - super( - new TimestampArrayTypeDescriptor(), configuration - ); - } - - public TimestampArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - public String getName() { - return "timestamp-array"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/UUIDArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/UUIDArrayType.java deleted file mode 100644 index 12d856196..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/UUIDArrayType.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.array.internal.UUIDArrayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.type.util.ParameterizedParameterType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; -import java.util.UUID; - -/** - * Maps an {@code UUID[]} array on a PostgreSQL ARRAY type. Multidimensional arrays are supported as well, as explained in this article. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Rafael Acevedo - */ -public class UUIDArrayType extends AbstractArrayType { - - public static final UUIDArrayType INSTANCE = new UUIDArrayType(); - - public UUIDArrayType() { - super( - new UUIDArrayTypeDescriptor() - ); - } - - public UUIDArrayType(Configuration configuration) { - super( - new UUIDArrayTypeDescriptor(), - configuration - ); - } - - public UUIDArrayType(Class arrayClass) { - this(); - Properties parameters = new Properties(); - parameters.put(DynamicParameterizedType.PARAMETER_TYPE, new ParameterizedParameterType(arrayClass)); - setParameterValues(parameters); - } - - public String getName() { - return "uuid-array"; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/AbstractArrayType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/AbstractArrayType.java deleted file mode 100644 index ce26465b2..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/AbstractArrayType.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; - -/** - * Base class for all ARRAY types. - * - * @author Vlad Mihalcea - */ -public abstract class AbstractArrayType - extends AbstractHibernateType - implements DynamicParameterizedType { - - public static final String SQL_ARRAY_TYPE = "sql_array_type"; - - public AbstractArrayType(AbstractArrayTypeDescriptor arrayTypeDescriptor) { - super( - ArraySqlTypeDescriptor.INSTANCE, - arrayTypeDescriptor - ); - } - - public AbstractArrayType(AbstractArrayTypeDescriptor arrayTypeDescriptor, Configuration configuration) { - super( - ArraySqlTypeDescriptor.INSTANCE, - arrayTypeDescriptor, - configuration - ); - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } - - @Override - public void setParameterValues(Properties parameters) { - ((AbstractArrayTypeDescriptor) getJavaTypeDescriptor()).setParameterValues(parameters); - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/AbstractArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/AbstractArrayTypeDescriptor.java deleted file mode 100644 index 1d9e4d1e3..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/AbstractArrayTypeDescriptor.java +++ /dev/null @@ -1,107 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -import org.hibernate.HibernateException; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; -import org.hibernate.type.descriptor.java.MutabilityPlan; -import org.hibernate.type.descriptor.java.MutableMutabilityPlan; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.sql.Array; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.Properties; - -import static io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType.SQL_ARRAY_TYPE; - -/** - * @author Vlad Mihalcea - */ -public abstract class AbstractArrayTypeDescriptor - extends AbstractTypeDescriptor implements DynamicParameterizedType { - - private Class arrayObjectClass; - - private String sqlArrayType; - - public AbstractArrayTypeDescriptor(Class arrayObjectClass) { - this(arrayObjectClass, (MutabilityPlan) new MutableMutabilityPlan() { - @Override - protected T deepCopyNotNull(Object value) { - return ArrayUtil.deepCopy(value); - } - }); - } - - protected AbstractArrayTypeDescriptor(Class arrayObjectClass, MutabilityPlan mutableMutabilityPlan) { - super(arrayObjectClass, mutableMutabilityPlan); - this.arrayObjectClass = arrayObjectClass; - } - - public Class getArrayObjectClass() { - return arrayObjectClass; - } - - public void setArrayObjectClass(Class arrayObjectClass) { - this.arrayObjectClass = arrayObjectClass; - } - - @Override - public void setParameterValues(Properties parameters) { - if (parameters.containsKey(PARAMETER_TYPE)) { - arrayObjectClass = ((ParameterType) parameters.get(PARAMETER_TYPE)).getReturnedClass(); - } - sqlArrayType = parameters.getProperty(SQL_ARRAY_TYPE); - } - - @Override - public boolean areEqual(T one, T another) { - if (one == another) { - return true; - } - if (one == null || another == null) { - return false; - } - return ArrayUtil.isEquals(one, another); - } - - @Override - public String toString(T value) { - return Arrays.deepToString(ArrayUtil.wrapArray(value)); - } - - @Override - public T fromString(String string) { - return ArrayUtil.fromString(string, arrayObjectClass); - } - - @Override - public String extractLoggableRepresentation(T value) { - return (value == null) ? "null" : toString(value); - } - - @SuppressWarnings({"unchecked"}) - @Override - public X unwrap(T value, Class type, WrapperOptions options) { - return (X) ArrayUtil.wrapArray(value); - } - - @Override - public T wrap(X value, WrapperOptions options) { - if (value instanceof Array) { - Array array = (Array) value; - try { - return ArrayUtil.unwrapArray((Object[]) array.getArray(), arrayObjectClass); - } catch (SQLException e) { - throw new HibernateException( - new IllegalArgumentException(e) - ); - } - } - return (T) value; - } - - protected String getSqlArrayType() { - return sqlArrayType; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ArraySqlTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ArraySqlTypeDescriptor.java deleted file mode 100644 index 638ea67a4..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ArraySqlTypeDescriptor.java +++ /dev/null @@ -1,70 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -import org.hibernate.type.descriptor.ValueBinder; -import org.hibernate.type.descriptor.ValueExtractor; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.hibernate.type.descriptor.sql.BasicBinder; -import org.hibernate.type.descriptor.sql.BasicExtractor; -import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; - -import java.sql.*; - -/** - * @author Vlad Mihalcea - */ -public class ArraySqlTypeDescriptor implements SqlTypeDescriptor { - - public static final ArraySqlTypeDescriptor INSTANCE = new ArraySqlTypeDescriptor(); - - @Override - public int getSqlType() { - return Types.ARRAY; - } - - @Override - public boolean canBeRemapped() { - return true; - } - - @Override - public ValueBinder getBinder(final JavaTypeDescriptor javaTypeDescriptor) { - return new BasicBinder(javaTypeDescriptor, this) { - @Override - protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { - AbstractArrayTypeDescriptor abstractArrayTypeDescriptor = (AbstractArrayTypeDescriptor) javaTypeDescriptor; - st.setArray(index, st.getConnection().createArrayOf( - abstractArrayTypeDescriptor.getSqlArrayType(), - abstractArrayTypeDescriptor.unwrap(value, Object[].class, options) - )); - } - - @Override - protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) - throws SQLException { - throw new UnsupportedOperationException("Binding by name is not supported!"); - } - }; - } - - @Override - public ValueExtractor getExtractor(final JavaTypeDescriptor javaTypeDescriptor) { - return new BasicExtractor(javaTypeDescriptor, this) { - @Override - protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException { - return javaTypeDescriptor.wrap(rs.getArray(name), options); - } - - @Override - protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException { - return javaTypeDescriptor.wrap(statement.getArray(index), options); - } - - @Override - protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException { - return javaTypeDescriptor.wrap(statement.getArray(name), options); - } - }; - } - -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ArrayUtil.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ArrayUtil.java deleted file mode 100644 index e913db7c0..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ArrayUtil.java +++ /dev/null @@ -1,392 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -/** - * ArrayUtil - Array utilities holder. - * - * @author Vlad Mihalcea - */ -public class ArrayUtil { - - /** - * Clone an array. - * - * @param originalArray original array - * @param array element type - * @return cloned array - */ - public static T deepCopy(Object originalArray) { - Class arrayClass = originalArray.getClass(); - - if (boolean[].class.equals(arrayClass)) { - boolean[] array = (boolean[]) originalArray; - return (T) Arrays.copyOf(array, array.length); - } else if (byte[].class.equals(arrayClass)) { - byte[] array = (byte[]) originalArray; - return (T) Arrays.copyOf(array, array.length); - } else if (short[].class.equals(arrayClass)) { - short[] array = (short[]) originalArray; - return (T) Arrays.copyOf(array, array.length); - } else if (int[].class.equals(arrayClass)) { - int[] array = (int[]) originalArray; - return (T) Arrays.copyOf(array, array.length); - } else if (long[].class.equals(arrayClass)) { - long[] array = (long[]) originalArray; - return (T) Arrays.copyOf(array, array.length); - } else if (float[].class.equals(arrayClass)) { - float[] array = (float[]) originalArray; - return (T) Arrays.copyOf(array, array.length); - } else if (double[].class.equals(arrayClass)) { - double[] array = (double[]) originalArray; - return (T) Arrays.copyOf(array, array.length); - } else if (char[].class.equals(arrayClass)) { - char[] array = (char[]) originalArray; - return (T) Arrays.copyOf(array, array.length); - } else { - Object[] array = (Object[]) originalArray; - return (T) Arrays.copyOf(array, array.length); - } - } - - /** - * Wrap a given array so that primitives become wrapper objects. - * - * @param originalArray original array - * @return wrapped array - */ - public static Object[] wrapArray(Object originalArray) { - Class arrayClass = originalArray.getClass(); - - if (boolean[].class.equals(arrayClass)) { - boolean[] fromArray = (boolean[]) originalArray; - Boolean[] array = new Boolean[fromArray.length]; - for (int i = 0; i < fromArray.length; i++) { - array[i] = fromArray[i]; - } - return array; - } else if (byte[].class.equals(arrayClass)) { - byte[] fromArray = (byte[]) originalArray; - Byte[] array = new Byte[fromArray.length]; - for (int i = 0; i < fromArray.length; i++) { - array[i] = fromArray[i]; - } - return array; - } else if (short[].class.equals(arrayClass)) { - short[] fromArray = (short[]) originalArray; - Short[] array = new Short[fromArray.length]; - for (int i = 0; i < fromArray.length; i++) { - array[i] = fromArray[i]; - } - return array; - } else if (int[].class.equals(arrayClass)) { - int[] fromArray = (int[]) originalArray; - Integer[] array = new Integer[fromArray.length]; - for (int i = 0; i < fromArray.length; i++) { - array[i] = fromArray[i]; - } - return array; - } else if (long[].class.equals(arrayClass)) { - long[] fromArray = (long[]) originalArray; - Long[] array = new Long[fromArray.length]; - for (int i = 0; i < fromArray.length; i++) { - array[i] = fromArray[i]; - } - return array; - } else if (float[].class.equals(arrayClass)) { - float[] fromArray = (float[]) originalArray; - Float[] array = new Float[fromArray.length]; - for (int i = 0; i < fromArray.length; i++) { - array[i] = fromArray[i]; - } - return array; - } else if (double[].class.equals(arrayClass)) { - double[] fromArray = (double[]) originalArray; - Double[] array = new Double[fromArray.length]; - for (int i = 0; i < fromArray.length; i++) { - array[i] = fromArray[i]; - } - return array; - } else if (char[].class.equals(arrayClass)) { - char[] fromArray = (char[]) originalArray; - Character[] array = new Character[fromArray.length]; - for (int i = 0; i < fromArray.length; i++) { - array[i] = fromArray[i]; - } - return array; - } else if (originalArray instanceof Collection) { - return ((Collection) originalArray).toArray(); - } else { - return (Object[]) originalArray; - } - } - - /** - * Unwrap {@link Object[]} array to an array of the provided type - * - * @param originalArray original array - * @param arrayClass array class - * @param array element type - * @return unwrapped array - */ - public static T unwrapArray(Object[] originalArray, Class arrayClass) { - - if (boolean[].class.equals(arrayClass)) { - boolean[] array = new boolean[originalArray.length]; - for (int i = 0; i < originalArray.length; i++) { - array[i] = originalArray[i] != null ? (Boolean) originalArray[i] : Boolean.FALSE; - } - return (T) array; - } else if (byte[].class.equals(arrayClass)) { - byte[] array = new byte[originalArray.length]; - for (int i = 0; i < originalArray.length; i++) { - array[i] = originalArray[i] != null ? (Byte) originalArray[i] : 0; - } - return (T) array; - } else if (short[].class.equals(arrayClass)) { - short[] array = new short[originalArray.length]; - for (int i = 0; i < originalArray.length; i++) { - array[i] = originalArray[i] != null ? (Short) originalArray[i] : 0; - } - return (T) array; - } else if (int[].class.equals(arrayClass)) { - int[] array = new int[originalArray.length]; - for (int i = 0; i < originalArray.length; i++) { - array[i] = originalArray[i] != null ? (Integer) originalArray[i] : 0; - } - return (T) array; - } else if (long[].class.equals(arrayClass)) { - long[] array = new long[originalArray.length]; - for (int i = 0; i < originalArray.length; i++) { - array[i] = originalArray[i] != null ? (Long) originalArray[i] : 0L; - } - return (T) array; - } else if (float[].class.equals(arrayClass)) { - float[] array = new float[originalArray.length]; - for (int i = 0; i < originalArray.length; i++) { - array[i] = originalArray[i] != null ? ((Number) originalArray[i]).floatValue() : 0f; - } - return (T) array; - } else if (double[].class.equals(arrayClass)) { - double[] array = new double[originalArray.length]; - for (int i = 0; i < originalArray.length; i++) { - array[i] = originalArray[i] != null ? (Double) originalArray[i] : 0d; - } - return (T) array; - } else if (char[].class.equals(arrayClass)) { - char[] array = new char[originalArray.length]; - for (int i = 0; i < originalArray.length; i++) { - array[i] = originalArray[i] != null ? (Character) originalArray[i] : 0; - } - return (T) array; - } else if (Enum[].class.isAssignableFrom(arrayClass)) { - T array = arrayClass.cast(Array.newInstance(arrayClass.getComponentType(), originalArray.length)); - for (int i = 0; i < originalArray.length; i++) { - Object objectValue = originalArray[i]; - if (objectValue != null) { - String stringValue = (objectValue instanceof String) ? (String) objectValue : String.valueOf(objectValue); - objectValue = Enum.valueOf((Class) arrayClass.getComponentType(), stringValue); - } - Array.set(array, i, objectValue); - } - return array; - } else if (java.time.LocalDate[].class.equals(arrayClass) && java.sql.Date[].class.equals(originalArray.getClass())) { - // special case because conversion is neither with ctor nor valueOf - Object[] array = (Object[]) Array.newInstance(java.time.LocalDate.class, originalArray.length); - for (int i = 0; i < array.length; ++i) { - array[i] = originalArray[i] != null ? ((java.sql.Date) originalArray[i]).toLocalDate() : null; - } - return (T) array; - } else if (java.time.LocalDateTime[].class.equals(arrayClass) && java.sql.Timestamp[].class.equals(originalArray.getClass())) { - // special case because conversion is neither with ctor nor valueOf - Object[] array = (Object[]) Array.newInstance(java.time.LocalDateTime.class, originalArray.length); - for (int i = 0; i < array.length; ++i) { - array[i] = originalArray[i] != null ? ((java.sql.Timestamp) originalArray[i]).toLocalDateTime() : null; - } - return (T) array; - } else if(arrayClass.getComponentType() != null && arrayClass.getComponentType().isArray()) { - int arrayLength = originalArray.length; - Object[] array = (Object[]) Array.newInstance(arrayClass.getComponentType(), arrayLength); - if (arrayLength > 0) { - for (int i = 0; i < originalArray.length; i++) { - array[i] = unwrapArray((Object[]) originalArray[i], arrayClass.getComponentType()); - } - } - return (T) array; - } else { - if(arrayClass.isInstance(originalArray)) { - return (T) originalArray; - } else { - return (T) Arrays.copyOf(originalArray, originalArray.length, (Class) arrayClass); - } - } - } - - /** - * Create array from its {@link String} representation. - * - * @param string string representation - * @param arrayClass array class - * @param array element type - * @return array - */ - public static T fromString(String string, Class arrayClass) { - String stringArray = string.replaceAll("[\\[\\]]", ""); - String[] tokens = stringArray.split(","); - - int length = tokens.length; - - if (boolean[].class.equals(arrayClass)) { - boolean[] array = new boolean[length]; - for (int i = 0; i < tokens.length; i++) { - array[i] = Boolean.valueOf(tokens[i]); - } - return (T) array; - } else if (byte[].class.equals(arrayClass)) { - byte[] array = new byte[length]; - for (int i = 0; i < tokens.length; i++) { - array[i] = Byte.valueOf(tokens[i]); - } - return (T) array; - } else if (short[].class.equals(arrayClass)) { - short[] array = new short[length]; - for (int i = 0; i < tokens.length; i++) { - array[i] = Short.valueOf(tokens[i]); - } - return (T) array; - } else if (int[].class.equals(arrayClass)) { - int[] array = new int[length]; - for (int i = 0; i < tokens.length; i++) { - array[i] = Integer.valueOf(tokens[i]); - } - return (T) array; - } else if (long[].class.equals(arrayClass)) { - long[] array = new long[length]; - for (int i = 0; i < tokens.length; i++) { - array[i] = Long.valueOf(tokens[i]); - } - return (T) array; - } else if (float[].class.equals(arrayClass)) { - float[] array = new float[length]; - for (int i = 0; i < tokens.length; i++) { - array[i] = Float.valueOf(tokens[i]); - } - return (T) array; - } else if (double[].class.equals(arrayClass)) { - double[] array = new double[length]; - for (int i = 0; i < tokens.length; i++) { - array[i] = Double.valueOf(tokens[i]); - } - return (T) array; - } else if (char[].class.equals(arrayClass)) { - char[] array = new char[length]; - for (int i = 0; i < tokens.length; i++) { - array[i] = tokens[i].length() > 0 ? tokens[i].charAt(0) : Character.MIN_VALUE; - } - return (T) array; - } else { - return (T) tokens; - } - } - - /** - * Check if two arrays are equal. - * - * @param firstArray first array - * @param secondArray second array - * @return arrays are equal - */ - public static boolean isEquals(Object firstArray, Object secondArray) { - if (firstArray.getClass() != secondArray.getClass()) { - return false; - } - Class arrayClass = firstArray.getClass(); - - if (boolean[].class.equals(arrayClass)) { - return Arrays.equals((boolean[]) firstArray, (boolean[]) secondArray); - } else if (byte[].class.equals(arrayClass)) { - return Arrays.equals((byte[]) firstArray, (byte[]) secondArray); - } else if (short[].class.equals(arrayClass)) { - return Arrays.equals((short[]) firstArray, (short[]) secondArray); - } else if (int[].class.equals(arrayClass)) { - return Arrays.equals((int[]) firstArray, (int[]) secondArray); - } else if (long[].class.equals(arrayClass)) { - return Arrays.equals((long[]) firstArray, (long[]) secondArray); - } else if (float[].class.equals(arrayClass)) { - return Arrays.equals((float[]) firstArray, (float[]) secondArray); - } else if (double[].class.equals(arrayClass)) { - return Arrays.equals((double[]) firstArray, (double[]) secondArray); - } else if (char[].class.equals(arrayClass)) { - return Arrays.equals((char[]) firstArray, (char[]) secondArray); - } else { - return Arrays.equals((Object[]) firstArray, (Object[]) secondArray); - } - } - - /** - * Get the array class for the provided array element class. - * - * @param arrayElementClass array element class - * @param array element type - * @return array class - */ - public static Class toArrayClass(Class arrayElementClass) { - - if (boolean.class.equals(arrayElementClass)) { - return (Class) boolean[].class; - } else if (byte.class.equals(arrayElementClass)) { - return (Class) byte[].class; - } else if (short.class.equals(arrayElementClass)) { - return (Class) short[].class; - } else if (int.class.equals(arrayElementClass)) { - return (Class) int[].class; - } else if (long.class.equals(arrayElementClass)) { - return (Class) long[].class; - } else if (float.class.equals(arrayElementClass)) { - return (Class) float[].class; - } else if (double[].class.equals(arrayElementClass)) { - return (Class) double[].class; - } else if (char[].class.equals(arrayElementClass)) { - return (Class) char[].class; - } else { - Object array = Array.newInstance(arrayElementClass, 0); - return (Class) array.getClass(); - } - } - - /** - * Transforms an array to a {@link List}. The reason why {@link Arrays#asList(Object[])} - * is not used is because on Java 6 it wraps the {@link List} so we end up - * with two nested {@link List} objects. - * - * @param array array to transform - * @param array element type - * @return the {@link List} representation of the array - */ - public static List asList(T[] array) { - List list = new ArrayList(array.length); - for (int i = 0; i < array.length; i++) { - list.add(i, array[i]); - } - return list; - } - - /** - * @param array array to transform - * @param array element type - * @return the {@link Set} representation of the array - */ - public static Set asSet(T[] array) { - Set set = new LinkedHashSet(array.length); - for (int i = 0; i < array.length; i++) { - set.add(array[i]); - } - return set; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/BooleanArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/BooleanArrayTypeDescriptor.java deleted file mode 100644 index 418c438bf..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/BooleanArrayTypeDescriptor.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -/** - * @author jeet.choudhary7@gmail.com - * @version 2.9.13 - */ -public class BooleanArrayTypeDescriptor extends AbstractArrayTypeDescriptor { - - public BooleanArrayTypeDescriptor() { - super(boolean[].class); - } - - @Override - protected String getSqlArrayType() { - String sqlArrayType = super.getSqlArrayType(); - return sqlArrayType != null ? sqlArrayType : "boolean"; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DateArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DateArrayTypeDescriptor.java deleted file mode 100644 index 20c2ab04b..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DateArrayTypeDescriptor.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -import java.util.Date; - -/** - * @author Guillaume Briand - */ -public class DateArrayTypeDescriptor extends AbstractArrayTypeDescriptor { - - public DateArrayTypeDescriptor() { - super(Date[].class); - } - - @Override - protected String getSqlArrayType() { - return "date"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DecimalArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DecimalArrayTypeDescriptor.java deleted file mode 100644 index a56696d2e..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DecimalArrayTypeDescriptor.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -import java.math.BigDecimal; - -/** - * @author Moritz Kobel - */ -public class DecimalArrayTypeDescriptor extends AbstractArrayTypeDescriptor { - - public DecimalArrayTypeDescriptor() { - super(BigDecimal[].class); - } - - @Override - protected String getSqlArrayType() { - return "decimal"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DoubleArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DoubleArrayTypeDescriptor.java deleted file mode 100644 index d832bb125..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/DoubleArrayTypeDescriptor.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -/** - * @author Vlad Mihalcea - */ -public class DoubleArrayTypeDescriptor - extends AbstractArrayTypeDescriptor { - - public DoubleArrayTypeDescriptor() { - super(double[].class); - } - - @Override - protected String getSqlArrayType() { - String sqlArrayType = super.getSqlArrayType(); - return sqlArrayType != null ? sqlArrayType : "float8"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/EnumArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/EnumArrayTypeDescriptor.java deleted file mode 100644 index da3a4a199..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/EnumArrayTypeDescriptor.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -import java.util.Properties; - -/** - * @author Nazir El-Kayssi - * @author Vlad Mihalcea - */ -public class EnumArrayTypeDescriptor - extends AbstractArrayTypeDescriptor { - - private String sqlArrayType; - - public EnumArrayTypeDescriptor() { - super(Enum[].class); - } - - @Override - protected String getSqlArrayType() { - return sqlArrayType; - } - - @Override - public void setParameterValues(Properties parameters) { - sqlArrayType = parameters.getProperty(AbstractArrayType.SQL_ARRAY_TYPE); - super.setParameterValues(parameters); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/FloatArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/FloatArrayTypeDescriptor.java deleted file mode 100644 index cb9ca95f6..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/FloatArrayTypeDescriptor.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -/** - * @author Vlad Mihalcea - * @author Andreas Eberle - */ -public class FloatArrayTypeDescriptor - extends AbstractArrayTypeDescriptor { - - public FloatArrayTypeDescriptor() { - super(float[].class); - } - - @Override - protected String getSqlArrayType() { - String sqlArrayType = super.getSqlArrayType(); - return sqlArrayType != null ? sqlArrayType : "float4"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/IntArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/IntArrayTypeDescriptor.java deleted file mode 100644 index 386d6b126..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/IntArrayTypeDescriptor.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -/** - * @author Vlad Mihalcea - */ -public class IntArrayTypeDescriptor - extends AbstractArrayTypeDescriptor { - - public IntArrayTypeDescriptor() { - super(int[].class); - } - - @Override - protected String getSqlArrayType() { - return "integer"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ListArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ListArrayTypeDescriptor.java deleted file mode 100644 index 7ccdf64a7..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/ListArrayTypeDescriptor.java +++ /dev/null @@ -1,164 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.MutableMutabilityPlan; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.io.Serializable; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.WildcardType; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.*; - -/** - * @author Vlad Mihalcea - */ -public class ListArrayTypeDescriptor extends AbstractArrayTypeDescriptor { - - private String sqlArrayType; - - private Class entityClass; - - private String propertyName; - - private Class propertyClass; - - public ListArrayTypeDescriptor() { - super(Object.class, new MutableMutabilityPlan() { - @Override - protected Object deepCopyNotNull(Object value) { - if (value instanceof Set) { - Object[] array = ((Set) value).toArray(); - return ArrayUtil.asSet(ArrayUtil.deepCopy(array)); - } else if (value instanceof Collection) { - Object[] array = ((Collection) value).toArray(); - return ArrayUtil.asList(ArrayUtil.deepCopy(array)); - } else if (value.getClass().isArray()) { - Object[] array = (Object[]) value; - return ArrayUtil.deepCopy(array); - } else { - throw new UnsupportedOperationException("The provided " + value + " is not a List!"); - } - } - - @Override - public Object assemble(Serializable cached) { - if (cached != null && cached.getClass().isArray()) { - Object[] array = (Object[]) cached; - return Arrays.asList(array); - } - return super.assemble(cached); - } - }); - } - - @Override - protected String getSqlArrayType() { - return sqlArrayType; - } - - @Override - public Object unwrap(Object value, Class type, WrapperOptions options) { - if (value instanceof Object[]) { - return value; - } else if (value instanceof Collection) { - return super.unwrap(((Collection) value).toArray(), type, options); - } else { - throw new UnsupportedOperationException("The provided " + value + " is not a Object[] or List!"); - } - } - - @Override - public Object wrap(Object value, WrapperOptions options) { - Object wrappedObject = super.wrap(value, options); - Collection list = null; - if (wrappedObject != null) { - list = newPropertyCollectionInstance(); - if (wrappedObject instanceof Object[]) { - Object[] wrappedArray = (Object[]) wrappedObject; - Collections.addAll(list, wrappedArray); - } else { - throw new UnsupportedOperationException("The wrapped object " + value + " is not an Object[]!"); - } - } - return list; - } - - @Override - public boolean areEqual(Object one, Object another) { - if (one == another) { - return true; - } - if (one == null || another == null) { - return false; - } - if (one instanceof Collection && another instanceof Collection) { - return ArrayUtil.isEquals(((Collection) one).toArray(), ((Collection) another).toArray()); - } - if (one instanceof Object[] && another instanceof Object[]) { - return ArrayUtil.isEquals(one, another); - } else { - throw new UnsupportedOperationException("The provided " + one + " and " + another + " are not Object[] or List!"); - } - } - - @Override - public void setParameterValues(Properties parameters) { - this.entityClass = ReflectionUtils.getClass(parameters.getProperty(DynamicParameterizedType.ENTITY)); - this.propertyName = parameters.getProperty(DynamicParameterizedType.PROPERTY); - this.propertyClass = ReflectionUtils.getClass(parameters.getProperty(DynamicParameterizedType.RETURNED_CLASS)); - Type memberGenericType = ReflectionUtils.getMemberGenericTypeOrNull(entityClass, propertyName); - if (memberGenericType instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) memberGenericType; - Type genericType = parameterizedType.getActualTypeArguments()[0]; - if (genericType instanceof WildcardType) { - genericType = ((WildcardType) genericType).getUpperBounds()[0]; - } - Class arrayElementClass = ReflectionUtils.getClass(genericType.getTypeName()); - setArrayObjectClass( - arrayElementClass.isArray() ? - arrayElementClass : - ArrayUtil.toArrayClass(arrayElementClass) - ); - sqlArrayType = parameters.getProperty(AbstractArrayType.SQL_ARRAY_TYPE); - if (sqlArrayType == null) { - if (Integer.class.isAssignableFrom(arrayElementClass)) { - sqlArrayType = "integer"; - } else if (Long.class.isAssignableFrom(arrayElementClass)) { - sqlArrayType = "bigint"; - } else if (Double.class.isAssignableFrom(arrayElementClass)) { - sqlArrayType = "float8"; - } else if (String.class.isAssignableFrom(arrayElementClass)) { - sqlArrayType = "text"; - } else if (UUID.class.isAssignableFrom(arrayElementClass)) { - sqlArrayType = "uuid"; - } else if (Date.class.isAssignableFrom(arrayElementClass) || LocalDateTime.class.isAssignableFrom(arrayElementClass)) { - sqlArrayType = "timestamp"; - } else if (Boolean.class.isAssignableFrom(arrayElementClass)) { - sqlArrayType = "boolean"; - } else if (BigDecimal.class.isAssignableFrom(arrayElementClass)) { - sqlArrayType = "decimal"; - } else if (LocalDate.class.isAssignableFrom(arrayElementClass)) { - sqlArrayType = "date"; - } else { - throw new UnsupportedOperationException("The " + arrayElementClass + " is not supported yet!"); - } - } - } else { - throw new UnsupportedOperationException("The property " + propertyName + " in the " + entityClass + " entity is not parameterized!"); - } - } - - private Collection newPropertyCollectionInstance() { - if (propertyClass == null || List.class.isAssignableFrom(propertyClass)) { - return new ArrayList(); - } else if(Set.class.isAssignableFrom(propertyClass)) { - return new LinkedHashSet(); - } - throw new UnsupportedOperationException("The property " + propertyName + " in the " + entityClass + " entity is not supported by the ListArrayType!"); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LocalDateArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LocalDateArrayTypeDescriptor.java deleted file mode 100644 index 1a4beff53..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LocalDateArrayTypeDescriptor.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -/** - * @author Vlad Mihalcea - */ -public class LocalDateArrayTypeDescriptor - extends AbstractArrayTypeDescriptor { - - public LocalDateArrayTypeDescriptor() { - super(java.time.LocalDate[].class); - } - - @Override - protected String getSqlArrayType() { - return "date"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LocalDateTimeArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LocalDateTimeArrayTypeDescriptor.java deleted file mode 100644 index 7d298ce76..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LocalDateTimeArrayTypeDescriptor.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -/** - * @author Vlad Mihalcea - */ -public class LocalDateTimeArrayTypeDescriptor - extends AbstractArrayTypeDescriptor { - - public LocalDateTimeArrayTypeDescriptor() { - super(java.time.LocalDateTime[].class); - } - - @Override - protected String getSqlArrayType() { - return "timestamp"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LongArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LongArrayTypeDescriptor.java deleted file mode 100644 index f3bc5856f..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/LongArrayTypeDescriptor.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -/** - * @author Vlad Mihalcea - */ -public class LongArrayTypeDescriptor - extends AbstractArrayTypeDescriptor { - - public LongArrayTypeDescriptor() { - super(long[].class); - } - - @Override - protected String getSqlArrayType() { - return "bigint"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/StringArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/StringArrayTypeDescriptor.java deleted file mode 100644 index b4838bca1..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/StringArrayTypeDescriptor.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -/** - * @author Vlad Mihalcea - */ -public class StringArrayTypeDescriptor - extends AbstractArrayTypeDescriptor { - - public StringArrayTypeDescriptor() { - super(String[].class); - } - - @Override - protected String getSqlArrayType() { - String sqlArrayType = super.getSqlArrayType(); - return sqlArrayType != null ? sqlArrayType : "text"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/TimestampArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/TimestampArrayTypeDescriptor.java deleted file mode 100644 index 7e7b64b21..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/TimestampArrayTypeDescriptor.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -import java.util.Date; - -/** - * @author Vlad Mihalcea - */ -public class TimestampArrayTypeDescriptor extends AbstractArrayTypeDescriptor { - - public TimestampArrayTypeDescriptor() { - super(Date[].class); - } - - @Override - protected String getSqlArrayType() { - return "timestamp"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/UUIDArrayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/UUIDArrayTypeDescriptor.java deleted file mode 100644 index 60fe0ea23..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/array/internal/UUIDArrayTypeDescriptor.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array.internal; - -import java.util.UUID; - -/** - * @author Rafael Acevedo - */ -public class UUIDArrayTypeDescriptor - extends AbstractArrayTypeDescriptor { - - public UUIDArrayTypeDescriptor() { - super(UUID[].class); - } - - @Override - protected String getSqlArrayType() { - return "uuid"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/Inet.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/Inet.java deleted file mode 100644 index 29cb33cfe..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/Inet.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import org.hibernate.HibernateException; - -import java.io.Serializable; -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Objects; - -/** - * The {@link Inet} object type is used to represent an IP address. - *

- * For more details about how to use it, - * check out this article - * on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class Inet implements Serializable { - - private final String address; - - public Inet(String address) { - this.address = address; - } - - public String getAddress() { - return address; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - return Objects.equals(address, Inet.class.cast(o).address); - } - - @Override - public int hashCode() { - return Objects.hash(address); - } - - /** - * Get the associated {@link InetAddress} for the current {@link #address}. - * - * @return the associated {@link InetAddress} - */ - public InetAddress toInetAddress() { - try { - String host = address.replaceAll("\\/.*$", ""); - return Inet4Address.getByName(host); - } catch (UnknownHostException e) { - throw new HibernateException( - new IllegalArgumentException(e) - ); - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/Iso8601MonthType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/Iso8601MonthType.java deleted file mode 100644 index 7c7602add..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/Iso8601MonthType.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.basic.internal.Iso8601MonthMonthTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.descriptor.sql.IntegerTypeDescriptor; - -import java.time.Month; - -/** - * Maps a {@link Month} object type to a {@code INT} column type - * which is saved as value from 1 (January) to 12 (December), - * according to the ISO 8601 standard. - * - * @author Martin Panzer - */ -public class Iso8601MonthType extends AbstractHibernateType { - - public static final Iso8601MonthType INSTANCE = new Iso8601MonthType(); - - public Iso8601MonthType() { - super( - IntegerTypeDescriptor.INSTANCE, - Iso8601MonthMonthTypeDescriptor.INSTANCE - ); - } - - public Iso8601MonthType(Configuration configuration) { - super( - IntegerTypeDescriptor.INSTANCE, - Iso8601MonthMonthTypeDescriptor.INSTANCE, - configuration - ); - } - - @Override - public String getName() { - return "month"; - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/MonthDayDateType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/MonthDayDateType.java deleted file mode 100644 index 2b7a04979..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/MonthDayDateType.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.basic.internal.MonthDayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.descriptor.sql.DateTypeDescriptor; - -import java.time.MonthDay; - -/** - * Maps a Java {@link java.time.MonthDay} object to a {@code DATE} column type. - * - * @author Mladen Savic (mladensavic94@gmail.com) - */ - -public class MonthDayDateType extends AbstractHibernateType { - - public static final MonthDayDateType INSTANCE = new MonthDayDateType(); - - - public MonthDayDateType() { - super(DateTypeDescriptor.INSTANCE, MonthDayTypeDescriptor.INSTANCE); - } - - public MonthDayDateType(Configuration configuration) { - super(DateTypeDescriptor.INSTANCE, MonthDayTypeDescriptor.INSTANCE, configuration); - } - - @Override - public String getName() { - return "monthday-date"; - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/MonthDayIntegerType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/MonthDayIntegerType.java deleted file mode 100644 index 71655e612..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/MonthDayIntegerType.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.basic.internal.MonthDayTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.descriptor.sql.IntegerTypeDescriptor; - -import java.time.MonthDay; - -/** - * Maps a Java {@link java.time.MonthDay} object to a {@code INT} column type. - * - * @author Mladen Savic (mladensavic94@gmail.com) - */ -public class MonthDayIntegerType extends AbstractHibernateType { - - public static final MonthDayIntegerType INSTANCE = new MonthDayIntegerType(); - - - public MonthDayIntegerType() { - super(IntegerTypeDescriptor.INSTANCE, MonthDayTypeDescriptor.INSTANCE); - } - - public MonthDayIntegerType(Configuration configuration) { - super(IntegerTypeDescriptor.INSTANCE, MonthDayTypeDescriptor.INSTANCE, configuration); - } - - @Override - public String getName() { - return "monthday-int"; - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/NullableCharacterType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/NullableCharacterType.java deleted file mode 100644 index eb4294114..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/NullableCharacterType.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.ImmutableType; -import org.hibernate.engine.spi.SharedSessionContractImplementor; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; - -/** - * Maps an {@link Character} to a nullable CHAR column type. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class NullableCharacterType extends ImmutableType { - - public static final NullableCharacterType INSTANCE = new NullableCharacterType(); - - public NullableCharacterType() { - super(Character.class); - } - - @Override - public int[] sqlTypes() { - return new int[]{Types.CHAR}; - } - - @Override - public Character get(ResultSet rs, String[] names, - SharedSessionContractImplementor session, Object owner) throws SQLException { - String value = rs.getString(names[0]); - return (value != null && value.length() > 0) ? value.charAt(0) : null; - } - - @Override - public void set(PreparedStatement st, Character value, int index, - SharedSessionContractImplementor session) throws SQLException { - if (value == null) { - st.setNull(index, Types.CHAR); - } else { - st.setString(index, String.valueOf(value)); - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLCITextType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLCITextType.java deleted file mode 100644 index 3695c890b..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLCITextType.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.ImmutableType; -import org.hibernate.engine.spi.SharedSessionContractImplementor; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; - -/** - * Maps a {@link String} object type to a PostgreSQL citext - * column type. - * - * @author Sergei Portnov - */ -public class PostgreSQLCITextType extends ImmutableType { - - public static final PostgreSQLCITextType INSTANCE = new PostgreSQLCITextType(); - - public PostgreSQLCITextType() { - super(String.class); - } - - @Override - public int[] sqlTypes() { - return new int[]{Types.OTHER}; - } - - @Override - protected String get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { - Object value = rs.getObject(names[0]); - return value == null ? null : value.toString(); - } - - @Override - protected void set(PreparedStatement st, String value, int index, SharedSessionContractImplementor session) throws SQLException { - st.setObject(index, value, Types.OTHER); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLEnumType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLEnumType.java deleted file mode 100644 index b38d38462..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLEnumType.java +++ /dev/null @@ -1,90 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.util.Configuration; -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import org.hibernate.HibernateException; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.type.descriptor.java.JavaTypeDescriptor; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Types; -import java.util.Properties; - -/** - * Maps an {@link Enum} to a PostgreSQL ENUM column type. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class PostgreSQLEnumType extends org.hibernate.type.EnumType { - - public static final PostgreSQLEnumType INSTANCE = new PostgreSQLEnumType(); - - private final Configuration configuration; - - /** - * Initialization constructor taking the default {@link Configuration} object. - */ - public PostgreSQLEnumType() { - this(Configuration.INSTANCE); - } - - /** - * Initialization constructor taking a custom {@link Configuration} object. - * - * @param configuration custom {@link Configuration} object. - */ - public PostgreSQLEnumType(Configuration configuration) { - this.configuration = configuration; - } - - /** - * Initialization constructor taking the {@link Class}. - * - * @param enumClass The enum type - */ - public PostgreSQLEnumType(Class enumClass) { - this(); - - Class typeConfigurationClass = ReflectionUtils.getClassOrNull("org.hibernate.type.spi.TypeConfiguration"); - - if(typeConfigurationClass != null) { - Object typeConfiguration = ReflectionUtils.newInstance(typeConfigurationClass); - - Class enumJavaTypeDescriptorClass = ReflectionUtils.getClassOrNull("org.hibernate.type.descriptor.java.EnumJavaTypeDescriptor"); - - Object enumJavaTypeDescriptor = ReflectionUtils.newInstance(enumJavaTypeDescriptorClass, new Object[] {enumClass}, new Class[]{enumClass.getClass()}); - - Object javaTypeDescriptorRegistry = ReflectionUtils.invokeGetter(typeConfiguration, "javaTypeDescriptorRegistry"); - - ReflectionUtils.invokeMethod( - javaTypeDescriptorRegistry, - ReflectionUtils.getMethod(javaTypeDescriptorRegistry, "addDescriptor", JavaTypeDescriptor.class), - enumJavaTypeDescriptor - ); - - ReflectionUtils.invokeSetter(this, "typeConfiguration", typeConfiguration); - } - - Properties properties = new Properties(); - properties.setProperty("enumClass", enumClass.getName()); - properties.setProperty("useNamed", Boolean.TRUE.toString()); - setParameterValues(properties); - } - - public void nullSafeSet( - PreparedStatement st, - Object value, - int index, - SharedSessionContractImplementor session) - throws HibernateException, SQLException { - st.setObject(index, value != null ? ((Enum) value).name() : null, Types.OTHER); - } - - @Override - public int[] sqlTypes() { - return new int[]{Types.VARCHAR}; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLHStoreType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLHStoreType.java deleted file mode 100644 index 36aa1ed94..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLHStoreType.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.ImmutableType; -import org.hibernate.engine.spi.SharedSessionContractImplementor; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.util.Map; - -/** - * Maps a {@link Map} object type to a PostgreSQL hstore - * column type. - *

- * For more details about how to use it, - * check out this article - * on vladmihalcea.com. - * - * @author Edgar Asatryan - * @author Vlad Mihalcea - */ -public class PostgreSQLHStoreType extends ImmutableType { - - public static final PostgreSQLHStoreType INSTANCE = new PostgreSQLHStoreType(); - - public PostgreSQLHStoreType() { - super(Map.class); - } - - @Override - public int[] sqlTypes() { - return new int[]{Types.OTHER}; - } - - @Override - protected Map get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { - return (Map) rs.getObject(names[0]); - } - - @Override - protected void set(PreparedStatement st, Map value, int index, SharedSessionContractImplementor session) throws SQLException { - st.setObject(index, value); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLInetType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLInetType.java deleted file mode 100644 index 9c59022d4..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLInetType.java +++ /dev/null @@ -1,51 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.ImmutableType; -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import org.hibernate.engine.spi.SharedSessionContractImplementor; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; - -/** - * Maps an {@link Inet} object type to a PostgreSQL INET column type. - *

- * For more details about how to use it, - * check out this article - * on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class PostgreSQLInetType extends ImmutableType { - - public static final PostgreSQLInetType INSTANCE = new PostgreSQLInetType(); - - public PostgreSQLInetType() { - super(Inet.class); - } - - @Override - public int[] sqlTypes() { - return new int[]{Types.OTHER}; - } - - @Override - public Inet get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { - String ip = rs.getString(names[0]); - return (ip != null) ? new Inet(ip) : null; - } - - @Override - public void set(PreparedStatement st, Inet value, int index, SharedSessionContractImplementor session) throws SQLException { - if (value == null) { - st.setNull(index, Types.OTHER); - } else { - Object holder = ReflectionUtils.newInstance("org.postgresql.util.PGobject"); - ReflectionUtils.invokeSetter(holder, "type", "inet"); - ReflectionUtils.invokeSetter(holder, "value", value.getAddress()); - st.setObject(index, holder); - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLLTreeType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLLTreeType.java deleted file mode 100644 index c9630fe75..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLLTreeType.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.ImmutableType; -import org.hibernate.engine.spi.SharedSessionContractImplementor; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; - -/** - * Maps a {@link String} object type to a PostgreSQL ltree - * column type. - * - * @author Joshua Richenhagen - * @author Vlad Mihalcea - */ -public class PostgreSQLLTreeType extends ImmutableType { - - public static final PostgreSQLLTreeType INSTANCE = new PostgreSQLLTreeType(); - - public PostgreSQLLTreeType() { - super(String.class); - } - - @Override - public int[] sqlTypes() { - return new int[]{Types.OTHER}; - } - - @Override - protected String get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { - Object value = rs.getObject(names[0]); - return value == null ? null : value.toString(); - } - - @Override - protected void set(PreparedStatement st, String value, int index, SharedSessionContractImplementor session) throws SQLException { - st.setObject(index, value, Types.OTHER); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthDateType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthDateType.java deleted file mode 100644 index 58962d09d..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthDateType.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.basic.internal.YearMonthTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.descriptor.sql.DateTypeDescriptor; - -import java.time.YearMonth; - -/** - * Maps a Java {@link java.time.YearMonth} object to a {@code DATE} column type. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class YearMonthDateType - extends AbstractHibernateType { - - public static final YearMonthDateType INSTANCE = new YearMonthDateType(); - - public YearMonthDateType() { - super( - DateTypeDescriptor.INSTANCE, - YearMonthTypeDescriptor.INSTANCE - ); - } - - public YearMonthDateType(Configuration configuration) { - super( - DateTypeDescriptor.INSTANCE, - YearMonthTypeDescriptor.INSTANCE, - configuration - ); - } - - public String getName() { - return "yearmonth-date"; - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthEpochType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthEpochType.java deleted file mode 100644 index 6b40993d3..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthEpochType.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.basic.internal.YearMonthEpochTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.descriptor.sql.SmallIntTypeDescriptor; - -import java.time.YearMonth; - -/** - * Maps a Java {@link YearMonth} object to an small and continuous {@code INT} column type - * which defines the months that passed since the Unix epoch. - * - * @author Vlad Mihalcea - */ -public class YearMonthEpochType - extends AbstractHibernateType { - - public static final YearMonthEpochType INSTANCE = new YearMonthEpochType(); - - public YearMonthEpochType() { - super( - SmallIntTypeDescriptor.INSTANCE, - YearMonthEpochTypeDescriptor.INSTANCE - ); - } - - public YearMonthEpochType(Configuration configuration) { - super( - SmallIntTypeDescriptor.INSTANCE, - YearMonthEpochTypeDescriptor.INSTANCE, - configuration - ); - } - - public String getName() { - return "yearmonth-epoch"; - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthIntegerType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthIntegerType.java deleted file mode 100644 index d16021534..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthIntegerType.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.basic.internal.YearMonthTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.descriptor.sql.IntegerTypeDescriptor; - -import java.time.YearMonth; - -/** - * Maps a Java {@link YearMonth} object to an {@code INT} column type. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class YearMonthIntegerType - extends AbstractHibernateType { - - public static final YearMonthIntegerType INSTANCE = new YearMonthIntegerType(); - - public YearMonthIntegerType() { - super( - IntegerTypeDescriptor.INSTANCE, - YearMonthTypeDescriptor.INSTANCE - ); - } - - public YearMonthIntegerType(Configuration configuration) { - super( - IntegerTypeDescriptor.INSTANCE, - YearMonthTypeDescriptor.INSTANCE, - configuration - ); - } - - public String getName() { - return "yearmonth-int"; - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthTimestampType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthTimestampType.java deleted file mode 100644 index 95aa542af..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearMonthTimestampType.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.basic.internal.YearMonthTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.descriptor.sql.TimestampTypeDescriptor; - -import java.time.YearMonth; - -/** - * Maps a Java {@link YearMonth} object to a {@code TIMESTAMP} column type. - *

- * - * @author Vlad Mihalcea - */ -public class YearMonthTimestampType - extends AbstractHibernateType { - - public static final YearMonthTimestampType INSTANCE = new YearMonthTimestampType(); - - public YearMonthTimestampType() { - super( - TimestampTypeDescriptor.INSTANCE, - YearMonthTypeDescriptor.INSTANCE - ); - } - - public YearMonthTimestampType(Configuration configuration) { - super( - TimestampTypeDescriptor.INSTANCE, - YearMonthTypeDescriptor.INSTANCE, - configuration - ); - } - - public String getName() { - return "yearmonth-timestamp"; - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearType.java deleted file mode 100644 index 81f6d5b02..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/YearType.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.basic.internal.YearTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.descriptor.sql.SmallIntTypeDescriptor; - -import java.time.Year; - -/** - * Maps a Java {@link Year} object to an {@code INT} column type. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class YearType - extends AbstractHibernateType { - - public static final YearType INSTANCE = new YearType(); - - public YearType() { - super( - SmallIntTypeDescriptor.INSTANCE, - YearTypeDescriptor.INSTANCE - ); - } - - public YearType(Configuration configuration) { - super( - SmallIntTypeDescriptor.INSTANCE, - YearTypeDescriptor.INSTANCE, - configuration - ); - } - - public String getName() { - return "year"; - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/ZoneIdType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/ZoneIdType.java deleted file mode 100644 index 21dd001b2..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/ZoneIdType.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.basic.internal.ZoneIdTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; - -import java.time.ZoneId; - -/** - * Maps a Java {@link ZoneId} object to an {@code VARCHAR} column type. - * - * @author stonio - */ -public class ZoneIdType extends AbstractHibernateType { - - public static final ZoneIdType INSTANCE = new ZoneIdType(); - - public ZoneIdType() { - super( - VarcharTypeDescriptor.INSTANCE, - ZoneIdTypeDescriptor.INSTANCE - ); - } - - public ZoneIdType(Configuration configuration) { - super( - VarcharTypeDescriptor.INSTANCE, - ZoneIdTypeDescriptor.INSTANCE, - configuration - ); - } - - @Override - public String getName() { - return "zone-id"; - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/Iso8601MonthMonthTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/Iso8601MonthMonthTypeDescriptor.java deleted file mode 100644 index 031ffbc2c..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/Iso8601MonthMonthTypeDescriptor.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic.internal; - -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; - -import java.time.Month; -import java.util.Objects; - -/** - * @author Martin Panzer - */ -public class Iso8601MonthMonthTypeDescriptor - extends AbstractTypeDescriptor { - - public static final Iso8601MonthMonthTypeDescriptor INSTANCE = new Iso8601MonthMonthTypeDescriptor(); - - public Iso8601MonthMonthTypeDescriptor() { - super(Month.class); - } - - @Override - public boolean areEqual(Month one, Month another) { - return Objects.equals(one, another); - } - - @Override - public String toString(Month value) { - return value.toString(); - } - - @Override - public Month fromString(String string) { - return Month.valueOf(string); - } - - @SuppressWarnings({"unchecked"}) - @Override - public X unwrap(Month value, Class type, WrapperOptions options) { - if (value == null) { - return null; - } - if (Number.class.isAssignableFrom(type)) { - return (X) (Number) value.getValue(); - } - throw unknownUnwrap(type); - } - - @Override - public Month wrap(X value, WrapperOptions options) { - if (value == null) { - return null; - } - if (value instanceof Number) { - int numericValue = ((Number) (value)).intValue(); - return Month.of(numericValue); - } - throw unknownWrap(value.getClass()); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/MonthDayTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/MonthDayTypeDescriptor.java deleted file mode 100644 index c96958142..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/MonthDayTypeDescriptor.java +++ /dev/null @@ -1,83 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic.internal; - -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; - -import java.time.Instant; -import java.time.LocalDate; -import java.time.MonthDay; -import java.time.ZoneId; -import java.util.Date; -import java.util.Objects; - -/** - * @author Mladen Savic (mladensavic94@gmail.com) - */ - -public class MonthDayTypeDescriptor extends AbstractTypeDescriptor { - - public static final MonthDayTypeDescriptor INSTANCE = new MonthDayTypeDescriptor(); - - protected MonthDayTypeDescriptor() { - super(MonthDay.class); - } - - @Override - public MonthDay fromString(String s) { - return MonthDay.parse(s); - } - - @SuppressWarnings({"unchecked"}) - @Override - public X unwrap(MonthDay monthDay, Class type, WrapperOptions wrapperOptions) { - if (monthDay == null) { - return null; - } - if (String.class.isAssignableFrom(type)) { - return (X) toString(monthDay); - } - if (Number.class.isAssignableFrom(type)) { - Integer numericValue = (monthDay.getMonthValue() * 100) + monthDay.getDayOfMonth(); - return (X) (numericValue); - } - if (Date.class.isAssignableFrom(type)) { - int currentYear = LocalDate.now().getYear(); - return (X) java.sql.Date.valueOf(monthDay.atYear(currentYear)); - } - - throw unknownUnwrap(type); - } - - @Override - public MonthDay wrap(X value, WrapperOptions wrapperOptions) { - if (value == null) { - return null; - } - if (value instanceof String) { - return fromString((String) value); - } - if (value instanceof Number) { - int numericValue = ((Number) (value)).intValue(); - int month = numericValue / 100; - int dayOfMonth = numericValue % 100; - return MonthDay.of(month, dayOfMonth); - } - if (value instanceof Date) { - Date date = (Date) value; - return MonthDay.from(Instant.ofEpochMilli(date.getTime()) - .atZone(ZoneId.systemDefault()) - .toLocalDate()); - } - throw unknownWrap(value.getClass()); - } - - @Override - public boolean areEqual(MonthDay one, MonthDay another) { - return Objects.equals(one, another); - } - - @Override - public String toString(MonthDay value) { - return value.toString(); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearMonthEpochTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearMonthEpochTypeDescriptor.java deleted file mode 100644 index 99f3fdf93..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearMonthEpochTypeDescriptor.java +++ /dev/null @@ -1,75 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic.internal; - -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; - -import java.math.BigInteger; -import java.time.LocalDate; -import java.time.Period; -import java.time.YearMonth; -import java.util.Objects; - -/** - * @author Vlad Mihalcea - */ -public class YearMonthEpochTypeDescriptor - extends AbstractTypeDescriptor { - - public static final YearMonth YEAR_MONTH_EPOCH = YearMonth.of(1970, 1); - - public static final LocalDate LOCAL_DATE_EPOCH = YEAR_MONTH_EPOCH.atDay(1); - - public static final YearMonthEpochTypeDescriptor INSTANCE = new YearMonthEpochTypeDescriptor(); - - public YearMonthEpochTypeDescriptor() { - super(YearMonth.class); - } - - @Override - public boolean areEqual(YearMonth one, YearMonth another) { - return Objects.equals(one, another); - } - - @Override - public String toString(YearMonth value) { - return value.toString(); - } - - @Override - public YearMonth fromString(String string) { - return YearMonth.parse(string); - } - - @SuppressWarnings({"unchecked"}) - @Override - public X unwrap(YearMonth value, Class type, WrapperOptions options) { - if (value == null) { - return null; - } - Number monthsSinceEpoch = Period.between(LOCAL_DATE_EPOCH, value.atDay(1)).toTotalMonths(); - if (Short.class.isAssignableFrom(type)) { - return (X) (Short) (monthsSinceEpoch.shortValue()); - } - if (Integer.class.isAssignableFrom(type)) { - return (X) (Integer) (monthsSinceEpoch.intValue()); - } - if (Long.class.isAssignableFrom(type)) { - return (X) (Long) (monthsSinceEpoch.longValue()); - } - if (BigInteger.class.isAssignableFrom(type)) { - return (X) (BigInteger.valueOf(monthsSinceEpoch.longValue())); - } - throw unknownUnwrap(type); - } - - @Override - public YearMonth wrap(X value, WrapperOptions options) { - if (value == null) { - return null; - } - if (value instanceof Number) { - return YEAR_MONTH_EPOCH.plusMonths(((Number) value).intValue()); - } - throw unknownWrap(value.getClass()); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearMonthTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearMonthTypeDescriptor.java deleted file mode 100644 index 915c44b83..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearMonthTypeDescriptor.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic.internal; - -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; - -import java.sql.Timestamp; -import java.time.Instant; -import java.time.YearMonth; -import java.time.ZoneId; -import java.util.Date; -import java.util.Objects; - -/** - * @author Vlad Mihalcea - */ -public class YearMonthTypeDescriptor - extends AbstractTypeDescriptor { - - public static final YearMonthTypeDescriptor INSTANCE = new YearMonthTypeDescriptor(); - - public YearMonthTypeDescriptor() { - super(YearMonth.class); - } - - @Override - public boolean areEqual(YearMonth one, YearMonth another) { - return Objects.equals(one, another); - } - - @Override - public String toString(YearMonth value) { - return value.toString(); - } - - @Override - public YearMonth fromString(String string) { - return YearMonth.parse(string); - } - - @SuppressWarnings({"unchecked"}) - @Override - public X unwrap(YearMonth value, Class type, WrapperOptions options) { - if (value == null) { - return null; - } - if (String.class.isAssignableFrom(type)) { - return (X) toString(value); - } - if (Number.class.isAssignableFrom(type)) { - Integer numericValue = (value.getYear() * 100) + value.getMonth().getValue(); - return (X) (numericValue); - } - if (Timestamp.class.isAssignableFrom(type)) { - return (X) java.sql.Timestamp.valueOf(value.atDay(1).atStartOfDay()); - } - if (Date.class.isAssignableFrom(type)) { - return (X) java.sql.Date.valueOf(value.atDay(1)); - } - throw unknownUnwrap(type); - } - - @Override - public YearMonth wrap(X value, WrapperOptions options) { - if (value == null) { - return null; - } - if (value instanceof String) { - return fromString((String) value); - } - if (value instanceof Number) { - int numericValue = ((Number) (value)).intValue(); - if(numericValue > 0) { - int year = numericValue / 100; - int month = numericValue % 100; - return YearMonth.of(year, month); - } else { - return null; - } - } - if (value instanceof Date) { - Date date = (Date) value; - return YearMonth.from(Instant.ofEpochMilli(date.getTime()) - .atZone(ZoneId.systemDefault()) - .toLocalDate()); - } - throw unknownWrap(value.getClass()); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearTypeDescriptor.java deleted file mode 100644 index 72c493ad2..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/YearTypeDescriptor.java +++ /dev/null @@ -1,66 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic.internal; - -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; - -import java.time.Year; -import java.util.Objects; - -/** - * @author Vlad Mihalcea - */ -public class YearTypeDescriptor - extends AbstractTypeDescriptor { - - public static final YearTypeDescriptor INSTANCE = new YearTypeDescriptor(); - - public YearTypeDescriptor() { - super(Year.class); - } - - @Override - public boolean areEqual(Year one, Year another) { - return Objects.equals(one, another); - } - - @Override - public String toString(Year value) { - return value.toString(); - } - - @Override - public Year fromString(String string) { - return Year.parse(string); - } - - @SuppressWarnings({"unchecked"}) - @Override - public X unwrap(Year value, Class type, WrapperOptions options) { - if (value == null) { - return null; - } - if (String.class.isAssignableFrom(type)) { - return (X) toString(value); - } - if (Number.class.isAssignableFrom(type)) { - Short numericValue = (short) value.getValue(); - return (X) (numericValue); - } - throw unknownUnwrap(type); - } - - @Override - public Year wrap(X value, WrapperOptions options) { - if (value == null) { - return null; - } - if (value instanceof String) { - return fromString((String) value); - } - if (value instanceof Number) { - short numericValue = ((Number) (value)).shortValue(); - return Year.of(numericValue); - } - throw unknownWrap(value.getClass()); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/ZoneIdTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/ZoneIdTypeDescriptor.java deleted file mode 100644 index 34fafe66e..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/basic/internal/ZoneIdTypeDescriptor.java +++ /dev/null @@ -1,64 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic.internal; - -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; - -import java.time.ZoneId; -import java.util.Comparator; - -/** - * Descriptor for {@link ZoneId} handling. - * - * @see org.hibernate.type.descriptor.java.TimeZoneTypeDescriptor - * @author stonio - */ -public class ZoneIdTypeDescriptor extends AbstractTypeDescriptor { - - public static final ZoneIdTypeDescriptor INSTANCE = new ZoneIdTypeDescriptor(); - - public static class ZoneIdComparator implements Comparator { - public static final ZoneIdComparator INSTANCE = new ZoneIdComparator(); - - public int compare(ZoneId o1, ZoneId o2) { - return o1.getId().compareTo(o2.getId()); - } - } - - public ZoneIdTypeDescriptor() { - super(ZoneId.class); - } - - public String toString(ZoneId value) { - return value.getId(); - } - - public ZoneId fromString(String string) { - return ZoneId.of(string); - } - - @Override - public Comparator getComparator() { - return ZoneIdComparator.INSTANCE; - } - - @SuppressWarnings({ "unchecked" }) - public X unwrap(ZoneId value, Class type, WrapperOptions options) { - if (value == null) { - return null; - } - if (String.class.isAssignableFrom(type)) { - return (X) toString(value); - } - throw unknownUnwrap(type); - } - - public ZoneId wrap(X value, WrapperOptions options) { - if (value == null) { - return null; - } - if (String.class.isInstance(value)) { - return fromString((String) value); - } - throw unknownWrap(value.getClass()); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/binary/MySQLBinaryType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/binary/MySQLBinaryType.java deleted file mode 100644 index 2a7579d1f..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/binary/MySQLBinaryType.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.hypersistence.utils.hibernate.type.binary; - -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.BinaryType; -import org.hibernate.type.descriptor.sql.BinaryTypeDescriptor; - -/** - * Maps a Java {@link byte[]} object to a BINARY MySQL column type. - * - * @author Vlad Mihalcea - * @since 2.10.1 - */ -public class MySQLBinaryType extends BinaryType { - - public static final MySQLBinaryType INSTANCE = new MySQLBinaryType(); - - private final Configuration configuration; - - /** - * Initialization constructor taking the default {@link Configuration} object. - */ - public MySQLBinaryType() { - this(Configuration.INSTANCE); - } - - /** - * Initialization constructor taking a custom {@link Configuration} object. - * - * @param configuration custom {@link Configuration} object. - */ - public MySQLBinaryType(Configuration configuration) { - this.configuration = configuration; - setSqlTypeDescriptor(BinaryTypeDescriptor.INSTANCE); - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/OracleIntervalDayToSecondType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/OracleIntervalDayToSecondType.java deleted file mode 100644 index 50affacd4..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/OracleIntervalDayToSecondType.java +++ /dev/null @@ -1,89 +0,0 @@ -package io.hypersistence.utils.hibernate.type.interval; - -import io.hypersistence.utils.hibernate.type.ImmutableType; -import org.hibernate.HibernateException; -import org.hibernate.engine.spi.SharedSessionContractImplementor; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Maps a Java {@link Duration} object to a Oracle IntervalDS column type. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - * @since 2.6.1 - */ -public class OracleIntervalDayToSecondType extends ImmutableType { - - public static final OracleIntervalDayToSecondType INSTANCE = new OracleIntervalDayToSecondType(); - - public OracleIntervalDayToSecondType() { - super(Duration.class); - } - - private static final int SQL_COLUMN_TYPE = -104; - private static final String INTERVAL_TOKENS = "%1$2d %2$2d:%3$2d:%4$2d.0"; - private static final Pattern INTERVAL_PATTERN = Pattern.compile("-?(\\d+)\\s(\\d+):(\\d+):(\\d+)\\.\\d+"); - - @Override - protected Duration get( - ResultSet rs, - String[] names, - SharedSessionContractImplementor session, - Object owner) throws SQLException { - final String intervalValue = rs.getString(names[0]); - - if (intervalValue == null) { - return null; - } - - Matcher matcher = INTERVAL_PATTERN.matcher(intervalValue); - - if (matcher.matches()) { - Integer days = Integer.parseInt(matcher.group(1)); - Integer hours = Integer.parseInt(matcher.group(2)); - Integer minutes = Integer.parseInt(matcher.group(3)); - Integer seconds = Integer.parseInt(matcher.group(4)); - - Duration duration = Duration.ofDays(days) - .plus(hours, ChronoUnit.HOURS) - .plus(minutes, ChronoUnit.MINUTES) - .plus((long) Math.floor(seconds), ChronoUnit.SECONDS); - - return intervalValue.startsWith("-") ? duration.negated() : duration; - } - - throw new HibernateException( - new IllegalArgumentException("The parsed interval " + intervalValue + " does not match the expected pattern: " + INTERVAL_PATTERN) - ); - } - - @Override - protected void set(PreparedStatement st, Duration value, int index, SharedSessionContractImplementor session) throws SQLException { - if (value == null) { - st.setNull(index, SQL_COLUMN_TYPE); - } else { - final int days = Math.abs((int) value.toDays()); - final int hours = Math.abs((int) (value.toHours() % 24)); - final int minutes = Math.abs((int) (value.toMinutes() % 60)); - final int seconds = Math.abs((int) (value.getSeconds() % 60)); - - st.setString(index, (value.isNegative() ? "-" : "") + String.format(INTERVAL_TOKENS, days, hours, minutes, seconds)); - } - } - - @Override - public int[] sqlTypes() { - return new int[]{ - SQL_COLUMN_TYPE - }; - } - -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLIntervalType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLIntervalType.java deleted file mode 100644 index 82fc5fe98..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLIntervalType.java +++ /dev/null @@ -1,74 +0,0 @@ -package io.hypersistence.utils.hibernate.type.interval; - -import io.hypersistence.utils.hibernate.type.ImmutableType; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.postgresql.util.PGInterval; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.time.Duration; -import java.time.temporal.ChronoUnit; - -/** - * Maps a Java {@link Duration} object to a PostgreSQL Interval column type. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Jan-Willem Gmelig Meyling - * @author Vlad Mihalcea - * @since 2.5.1 - */ -public class PostgreSQLIntervalType extends ImmutableType { - - private static final double MICROS_IN_SECOND = 1000000; - - public static final PostgreSQLIntervalType INSTANCE = new PostgreSQLIntervalType(); - - public PostgreSQLIntervalType() { - super(Duration.class); - } - - @Override - protected Duration get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { - final PGInterval interval = (PGInterval) rs.getObject(names[0]); - - if (interval == null) { - return null; - } - - final int days = interval.getDays(); - final int hours = interval.getHours(); - final int minutes = interval.getMinutes(); - final int seconds = (int) interval.getSeconds(); - final int micros = (int) Math.round((interval.getSeconds() - seconds) * MICROS_IN_SECOND); - - return Duration.ofDays(days) - .plus(hours, ChronoUnit.HOURS) - .plus(minutes, ChronoUnit.MINUTES) - .plus(seconds, ChronoUnit.SECONDS) - .plus(micros, ChronoUnit.MICROS); - } - - @Override - protected void set(PreparedStatement st, Duration value, int index, SharedSessionContractImplementor session) throws SQLException { - if (value == null) { - st.setNull(index, Types.OTHER); - } else { - final int days = (int) value.toDays(); - final int hours = (int) (value.toHours() % 24); - final int minutes = (int) (value.toMinutes() % 60); - final int seconds = (int) (value.getSeconds() % 60); - final int micros = value.getNano() / 1000; - final double secondsWithFraction = seconds + (micros / MICROS_IN_SECOND); - st.setObject(index, new PGInterval(0, 0, days, hours, minutes, secondsWithFraction)); - } - } - - @Override - public int[] sqlTypes() { - return new int[]{Types.OTHER}; - } - -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLPeriodType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLPeriodType.java deleted file mode 100644 index 2aa3b7bc9..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLPeriodType.java +++ /dev/null @@ -1,63 +0,0 @@ -package io.hypersistence.utils.hibernate.type.interval; - -import io.hypersistence.utils.hibernate.type.ImmutableType; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.postgresql.util.PGInterval; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.time.Duration; -import java.time.Period; - -/** - * Maps a Java {@link Period} object to a PostgreSQL Interval column type. - * - * @author Jan-Willem Gmelig Meyling - * @author Vlad Mihalcea - * @since 2.6.2 - */ -public class PostgreSQLPeriodType extends ImmutableType { - - public static final PostgreSQLPeriodType INSTANCE = new PostgreSQLPeriodType(); - - public PostgreSQLPeriodType() { - super(Period.class); - } - - @Override - protected Period get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { - final PGInterval interval = (PGInterval) rs.getObject(names[0]); - - if (interval == null) { - return null; - } - - final int years = interval.getYears(); - final int months = interval.getMonths(); - final int days = interval.getDays(); - - return Period.ofYears(years) - .plusMonths(months) - .plusDays(days); - } - - @Override - protected void set(PreparedStatement st, Period value, int index, SharedSessionContractImplementor session) throws SQLException { - if (value == null) { - st.setNull(index, Types.OTHER); - } else { - final int days = value.getDays(); - final int months = value.getMonths(); - final int years = value.getYears(); - st.setObject(index, new PGInterval(years, months, days, 0, 0, 0)); - } - } - - @Override - public int[] sqlTypes() { - return new int[]{Types.OTHER}; - } - -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonBinaryType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonBinaryType.java deleted file mode 100644 index c1c78b0be..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonBinaryType.java +++ /dev/null @@ -1,94 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.ObjectMapper; -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.json.internal.JsonBinarySqlTypeDescriptor; -import io.hypersistence.utils.hibernate.type.json.internal.JsonTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.JsonConfiguration; -import io.hypersistence.utils.hibernate.type.util.ObjectMapperWrapper; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.lang.reflect.Type; -import java.util.Properties; - -/** - *

- * Maps any given Java object on a JSON column type that is managed via {@link java.sql.PreparedStatement#setObject(int, Object)} at JDBC Driver level. - *

- *

- * If you are using PostgreSQL, you can use this {@link JsonBinaryType} to map both jsonb and json column types. - *

- *

- * For more details about how to use it, check out this article on vladmihalcea.com. - *

- *

- * If you want to use a more portable Hibernate Type that can work on Oracle, SQL Server, PostgreSQL, MySQL, or H2 without any configuration changes, then you should use the {@link JsonType} instead. - *

- * - * @author Vlad Mihalcea - */ -public class JsonBinaryType - extends AbstractHibernateType implements DynamicParameterizedType { - - public static final JsonBinaryType INSTANCE = new JsonBinaryType(); - - public JsonBinaryType() { - super( - JsonBinarySqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(JsonConfiguration.INSTANCE.getObjectMapperWrapper()) - ); - } - - public JsonBinaryType(Type javaType) { - super( - JsonBinarySqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(JsonConfiguration.INSTANCE.getObjectMapperWrapper(), javaType) - ); - } - - public JsonBinaryType(JsonConfiguration configuration) { - super( - JsonBinarySqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(configuration.getObjectMapperWrapper()), - configuration - ); - } - - public JsonBinaryType(ObjectMapper objectMapper) { - super( - JsonBinarySqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(new ObjectMapperWrapper(objectMapper)) - ); - } - - public JsonBinaryType(ObjectMapperWrapper objectMapperWrapper) { - super( - JsonBinarySqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(objectMapperWrapper) - ); - } - - public JsonBinaryType(ObjectMapper objectMapper, Type javaType) { - super( - JsonBinarySqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(new ObjectMapperWrapper(objectMapper), javaType) - ); - } - - public JsonBinaryType(ObjectMapperWrapper objectMapperWrapper, Type javaType) { - super( - JsonBinarySqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(objectMapperWrapper, javaType) - ); - } - - public String getName() { - return "jsonb"; - } - - @Override - public void setParameterValues(Properties parameters) { - ((JsonTypeDescriptor) getJavaTypeDescriptor()).setParameterValues(parameters); - } - -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonBlobType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonBlobType.java deleted file mode 100644 index 097bdcb27..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonBlobType.java +++ /dev/null @@ -1,94 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.ObjectMapper; -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.json.internal.JsonBlobSqlTypeDescriptor; -import io.hypersistence.utils.hibernate.type.json.internal.JsonTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.JsonConfiguration; -import io.hypersistence.utils.hibernate.type.util.ObjectMapperWrapper; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.lang.reflect.Type; -import java.sql.Blob; -import java.util.Properties; - -/** - *

- * Maps any given Java object on a JSON column type that is managed via {@link java.sql.PreparedStatement#setBlob(int, Blob)} at JDBC Driver level. - *

- *

- * If you are using Oracle, you can use this {@link JsonBlobType} to map a {@code BLOB} column type storing JSON. - *

- *

- * For more details about how to use it, check out this article on vladmihalcea.com. - *

- *

- * If you want to use a more portable Hibernate Type that can work on Oracle, SQL Server, PostgreSQL, MySQL, or H2 without any configuration changes, then you should use the {@link JsonType} instead. - *

- * - * @author Vlad Mihalcea - */ -public class JsonBlobType extends AbstractHibernateType implements DynamicParameterizedType { - - public static final JsonBlobType INSTANCE = new JsonBlobType(); - - public JsonBlobType() { - super( - JsonBlobSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(JsonConfiguration.INSTANCE.getObjectMapperWrapper()) - ); - } - - public JsonBlobType(Type javaType) { - super( - JsonBlobSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(JsonConfiguration.INSTANCE.getObjectMapperWrapper(), javaType) - ); - } - - public JsonBlobType(JsonConfiguration configuration) { - super( - JsonBlobSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(configuration.getObjectMapperWrapper()), - configuration - ); - } - - public JsonBlobType(ObjectMapper objectMapper) { - super( - JsonBlobSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(new ObjectMapperWrapper(objectMapper)) - ); - } - - public JsonBlobType(ObjectMapperWrapper objectMapperWrapper) { - super( - JsonBlobSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(objectMapperWrapper) - ); - } - - public JsonBlobType(ObjectMapper objectMapper, Type javaType) { - super( - JsonBlobSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(new ObjectMapperWrapper(objectMapper), javaType) - ); - } - - public JsonBlobType(ObjectMapperWrapper objectMapperWrapper, Type javaType) { - super( - JsonBlobSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(objectMapperWrapper, javaType) - ); - } - - public String getName() { - return "jsonb-lob"; - } - - @Override - public void setParameterValues(Properties parameters) { - ((JsonTypeDescriptor) getJavaTypeDescriptor()).setParameterValues(parameters); - } - -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonNodeBinaryType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonNodeBinaryType.java deleted file mode 100644 index a33484416..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonNodeBinaryType.java +++ /dev/null @@ -1,63 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.json.internal.JsonBinarySqlTypeDescriptor; -import io.hypersistence.utils.hibernate.type.json.internal.JsonNodeTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.JsonConfiguration; -import io.hypersistence.utils.hibernate.type.util.ObjectMapperWrapper; - -/** - *

- * Maps a Jackson {@link JsonNode} object on a JSON column type that is managed via {@link java.sql.PreparedStatement#setObject(int, Object)} at JDBC Driver level. - *

- *

- * For instance, if you are using PostgreSQL, you can use the {@link JsonNodeBinaryType} to map both {@code jsonb} and {@code json} column types to a Jackson {@link JsonNode} object. - *

- *

- * For more details about how to use it, check out this article on vladmihalcea.com. - *

- *

- * If you want to use a more portable Hibernate Type that can work on Oracle, SQL Server, PostgreSQL, MySQL, or H2 without any configuration changes, then you should use the {@link JsonType} instead. - *

- * - * @author Vlad Mihalcea - */ -public class JsonNodeBinaryType extends AbstractHibernateType { - - public static final JsonNodeBinaryType INSTANCE = new JsonNodeBinaryType(); - - public JsonNodeBinaryType() { - super( - JsonBinarySqlTypeDescriptor.INSTANCE, - new JsonNodeTypeDescriptor(JsonConfiguration.INSTANCE.getObjectMapperWrapper()) - ); - } - - public JsonNodeBinaryType(JsonConfiguration configuration) { - super( - JsonBinarySqlTypeDescriptor.INSTANCE, - new JsonNodeTypeDescriptor(configuration.getObjectMapperWrapper()), - configuration - ); - } - - public JsonNodeBinaryType(ObjectMapper objectMapper) { - super( - JsonBinarySqlTypeDescriptor.INSTANCE, - new JsonNodeTypeDescriptor(new ObjectMapperWrapper(objectMapper)) - ); - } - - public JsonNodeBinaryType(ObjectMapperWrapper objectMapperWrapper) { - super( - JsonBinarySqlTypeDescriptor.INSTANCE, - new JsonNodeTypeDescriptor(objectMapperWrapper) - ); - } - - public String getName() { - return "jsonb-node"; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonNodeStringType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonNodeStringType.java deleted file mode 100644 index 44bf2d85a..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonNodeStringType.java +++ /dev/null @@ -1,64 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.json.internal.JsonNodeTypeDescriptor; -import io.hypersistence.utils.hibernate.type.json.internal.JsonStringSqlTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.JsonConfiguration; -import io.hypersistence.utils.hibernate.type.util.ObjectMapperWrapper; - -/** - *

- * Maps a Jackson {@link JsonNode} object on a JSON column type that is managed via {@link java.sql.PreparedStatement#setString(int, String)} at JDBC Driver level. - *

- *

- * For instance, if you are using MySQL, you can use the {@link JsonNodeStringType} to map the {@code json} column type to a Jackson {@link JsonNode} object. - *

- *

- * For more details about how to use it, check out this article on vladmihalcea.com. - *

- *

- * If you want to use a more portable Hibernate Type that can work on Oracle, SQL Server, PostgreSQL, MySQL, or H2 without any configuration changes, then you should use the {@link JsonType} instead. - *

- * - * @author Vlad Mihalcea - */ -public class JsonNodeStringType extends AbstractHibernateType { - - public static final JsonNodeStringType INSTANCE = new JsonNodeStringType(); - - public JsonNodeStringType() { - super( - JsonStringSqlTypeDescriptor.INSTANCE, - new JsonNodeTypeDescriptor(JsonConfiguration.INSTANCE.getObjectMapperWrapper()) - ); - } - - public JsonNodeStringType(JsonConfiguration configuration) { - super( - JsonStringSqlTypeDescriptor.INSTANCE, - new JsonNodeTypeDescriptor(configuration.getObjectMapperWrapper()), - configuration - ); - } - - public JsonNodeStringType(ObjectMapper objectMapper) { - super( - JsonStringSqlTypeDescriptor.INSTANCE, - new JsonNodeTypeDescriptor(new ObjectMapperWrapper(objectMapper)) - ); - } - - public JsonNodeStringType(ObjectMapperWrapper objectMapperWrapper) { - super( - JsonStringSqlTypeDescriptor.INSTANCE, - new JsonNodeTypeDescriptor(objectMapperWrapper) - ); - } - - @Override - public String getName() { - return "jsonb-node"; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonStringType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonStringType.java deleted file mode 100644 index d123d11d9..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonStringType.java +++ /dev/null @@ -1,105 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.ObjectMapper; -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.json.internal.JsonStringSqlTypeDescriptor; -import io.hypersistence.utils.hibernate.type.json.internal.JsonTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.JsonConfiguration; -import io.hypersistence.utils.hibernate.type.util.ObjectMapperWrapper; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.lang.reflect.Type; -import java.util.Properties; - -/** - *

- * Maps any given Java object on a JSON column type that is managed via {@link java.sql.PreparedStatement#setString(int, String)} at JDBC Driver level. - *

- *
    - *
  • If you are using Oracle, you can use this {@link JsonStringType} to map a {@code VARCHAR2} column type storing JSON. For more details, check out this article on vladmihalcea.com. - *
  • - *
  • - * If you are using SQL Server, you can use this {@link JsonStringType} to map an {@code NVARCHAR} column type storing JSON. For more details, check out this article on vladmihalcea.com. - *
  • - *
  • - * If you are using MySQL, you can use this {@link JsonStringType} to map the {@code json} column type. For more details, check out this article on vladmihalcea.com. - *
  • - *
  • - * If you are using PostgreSQL, then you should NOT use this {@link JsonStringType}. You should use {@link JsonBinaryType} instead. For more details, check out this article on vladmihalcea.com. - *
  • - *
- *

- * If you want to use a more portable Hibernate Type that can work on Oracle, SQL Server, PostgreSQL, MySQL, or H2 without any configuration changes, then you should use the {@link JsonType} instead. - *

- * - * @author Vlad Mihalcea - */ -public class JsonStringType extends AbstractHibernateType implements DynamicParameterizedType { - - public static final JsonStringType INSTANCE = new JsonStringType(); - - public JsonStringType() { - super( - JsonStringSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(JsonConfiguration.INSTANCE.getObjectMapperWrapper()) - ); - } - - public JsonStringType(Type javaType) { - super( - JsonStringSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(JsonConfiguration.INSTANCE.getObjectMapperWrapper(), javaType) - ); - } - - public JsonStringType(JsonConfiguration configuration) { - super( - JsonStringSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(configuration.getObjectMapperWrapper()), - configuration - ); - } - - public JsonStringType(ObjectMapper objectMapper) { - super( - JsonStringSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(new ObjectMapperWrapper(objectMapper)) - ); - } - - public JsonStringType(ObjectMapperWrapper objectMapperWrapper) { - super( - JsonStringSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(objectMapperWrapper) - ); - } - - public JsonStringType(ObjectMapper objectMapper, Type javaType) { - super( - JsonStringSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(new ObjectMapperWrapper(objectMapper), javaType) - ); - } - - public JsonStringType(ObjectMapperWrapper objectMapperWrapper, Type javaType) { - super( - JsonStringSqlTypeDescriptor.INSTANCE, - new JsonTypeDescriptor(objectMapperWrapper, javaType) - ); - } - - @Override - public String getName() { - return "json"; - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } - - @Override - public void setParameterValues(Properties parameters) { - ((JsonTypeDescriptor) getJavaTypeDescriptor()).setParameterValues(parameters); - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonType.java deleted file mode 100644 index f04aeb902..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/JsonType.java +++ /dev/null @@ -1,125 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.ObjectMapper; -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.json.internal.JsonSqlTypeDescriptor; -import io.hypersistence.utils.hibernate.type.json.internal.JsonTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.JsonConfiguration; -import io.hypersistence.utils.hibernate.type.util.ObjectMapperWrapper; -import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; -import org.hibernate.usertype.DynamicParameterizedType; -import org.hibernate.usertype.ParameterizedType; - -import javax.persistence.Column; -import java.lang.reflect.Type; -import java.util.Properties; - -/** - *

- * {@link JsonType} allows you to map any given JSON object (e.g., POJO, Map<String, Object>, List<T>, JsonNode) on any of the following database systems: - *

- *
    - *
  • PostgreSQL - for both jsonb and json column types
  • - *
  • MySQL - for the json column type
  • - *
  • SQL Server - for the NVARCHAR column type storing JSON
  • - *
  • Oracle - for the JSON column type if you're using Oracle 21c or the VARCHAR column type storing JSON if you're using an older Oracle version
  • - *
  • H2 - for the json column type
  • - *
- *

- * If you switch to Oracle 21c from an older version, then you should also migrate your {@code JSON} columns to the native JSON type since this binary type performs better than - * {@code VARCHAR2} or {@code BLOB} column types. - *

- *

- * However, if you don't want to migrate to the new {@code JSON} data type, - * then you just have to provide the column type via the JPA {@link Column#columnDefinition()} attribute, - * like in the following example: - *

- *
- * {@code @Type(}type = "io.hypersistence.utils.hibernate.type.json.JsonType")
- * {@code @Column(}columnDefinition = "VARCHAR2")
- * 
- *

- * For more details about how to use the {@link JsonType}, check out this article on vladmihalcea.com. - *

- *

- * If you are using Oracle and want to store JSON objects in a BLOB column type, then you can use the {@link JsonBlobType} instead. For more details, check out this article on vladmihalcea.com. - *

- *

- * Or, you can use the {@link JsonType}, but you'll have to specify the underlying column type - * using the JPA {@link Column#columnDefinition()} attribute, like this: - *

- *
- * {@code @Type(}type = "io.hypersistence.utils.hibernate.type.json.JsonType")
- * {@code @Column(}columnDefinition = "BLOB")
- * 
- * @author Vlad Mihalcea - */ -public class JsonType - extends AbstractHibernateType implements DynamicParameterizedType { - - public static final JsonType INSTANCE = new JsonType(); - - public JsonType() { - super( - new JsonSqlTypeDescriptor(), - new JsonTypeDescriptor(JsonConfiguration.INSTANCE.getObjectMapperWrapper()) - ); - } - - public JsonType(Type javaType) { - super( - new JsonSqlTypeDescriptor(), - new JsonTypeDescriptor(JsonConfiguration.INSTANCE.getObjectMapperWrapper(), javaType) - ); - } - - public JsonType(JsonConfiguration configuration) { - super( - new JsonSqlTypeDescriptor(configuration.getProperties()), - new JsonTypeDescriptor(configuration.getObjectMapperWrapper()), - configuration - ); - } - - public JsonType(ObjectMapper objectMapper) { - super( - new JsonSqlTypeDescriptor(), - new JsonTypeDescriptor(new ObjectMapperWrapper(objectMapper)) - ); - } - - public JsonType(ObjectMapperWrapper objectMapperWrapper) { - super( - new JsonSqlTypeDescriptor(), - new JsonTypeDescriptor(objectMapperWrapper) - ); - } - - public JsonType(ObjectMapper objectMapper, Type javaType) { - super( - new JsonSqlTypeDescriptor(), - new JsonTypeDescriptor(new ObjectMapperWrapper(objectMapper), javaType) - ); - } - - public JsonType(ObjectMapperWrapper objectMapperWrapper, Type javaType) { - super( - new JsonSqlTypeDescriptor(), - new JsonTypeDescriptor(objectMapperWrapper, javaType) - ); - } - - public String getName() { - return "json"; - } - - @Override - public void setParameterValues(Properties parameters) { - ((JsonTypeDescriptor) getJavaTypeDescriptor()).setParameterValues(parameters); - SqlTypeDescriptor sqlTypeDescriptor = getSqlTypeDescriptor(); - if (sqlTypeDescriptor instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) sqlTypeDescriptor; - parameterizedType.setParameterValues(parameters); - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/AbstractJsonSqlTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/AbstractJsonSqlTypeDescriptor.java deleted file mode 100644 index 79d01d2fe..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/AbstractJsonSqlTypeDescriptor.java +++ /dev/null @@ -1,60 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.internal; - -import org.hibernate.type.descriptor.ValueExtractor; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.hibernate.type.descriptor.sql.BasicExtractor; -import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; - -import java.sql.CallableStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; - -/** - * @author Vlad Mihalcea - */ -public abstract class AbstractJsonSqlTypeDescriptor implements SqlTypeDescriptor { - - @Override - public int getSqlType() { - return Types.OTHER; - } - - @Override - public boolean canBeRemapped() { - return true; - } - - @Override - public ValueExtractor getExtractor(final JavaTypeDescriptor javaTypeDescriptor) { - return new BasicExtractor(javaTypeDescriptor, this) { - @Override - protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException { - return javaTypeDescriptor.wrap(extractJson(rs, name), options); - } - - @Override - protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException { - return javaTypeDescriptor.wrap(extractJson(statement, index), options); - } - - @Override - protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException { - return javaTypeDescriptor.wrap(extractJson(statement, name), options); - } - }; - } - - protected Object extractJson(ResultSet rs, String name) throws SQLException { - return rs.getObject(name); - } - - protected Object extractJson(CallableStatement statement, int index) throws SQLException { - return statement.getObject(index); - } - - protected Object extractJson(CallableStatement statement, String name) throws SQLException { - return statement.getObject(name); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JacksonUtil.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JacksonUtil.java deleted file mode 100644 index 1c20fa3fa..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JacksonUtil.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.internal; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.type.util.ObjectMapperWrapper; - -import java.lang.reflect.Type; - -/** - * @author Vlad Mihalcea - */ -public class JacksonUtil { - - public static T fromString(String string, Class clazz) { - return ObjectMapperWrapper.INSTANCE.fromString(string, clazz); - } - - public static T fromString(String string, Type type) { - return ObjectMapperWrapper.INSTANCE.fromString(string, type); - } - - public static String toString(Object value) { - return ObjectMapperWrapper.INSTANCE.toString(value); - } - - public static JsonNode toJsonNode(String value) { - return ObjectMapperWrapper.INSTANCE.toJsonNode(value); - } - - public static T clone(T value) { - return ObjectMapperWrapper.INSTANCE.clone(value); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBinarySqlTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBinarySqlTypeDescriptor.java deleted file mode 100644 index 7c9dcf9cf..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBinarySqlTypeDescriptor.java +++ /dev/null @@ -1,34 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.internal; - -import org.hibernate.type.descriptor.ValueBinder; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.hibernate.type.descriptor.sql.BasicBinder; - -import java.sql.CallableStatement; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -/** - * @author Vlad Mihalcea - */ -public class JsonBinarySqlTypeDescriptor extends AbstractJsonSqlTypeDescriptor { - - public static final JsonBinarySqlTypeDescriptor INSTANCE = new JsonBinarySqlTypeDescriptor(); - - @Override - public ValueBinder getBinder(final JavaTypeDescriptor javaTypeDescriptor) { - return new BasicBinder(javaTypeDescriptor, this) { - @Override - protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { - st.setObject(index, javaTypeDescriptor.unwrap(value, String.class, options), getSqlType()); - } - - @Override - protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) - throws SQLException { - st.setObject(name, javaTypeDescriptor.unwrap(value, String.class, options), getSqlType()); - } - }; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBlobSqlTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBlobSqlTypeDescriptor.java deleted file mode 100644 index 18acfe50c..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBlobSqlTypeDescriptor.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.internal; - -import org.hibernate.type.descriptor.ValueBinder; -import org.hibernate.type.descriptor.ValueExtractor; -import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.hibernate.type.descriptor.sql.BlobTypeDescriptor; - -/** - * @author Vlad Mihalcea - */ -public class JsonBlobSqlTypeDescriptor extends AbstractJsonSqlTypeDescriptor { - - public static final JsonBlobSqlTypeDescriptor INSTANCE = new JsonBlobSqlTypeDescriptor(); - - private BlobTypeDescriptor blobTypeDescriptor = BlobTypeDescriptor.DEFAULT; - - @Override - public ValueBinder getBinder(JavaTypeDescriptor javaTypeDescriptor) { - return blobTypeDescriptor.getBinder(javaTypeDescriptor); - } - - @Override - public int getSqlType() { - return blobTypeDescriptor.getSqlType(); - } - - @Override - public ValueExtractor getExtractor(JavaTypeDescriptor javaTypeDescriptor) { - return blobTypeDescriptor.getExtractor(javaTypeDescriptor); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBytesSqlTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBytesSqlTypeDescriptor.java deleted file mode 100644 index c9c1c57fc..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonBytesSqlTypeDescriptor.java +++ /dev/null @@ -1,98 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.internal; - -import org.hibernate.dialect.Database; -import org.hibernate.type.descriptor.ValueBinder; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.hibernate.type.descriptor.sql.BasicBinder; - -import java.io.UnsupportedEncodingException; -import java.sql.*; -import java.util.HashMap; -import java.util.Map; - -/** - * @author Vlad Mihalcea - */ -public class JsonBytesSqlTypeDescriptor extends AbstractJsonSqlTypeDescriptor { - - public static final JsonBytesSqlTypeDescriptor INSTANCE = new JsonBytesSqlTypeDescriptor(); - - private static final Map INSTANCE_MAP = new HashMap<>(); - - static { - INSTANCE_MAP.put(Database.H2, INSTANCE); - INSTANCE_MAP.put(Database.ORACLE, new JsonBytesSqlTypeDescriptor(2016)); - } - - public static JsonBytesSqlTypeDescriptor of(Database database) { - return INSTANCE_MAP.get(database); - } - - public static final String CHARSET = "UTF8"; - - private final int jdbcType; - - public JsonBytesSqlTypeDescriptor() { - this.jdbcType = Types.BINARY; - } - - public JsonBytesSqlTypeDescriptor(int jdbcType) { - this.jdbcType = jdbcType; - } - - @Override - public int getSqlType() { - return jdbcType; - } - - @Override - public ValueBinder getBinder(final JavaTypeDescriptor javaTypeDescriptor) { - return new BasicBinder(javaTypeDescriptor, this) { - @Override - protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { - st.setBytes(index, toJsonBytes(javaTypeDescriptor.unwrap(value, String.class, options))); - } - - @Override - protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) - throws SQLException { - st.setBytes(name, toJsonBytes(javaTypeDescriptor.unwrap(value, String.class, options))); - } - }; - } - - @Override - protected Object extractJson(ResultSet rs, String name) throws SQLException { - return fromJsonBytes(rs.getBytes(name)); - } - - @Override - protected Object extractJson(CallableStatement statement, int index) throws SQLException { - return fromJsonBytes(statement.getBytes(index)); - } - - @Override - protected Object extractJson(CallableStatement statement, String name) throws SQLException { - return fromJsonBytes(statement.getBytes(name)); - } - - protected byte[] toJsonBytes(String jsonValue) { - try { - return jsonValue.getBytes(CHARSET); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException(e); - } - } - - protected String fromJsonBytes(byte[] jsonBytes) { - if (jsonBytes == null) { - return null; - } - try { - return new String(jsonBytes, CHARSET); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException(e); - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonNodeTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonNodeTypeDescriptor.java deleted file mode 100644 index a6a9ae8f8..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonNodeTypeDescriptor.java +++ /dev/null @@ -1,90 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.internal; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.type.util.ObjectMapperWrapper; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; -import org.hibernate.type.descriptor.java.MutableMutabilityPlan; - -import java.io.Serializable; - -/** - * @author Vlad Mihalcea - */ -public class JsonNodeTypeDescriptor - extends AbstractTypeDescriptor { - - public static final JsonNodeTypeDescriptor INSTANCE = new JsonNodeTypeDescriptor(); - - private ObjectMapperWrapper objectMapperWrapper; - - public JsonNodeTypeDescriptor() { - this(ObjectMapperWrapper.INSTANCE); - } - - public JsonNodeTypeDescriptor(final ObjectMapperWrapper objectMapperWrapper) { - super(JsonNode.class, new MutableMutabilityPlan() { - @Override - public Serializable disassemble(JsonNode value) { - return JacksonUtil.toString(value); - } - - @Override - public JsonNode assemble(Serializable cached) { - return JacksonUtil.toJsonNode((String) cached); - } - - @Override - protected JsonNode deepCopyNotNull(JsonNode value) { - return objectMapperWrapper.clone(value); - } - }); - this.objectMapperWrapper = objectMapperWrapper; - } - - @Override - public boolean areEqual(JsonNode one, JsonNode another) { - if (one == another) { - return true; - } - if (one == null || another == null) { - return false; - } - return objectMapperWrapper.toJsonNode(objectMapperWrapper.toString(one)).equals( - objectMapperWrapper.toJsonNode(objectMapperWrapper.toString(another))); - } - - @Override - public String toString(JsonNode value) { - return objectMapperWrapper.toString(value); - } - - @Override - public JsonNode fromString(String string) { - return objectMapperWrapper.toJsonNode(string); - } - - @SuppressWarnings({"unchecked"}) - @Override - public X unwrap(JsonNode value, Class type, WrapperOptions options) { - if (value == null) { - return null; - } - if (String.class.isAssignableFrom(type)) { - return (X) toString(value); - } - if (JsonNode.class.isAssignableFrom(type)) { - return (X) objectMapperWrapper.toJsonNode(toString(value)); - } - throw unknownUnwrap(type); - } - - @Override - public JsonNode wrap(X value, WrapperOptions options) { - if (value == null) { - return null; - } - return fromString(value.toString()); - } - -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonSqlTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonSqlTypeDescriptor.java deleted file mode 100644 index 70ccaa61a..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonSqlTypeDescriptor.java +++ /dev/null @@ -1,130 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.internal; - -import io.hypersistence.utils.hibernate.type.util.ParameterTypeUtils; -import io.hypersistence.utils.hibernate.util.StringUtils; -import org.hibernate.dialect.*; -import org.hibernate.engine.jdbc.dialect.internal.StandardDialectResolver; -import org.hibernate.engine.jdbc.dialect.spi.DatabaseMetaDataDialectResolutionInfoAdapter; -import org.hibernate.type.descriptor.ValueBinder; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.hibernate.type.descriptor.sql.BasicBinder; -import org.hibernate.usertype.DynamicParameterizedType; -import org.hibernate.usertype.ParameterizedType; - -import java.sql.*; -import java.util.Properties; - -/** - * @author Vlad Mihalcea - */ -public class JsonSqlTypeDescriptor extends AbstractJsonSqlTypeDescriptor implements ParameterizedType { - - private volatile Dialect dialect; - private volatile AbstractJsonSqlTypeDescriptor sqlTypeDescriptor; - - private volatile Properties properties; - - public JsonSqlTypeDescriptor() { - } - - public JsonSqlTypeDescriptor(Properties properties) { - this.properties = properties; - } - - @Override - public ValueBinder getBinder(final JavaTypeDescriptor javaTypeDescriptor) { - return new BasicBinder(javaTypeDescriptor, this) { - @Override - protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { - sqlTypeDescriptor(st.getConnection()).getBinder(javaTypeDescriptor).bind( - st, value, index, options - ); - } - - @Override - protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) - throws SQLException { - sqlTypeDescriptor(st.getConnection()).getBinder(javaTypeDescriptor).bind( - st, value, name, options - ); - } - }; - } - - @Override - protected Object extractJson(ResultSet rs, String name) throws SQLException { - return sqlTypeDescriptor(rs.getStatement().getConnection()).extractJson(rs, name); - } - - @Override - protected Object extractJson(CallableStatement statement, int index) throws SQLException { - return sqlTypeDescriptor(statement.getConnection()).extractJson(statement, index); - } - - @Override - protected Object extractJson(CallableStatement statement, String name) throws SQLException { - return sqlTypeDescriptor(statement.getConnection()).extractJson(statement, name); - } - - private AbstractJsonSqlTypeDescriptor sqlTypeDescriptor(Connection connection) { - if (sqlTypeDescriptor == null) { - sqlTypeDescriptor = resolveSqlTypeDescriptor(connection); - } - return sqlTypeDescriptor; - } - - private AbstractJsonSqlTypeDescriptor resolveSqlTypeDescriptor(Connection connection) { - try { - StandardDialectResolver dialectResolver = new StandardDialectResolver(); - DatabaseMetaDataDialectResolutionInfoAdapter metaDataInfo = new DatabaseMetaDataDialectResolutionInfoAdapter(connection.getMetaData()); - dialect = dialectResolver.resolveDialect(metaDataInfo); - if (dialect instanceof PostgreSQL81Dialect) { - return JsonBinarySqlTypeDescriptor.INSTANCE; - } else if (dialect instanceof H2Dialect) { - return JsonBytesSqlTypeDescriptor.INSTANCE; - } else if (dialect instanceof Oracle8iDialect) { - if (properties != null) { - DynamicParameterizedType.ParameterType parameterType = ParameterTypeUtils.resolve(properties); - if (parameterType != null) { - String columnType = ParameterTypeUtils.getColumnType(parameterType); - if (!StringUtils.isBlank(columnType)) { - switch (columnType) { - case "json": - return JsonBytesSqlTypeDescriptor.of(Database.ORACLE); - case "blob": - case "clob": - return JsonBlobSqlTypeDescriptor.INSTANCE; - case "varchar2": - case "nvarchar2": - return JsonStringSqlTypeDescriptor.INSTANCE; - } - } - } - } - if (metaDataInfo.getDatabaseMajorVersion() >= 21) { - return JsonBytesSqlTypeDescriptor.of(Database.ORACLE); - } - } - return JsonStringSqlTypeDescriptor.INSTANCE; - } catch (SQLException e) { - throw new IllegalStateException(e); - } - } - - @Override - public int getSqlType() { - return sqlTypeDescriptor != null ? - sqlTypeDescriptor.getSqlType() : - super.getSqlType(); - } - - @Override - public void setParameterValues(Properties parameters) { - if (properties == null) { - properties = parameters; - } else { - properties.putAll(parameters); - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonStringSqlTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonStringSqlTypeDescriptor.java deleted file mode 100644 index 6650862da..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonStringSqlTypeDescriptor.java +++ /dev/null @@ -1,52 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.internal; - -import org.hibernate.type.descriptor.ValueBinder; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.hibernate.type.descriptor.sql.BasicBinder; - -import java.sql.*; - -/** - * @author Vlad Mihalcea - */ -public class JsonStringSqlTypeDescriptor extends AbstractJsonSqlTypeDescriptor { - - public static final JsonStringSqlTypeDescriptor INSTANCE = new JsonStringSqlTypeDescriptor(); - - @Override - public int getSqlType() { - return Types.VARCHAR; - } - - @Override - public ValueBinder getBinder(final JavaTypeDescriptor javaTypeDescriptor) { - return new BasicBinder(javaTypeDescriptor, this) { - @Override - protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { - st.setString(index, javaTypeDescriptor.unwrap(value, String.class, options)); - } - - @Override - protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) - throws SQLException { - st.setString(name, javaTypeDescriptor.unwrap(value, String.class, options)); - } - }; - } - - @Override - protected Object extractJson(ResultSet rs, String name) throws SQLException { - return rs.getString(name); - } - - @Override - protected Object extractJson(CallableStatement statement, int index) throws SQLException { - return statement.getString(index); - } - - @Override - protected Object extractJson(CallableStatement statement, String name) throws SQLException { - return statement.getString(name); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonTypeDescriptor.java deleted file mode 100644 index ceb4d338b..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/json/internal/JsonTypeDescriptor.java +++ /dev/null @@ -1,226 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.internal; - -import io.hypersistence.utils.hibernate.type.util.ObjectMapperWrapper; -import io.hypersistence.utils.hibernate.util.LogUtils; -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import org.hibernate.HibernateException; -import org.hibernate.annotations.common.reflection.XProperty; -import org.hibernate.annotations.common.reflection.java.JavaXMember; -import org.hibernate.engine.jdbc.BinaryStream; -import org.hibernate.engine.jdbc.internal.BinaryStreamImpl; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; -import org.hibernate.type.descriptor.java.BlobTypeDescriptor; -import org.hibernate.type.descriptor.java.DataHelper; -import org.hibernate.type.descriptor.java.MutableMutabilityPlan; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.sql.Blob; -import java.sql.SQLException; -import java.util.*; - -/** - * @author Vlad Mihalcea - */ -public class JsonTypeDescriptor - extends AbstractTypeDescriptor implements DynamicParameterizedType { - - private Type propertyType; - - private Class propertyClass; - - private ObjectMapperWrapper objectMapperWrapper; - - public JsonTypeDescriptor() { - this(ObjectMapperWrapper.INSTANCE); - } - - public JsonTypeDescriptor(Type type) { - this(); - setPropertyClass(type); - } - - public JsonTypeDescriptor(final ObjectMapperWrapper objectMapperWrapper) { - super(Object.class, new MutableMutabilityPlan() { - @Override - protected Object deepCopyNotNull(Object value) { - return objectMapperWrapper.clone(value); - } - }); - this.objectMapperWrapper = objectMapperWrapper; - } - - public JsonTypeDescriptor(final ObjectMapperWrapper objectMapperWrapper, Type type) { - this(objectMapperWrapper); - setPropertyClass(type); - } - - @Override - public void setParameterValues(Properties parameters) { - final XProperty xProperty = (XProperty) parameters.get(DynamicParameterizedType.XPROPERTY); - Type type = null; - if(xProperty instanceof JavaXMember) { - type = ((JavaXMember) xProperty).getJavaType(); - } else { - Object parameterType = parameters.get(PARAMETER_TYPE); - if(parameterType instanceof ParameterType) { - type = ((ParameterType) parameterType).getReturnedClass(); - } else if(parameterType instanceof String) { - type = ReflectionUtils.getClass((String) parameterType); - } - } - if(type == null) { - throw new HibernateException("Could not resolve property type!"); - } - setPropertyClass(type); - } - - @Override - public boolean areEqual(Object one, Object another) { - if (one == another) { - return true; - } - if (one == null || another == null) { - return false; - } - if (one instanceof String && another instanceof String) { - return one.equals(another); - } - if ((one instanceof Collection && another instanceof Collection) || - (one instanceof Map && another instanceof Map)) { - return Objects.equals(one, another); - } - if (one.getClass().equals(another.getClass())) { - Method equalsMethod = ReflectionUtils.getMethodOrNull(one.getClass(), "equals", Object.class); - if (equalsMethod != null && !Object.class.equals(equalsMethod.getDeclaringClass())) { - return one.equals(another); - } - } - return objectMapperWrapper.toJsonNode(objectMapperWrapper.toString(one)).equals( - objectMapperWrapper.toJsonNode(objectMapperWrapper.toString(another)) - ); - } - - @Override - public String toString(Object value) { - return objectMapperWrapper.toString(value); - } - - @Override - public Object fromString(String string) { - if(propertyClass == null) { - throw new HibernateException( - "The propertyClass in JsonTypeDescriptor is null, " + - "hence it doesn't know to what Java Object type " + - "to map the JSON column value that was read from the database!" - ); - } - if (String.class.isAssignableFrom(propertyClass)) { - return string; - } - return objectMapperWrapper.fromString(string, propertyType); - } - - @SuppressWarnings({"unchecked"}) - @Override - public X unwrap(Object value, Class type, WrapperOptions options) { - if (value == null) { - return null; - } - - if (String.class.isAssignableFrom(type)) { - return value instanceof String ? (X) value : (X) toString(value); - } else if (BinaryStream.class.isAssignableFrom(type) || - byte[].class.isAssignableFrom(type)) { - String stringValue = (value instanceof String) ? (String) value : toString(value); - - return (X) new BinaryStreamImpl(DataHelper.extractBytes(new ByteArrayInputStream(stringValue.getBytes()))); - } else if (Blob.class.isAssignableFrom(type)) { - String stringValue = (value instanceof String) ? (String) value : toString(value); - - final Blob blob = BlobTypeDescriptor.INSTANCE.fromString(stringValue); - return (X) blob; - } else if (Object.class.isAssignableFrom(type)) { - String stringValue = (value instanceof String) ? (String) value : toString(value); - return (X) objectMapperWrapper.toJsonNode(stringValue); - } - - throw unknownUnwrap(type); - } - - @Override - public Object wrap(X value, WrapperOptions options) { - if (value == null) { - return null; - } - - Blob blob = null; - - if (Blob.class.isAssignableFrom(value.getClass())) { - blob = options.getLobCreator().wrap((Blob) value); - } else if (byte[].class.isAssignableFrom(value.getClass())) { - blob = options.getLobCreator().createBlob((byte[]) value); - } else if (InputStream.class.isAssignableFrom(value.getClass())) { - InputStream inputStream = (InputStream) value; - try { - blob = options.getLobCreator().createBlob(inputStream, inputStream.available()); - } catch (IOException e) { - throw unknownWrap(value.getClass()); - } - } - - String stringValue; - try { - stringValue = (blob != null) ? new String(DataHelper.extractBytes(blob.getBinaryStream())) : value.toString(); - } catch (SQLException e) { - throw new HibernateException("Unable to extract binary stream from Blob", e); - } - - return fromString(stringValue); - } - - private void setPropertyClass(Type type) { - this.propertyType = type; - if (type instanceof ParameterizedType) { - type = ((ParameterizedType) type).getRawType(); - } else if (type instanceof TypeVariable) { - type = ((TypeVariable) type).getGenericDeclaration().getClass(); - } - this.propertyClass = (Class) type; - validatePropertyType(); - } - - private void validatePropertyType() { - if(Collection.class.isAssignableFrom(propertyClass)) { - if (propertyType instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) propertyType; - - for(Class genericType : ReflectionUtils.getGenericTypes(parameterizedType)) { - synchronized (validatedTypes) { - if(!validatedTypes.add(genericType)) { - continue; - } - } - Method equalsMethod = ReflectionUtils.getMethodOrNull(genericType, "equals", Object.class); - Method hashCodeMethod = ReflectionUtils.getMethodOrNull(genericType, "hashCode"); - - if(equalsMethod == null || - hashCodeMethod == null || - Object.class.equals(equalsMethod.getDeclaringClass()) || - Object.class.equals(hashCodeMethod.getDeclaringClass())) { - LogUtils.LOGGER.warn("The {} class should override both the equals and hashCode methods based on the JSON object value it represents!", genericType); - } - } - } - } - } - - private static final Set validatedTypes = new HashSet<>(); -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/CurrencyUnitType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/CurrencyUnitType.java deleted file mode 100644 index 9cebc8904..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/CurrencyUnitType.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.hypersistence.utils.hibernate.type.money; - -import io.hypersistence.utils.hibernate.type.AbstractHibernateType; -import io.hypersistence.utils.hibernate.type.money.internal.CurrencyUnitTypeDescriptor; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; - -import javax.money.CurrencyUnit; - -/** - * Maps a Java {@link CurrencyUnit} object to a {@code VARCHAR} column type. - * - * @author Piotr Olaszewski - */ -public class CurrencyUnitType extends AbstractHibernateType { - public static final CurrencyUnitType INSTANCE = new CurrencyUnitType(); - - public CurrencyUnitType() { - super(VarcharTypeDescriptor.INSTANCE, CurrencyUnitTypeDescriptor.INSTANCE); - } - - public CurrencyUnitType(Configuration configuration) { - super( - VarcharTypeDescriptor.INSTANCE, - CurrencyUnitTypeDescriptor.INSTANCE, - configuration - ); - } - - @Override - public String getName() { - return "currency"; - } - - @Override - protected boolean registerUnderJavaType() { - return true; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/MonetaryAmountType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/MonetaryAmountType.java deleted file mode 100644 index 6bdddf917..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/MonetaryAmountType.java +++ /dev/null @@ -1,115 +0,0 @@ -package io.hypersistence.utils.hibernate.type.money; - -import io.hypersistence.utils.hibernate.type.ImmutableCompositeType; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.HibernateException; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.type.BigDecimalType; -import org.hibernate.type.StringType; -import org.hibernate.type.Type; -import org.javamoney.moneta.Money; - -import javax.money.MonetaryAmount; -import java.math.BigDecimal; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -import static java.sql.Types.DECIMAL; -import static java.sql.Types.VARCHAR; - -/** - * Maps a {@link MonetaryAmount} object type onto two columns (amount and currency). - * - *

- * For more details about how to use it, - * check out this article - * on vladmihalcea.com. - * - * @author Piotr Olaszewski - * @author Edgar Asatryan - */ -public class MonetaryAmountType extends ImmutableCompositeType { - - public static final MonetaryAmountType INSTANCE = new MonetaryAmountType(); - - public MonetaryAmountType() { - super(MonetaryAmount.class); - } - - public MonetaryAmountType(Configuration configuration) { - super(MonetaryAmount.class, configuration); - } - - @Override - public String[] getPropertyNames() { - return new String[]{"amount", "currency"}; - } - - @Override - public Type[] getPropertyTypes() { - return new Type[]{BigDecimalType.INSTANCE, StringType.INSTANCE}; - } - - @Override - public Object getPropertyValue(Object component, int property) throws HibernateException { - MonetaryAmount monetaryAmount = (MonetaryAmount) component; - if (property == 0) { - return monetaryAmount.getNumber().numberValue(BigDecimal.class); - } else if (property == 1) { - return monetaryAmount.getCurrency(); - } - - throw new IllegalArgumentException("Invalid property index " + property + " for class " + component.getClass()); - } - - @Override - public void setPropertyValue(Object component, int property, Object value) throws HibernateException { - throw new HibernateException("Call setPropertyValue on immutable type " + component.getClass()); - } - - @Override - protected MonetaryAmount get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { - String amountColumnName = names[0]; - String currencyColumnName = names[1]; - - BigDecimal amount = rs.getBigDecimal(amountColumnName); - if(amount == null) { - return null; - } - String currency = rs.getString(currencyColumnName); - if(currency == null) { - return null; - } - - return Money.of(amount, currency); - } - - @Override - protected void set(PreparedStatement st, MonetaryAmount value, int amountColumnIndex, SharedSessionContractImplementor session) throws SQLException { - int currencyColumnIndex = amountColumnIndex + 1; - - if (value == null) { - st.setNull(amountColumnIndex, DECIMAL); - st.setNull(currencyColumnIndex, VARCHAR); - } else { - BigDecimal amount = value.getNumber().numberValue(BigDecimal.class); - String currency = value.getCurrency().getCurrencyCode(); - - st.setBigDecimal(amountColumnIndex, amount); - st.setString(currencyColumnIndex, currency); - } - } - - @Override - public int getPropertyIndex(String propertyName) { - switch (propertyName) { - case "amount": - return 0; - case "currency": - return 1; - default: - throw new IllegalArgumentException("Unknown property name: " + propertyName); - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/internal/CurrencyUnitTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/internal/CurrencyUnitTypeDescriptor.java deleted file mode 100644 index 592774c6f..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/money/internal/CurrencyUnitTypeDescriptor.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.hypersistence.utils.hibernate.type.money.internal; - -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; - -import javax.money.CurrencyUnit; -import javax.money.Monetary; - -/** - * @author Piotr Olaszewski - */ -public class CurrencyUnitTypeDescriptor extends AbstractTypeDescriptor { - - public static final CurrencyUnitTypeDescriptor INSTANCE = new CurrencyUnitTypeDescriptor(); - - public CurrencyUnitTypeDescriptor() { - super(CurrencyUnit.class); - } - - @Override - public CurrencyUnit fromString(String string) { - return Monetary.getCurrency(string); - } - - @Override - public X unwrap(CurrencyUnit value, Class type, WrapperOptions options) { - if (value == null) { - return null; - } - - if (String.class.isAssignableFrom(type)) { - return (X) value.getCurrencyCode(); - } - - throw unknownUnwrap(type); - } - - @Override - public CurrencyUnit wrap(X value, WrapperOptions options) { - if (value == null) { - return null; - } - - if (value instanceof String) { - return fromString((String) value); - } - - throw unknownWrap(value.getClass()); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeType.java deleted file mode 100644 index 639483d75..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeType.java +++ /dev/null @@ -1,140 +0,0 @@ -package io.hypersistence.utils.hibernate.type.range; - -import io.hypersistence.utils.hibernate.type.ImmutableType; -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import org.hibernate.HibernateException; -import org.hibernate.annotations.common.reflection.XProperty; -import org.hibernate.annotations.common.reflection.java.JavaXMember; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZonedDateTime; -import java.util.Properties; - -/** - * Maps a {@link Range} object type to a PostgreSQL range - * column type. - *

- * Supported range types: - *

    - *
  • int4range
  • - *
  • int8range
  • - *
  • numrange
  • - *
  • tsrange
  • - *
  • tstzrange
  • - *
  • daterange
  • - *
- *

- * For more details about how to use it, - * check out this article - * on vladmihalcea.com. - * - * @author Edgar Asatryan - * @author Vlad Mihalcea - */ -public class PostgreSQLRangeType extends ImmutableType implements DynamicParameterizedType { - - public static final PostgreSQLRangeType INSTANCE = new PostgreSQLRangeType(); - - private Type type; - - public PostgreSQLRangeType() { - super(Range.class); - } - - @Override - public int[] sqlTypes() { - return new int[]{Types.OTHER}; - } - - @Override - protected Range get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { - Object pgObject = rs.getObject(names[0]); - - if (pgObject == null) { - return null; - } - - String type = ReflectionUtils.invokeGetter(pgObject, "type"); - String value = ReflectionUtils.invokeGetter(pgObject, "value"); - - switch (type) { - case "int4range": - return Range.integerRange(value); - case "int8range": - return Range.longRange(value); - case "numrange": - return Range.bigDecimalRange(value); - case "tsrange": - return Range.localDateTimeRange(value); - case "tstzrange": - return Range.zonedDateTimeRange(value); - case "daterange": - return Range.localDateRange(value); - default: - throw new HibernateException( - new IllegalStateException("The range type [" + type + "] is not supported!") - ); - } - } - - @Override - protected void set(PreparedStatement st, Range range, int index, SharedSessionContractImplementor session) throws SQLException { - - if (range == null) { - st.setNull(index, Types.OTHER); - } else { - Object holder = ReflectionUtils.newInstance("org.postgresql.util.PGobject"); - ReflectionUtils.invokeSetter(holder, "type", determineRangeType(range)); - ReflectionUtils.invokeSetter(holder, "value", range.asString()); - st.setObject(index, holder); - } - } - - private static String determineRangeType(Range range) { - Class clazz = range.getClazz(); - - if (clazz.equals(Integer.class)) { - return "int4range"; - } else if (clazz.equals(Long.class)) { - return "int8range"; - } else if (clazz.equals(BigDecimal.class)) { - return "numrange"; - } else if (clazz.equals(LocalDateTime.class)) { - return "tsrange"; - } else if (clazz.equals(ZonedDateTime.class)) { - return "tstzrange"; - } else if (clazz.equals(LocalDate.class)) { - return "daterange"; - } - - throw new HibernateException( - new IllegalStateException("The class [" + clazz.getName() + "] is not supported!") - ); - } - - @Override - public void setParameterValues(Properties parameters) { - final XProperty xProperty = (XProperty) parameters.get(DynamicParameterizedType.XPROPERTY); - if (xProperty instanceof JavaXMember) { - type = ((JavaXMember) xProperty).getJavaType(); - } else { - type = ((ParameterType) parameters.get(PARAMETER_TYPE)).getReturnedClass(); - } - } - - public Class getElementType() { - return type instanceof ParameterizedType ? - (Class) ((ParameterizedType) type).getActualTypeArguments()[0] : null; - } - -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/Range.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/Range.java deleted file mode 100644 index 33f7cf040..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/Range.java +++ /dev/null @@ -1,680 +0,0 @@ -package io.hypersistence.utils.hibernate.type.range; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.time.*; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.DateTimeParseException; -import java.time.temporal.ChronoField; -import java.util.Objects; -import java.util.function.Function; - -/** - * Represents the range/interval with two bounds. Abstraction follows the semantics of the mathematical interval. The - * range can be unbounded, empty or open from the left or/and unbounded from the right. The range supports half-open or closed - * bounds on both sides. - * - *

- * The class has some very simple methods for usability. For example {@link Range#contains(Comparable)} method can tell user whether - * this range contains argument or not. The {@link Range#contains(Range)} helps to find out whether this range fully - * enclosing argument or not. - *

- * For more details about how to use it, - * check out this article - * on vladmihalcea.com. - * - * @author Edgar Asatryan - * @author Vlad Mihalcea - */ -public final class Range> implements Serializable { - - public static final int LOWER_INCLUSIVE = 1 << 1; - public static final int LOWER_EXCLUSIVE = 1 << 2; - public static final int UPPER_INCLUSIVE = 1 << 3; - public static final int UPPER_EXCLUSIVE = 1 << 4; - public static final int LOWER_INFINITE = (1 << 5) | LOWER_EXCLUSIVE; - public static final int UPPER_INFINITE = (1 << 6) | UPPER_EXCLUSIVE; - - public static final String EMPTY = "empty"; - - public static final String INFINITY = "infinity"; - - private static final DateTimeFormatter LOCAL_DATE_TIME = new DateTimeFormatterBuilder() - .appendPattern("yyyy-MM-dd HH:mm:ss") - .optionalStart() - .appendPattern(".") - .appendFraction(ChronoField.NANO_OF_SECOND, 1, 6, false) - .optionalEnd() - .toFormatter(); - - private static final DateTimeFormatter ZONE_DATE_TIME = new DateTimeFormatterBuilder() - .appendPattern("yyyy-MM-dd HH:mm:ss") - .optionalStart() - .appendPattern(".") - .appendFraction(ChronoField.NANO_OF_SECOND, 1, 6, false) - .optionalEnd() - .appendOffset("+HH:mm", "Z") - .toFormatter(); - - private final T lower; - private final T upper; - private final int mask; - private final Class clazz; - - private Range(T lower, T upper, int mask, Class clazz) { - this.lower = lower; - this.upper = upper; - this.mask = mask; - this.clazz = clazz; - - if (isBounded() && lower != null && upper != null && lower.compareTo(upper) > 0) { - throw new IllegalArgumentException("The lower bound is greater then upper!"); - } - } - - /** - * Creates the closed range with provided bounds. - *

- * The mathematical equivalent will be: - *

{@code
-     *     [a, b] = {x | a <= x <= b}
-     * }
. - * - * @param lower The lower bound, never null. - * @param upper The upper bound, never null. - * @param The type of bounds. - * - * @return The closed range. - */ - @SuppressWarnings("unchecked") - public static > Range closed(T lower, T upper) { - Objects.requireNonNull(lower); - Objects.requireNonNull(upper); - return new Range<>(lower, upper, LOWER_INCLUSIVE | UPPER_INCLUSIVE, (Class) lower.getClass()); - } - - /** - * Creates the open range with provided bounds. - *

- * The mathematical equivalent will be: - *

{@code
-     *     (a, b) = {x | a < x < b}
-     * }
- * - * @param lower The lower bound, never null. - * @param upper The upper bound, never null. - * @param The type of bounds. - * - * @return The range. - */ - @SuppressWarnings("unchecked") - public static > Range open(T lower, T upper) { - Objects.requireNonNull(lower); - Objects.requireNonNull(upper); - return new Range<>(lower, upper, LOWER_EXCLUSIVE | UPPER_EXCLUSIVE, (Class) lower.getClass()); - } - - /** - * Creates the left-open, right-closed range with provided bounds. - *

- * The mathematical equivalent will be: - *

{@code
-     *     (a, b] = {x | a < x <= b}
-     * }
- * - * @param lower The lower bound, never null. - * @param upper The upper bound, never null. - * @param The type of bounds. - * - * @return The range. - */ - @SuppressWarnings("unchecked") - public static > Range openClosed(T lower, T upper) { - Objects.requireNonNull(lower); - Objects.requireNonNull(upper); - return new Range<>(lower, upper, LOWER_EXCLUSIVE | UPPER_INCLUSIVE, (Class) lower.getClass()); - } - - /** - * Creates the left-closed, right-open range with provided bounds. - *

- * The mathematical equivalent will be: - *

{@code
-     *     [a, b) = {x | a <= x < b}
-     * }
- * - * @param lower The lower bound, never null. - * @param upper The upper bound, never null. - * @param The type of bounds. - * - * @return The range. - */ - @SuppressWarnings("unchecked") - public static > Range closedOpen(T lower, T upper) { - Objects.requireNonNull(lower); - Objects.requireNonNull(upper); - return new Range<>(lower, upper, LOWER_INCLUSIVE | UPPER_EXCLUSIVE, (Class) lower.getClass()); - } - - /** - * Creates the left-bounded, left-open and right-unbounded range with provided lower bound. - *

- * The mathematical equivalent will be: - *

{@code
-     *     (a, +∞) = {x | x > a}
-     * }
- * - * @param lower The lower bound, never null. - * @param The type of bounds. - * - * @return The range. - */ - @SuppressWarnings("unchecked") - public static > Range openInfinite(T lower) { - Objects.requireNonNull(lower); - return new Range<>(lower, null, LOWER_EXCLUSIVE | UPPER_INFINITE, (Class) lower.getClass()); - } - - /** - * Creates the left-bounded, left-closed and right-unbounded range with provided lower bound. - *

- * The mathematical equivalent will be: - *

{@code
-     *     [a, +∞) = {x | x >= a}
-     * }
- * - * @param lower The lower bound, never null. - * @param The type of bounds. - * - * @return The range. - */ - @SuppressWarnings("unchecked") - public static > Range closedInfinite(T lower) { - Objects.requireNonNull(lower); - return new Range<>(lower, null, LOWER_INCLUSIVE | UPPER_INFINITE, (Class) lower.getClass()); - } - - /** - * Creates the left-unbounded, right-bounded and right-open range with provided upper bound. - *

- * The mathematical equivalent will be: - *

{@code
-     *     (-∞, b) = {x | x < b}
-     * }
- * - * @param upper The upper bound, never null. - * @param The type of bounds. - * - * @return The range. - */ - @SuppressWarnings("unchecked") - public static > Range infiniteOpen(T upper) { - Objects.requireNonNull(upper); - return new Range<>(null, upper, UPPER_EXCLUSIVE | LOWER_INFINITE, (Class) upper.getClass()); - } - - /** - * Creates the left-unbounded, right-bounded and right-closed range with provided upper bound. - *

- * The mathematical equivalent will be: - *

{@code
-     *     (-∞, b] = {x | x =< b}
-     * }
- * - * @param upper The upper bound, never null. - * @param The type of bounds. - * - * @return The range. - */ - @SuppressWarnings("unchecked") - public static > Range infiniteClosed(T upper) { - Objects.requireNonNull(upper); - return new Range<>(null, upper, UPPER_INCLUSIVE | LOWER_INFINITE, (Class) upper.getClass()); - } - - /** - * Creates the unbounded at both ends range with provided upper bound. - *

- * The mathematical equivalent will be: - *

{@code
-     *     (-∞, +∞) = ℝ
-     * }
- * - * @param cls The range class, never null. - * @param The type of bounds. - * - * @return The infinite range. - */ - public static > Range infinite(Class cls) { - return new Range<>(null, null, LOWER_INFINITE | UPPER_INFINITE, cls); - } - - /** - * Creates the empty range. In other words the range that contains no points. - *

- * The mathematical equivalent will be: - *

{@code
-     *     (a, a) = ∅
-     * }
- * - * @param cls The range class, never null. - * @param The type of bounds. - * - * @return The empty range. - */ - public static > Range emptyRange(Class cls) { - return new Range<>( - null, - null, - LOWER_EXCLUSIVE | UPPER_EXCLUSIVE, - cls - ); - } - - public static > Range ofString(String str, Function converter, Class clazz) { - if(str.equals(EMPTY)) { - return emptyRange(clazz); - } - - int mask = str.charAt(0) == '[' ? LOWER_INCLUSIVE : LOWER_EXCLUSIVE; - mask |= str.charAt(str.length() - 1) == ']' ? UPPER_INCLUSIVE : UPPER_EXCLUSIVE; - - int delim = str.indexOf(','); - - if (delim == -1) { - throw new IllegalArgumentException("Cannot find comma character"); - } - - String lowerStr = str.substring(1, delim); - String upperStr = str.substring(delim + 1, str.length() - 1); - - if (lowerStr.length() == 0 || lowerStr.endsWith(INFINITY)) { - mask |= LOWER_INFINITE; - } - - if (upperStr.length() == 0 || upperStr.endsWith(INFINITY)) { - mask |= UPPER_INFINITE; - } - - T lower = null; - T upper = null; - - if ((mask & LOWER_INFINITE) != LOWER_INFINITE) { - lower = converter.apply(lowerStr); - } - - if ((mask & UPPER_INFINITE) != UPPER_INFINITE) { - upper = converter.apply(upperStr); - } - - return new Range<>(lower, upper, mask, clazz); - } - - /** - * Creates the {@code BigDecimal} range from provided string: - *
{@code
-     *     Range closed = Range.bigDecimalRange("[0.1,1.1]");
-     *     Range halfOpen = Range.bigDecimalRange("(0.1,1.1]");
-     *     Range open = Range.bigDecimalRange("(0.1,1.1)");
-     *     Range leftUnbounded = Range.bigDecimalRange("(,1.1)");
-     * }
- * - * @param range The range string, for example {@literal "[5.5,7.8]"}. - * - * @return The range of {@code BigDecimal}s. - * - * @throws NumberFormatException when one of the bounds are invalid. - */ - public static Range bigDecimalRange(String range) { - return ofString(range, BigDecimal::new, BigDecimal.class); - } - - /** - * Creates the {@code Integer} range from provided string: - *
{@code
-     *     Range closed = Range.integerRange("[1,5]");
-     *     Range halfOpen = Range.integerRange("(-1,1]");
-     *     Range open = Range.integerRange("(1,2)");
-     *     Range leftUnbounded = Range.integerRange("(,10)");
-     *     Range unbounded = Range.integerRange("(,)");
-     * }
- * - * @param range The range string, for example {@literal "[5,7]"}. - * - * @return The range of {@code Integer}s. - * - * @throws NumberFormatException when one of the bounds are invalid. - */ - public static Range integerRange(String range) { - return ofString(range, Integer::parseInt, Integer.class); - } - - /** - * Creates the {@code Long} range from provided string: - *
{@code
-     *     Range closed = Range.longRange("[1,5]");
-     *     Range halfOpen = Range.longRange("(-1,1]");
-     *     Range open = Range.longRange("(1,2)");
-     *     Range leftUnbounded = Range.longRange("(,10)");
-     *     Range unbounded = Range.longRange("(,)");
-     * }
- * - * @param range The range string, for example {@literal "[5,7]"}. - * - * @return The range of {@code Long}s. - * - * @throws NumberFormatException when one of the bounds are invalid. - */ - public static Range longRange(String range) { - return ofString(range, Long::parseLong, Long.class); - } - - /** - * Creates the {@code LocalDateTime} range from provided string: - *
{@code
-     *     Range closed = Range.localDateTimeRange("[2014-04-28 16:00:49,2015-04-28 16:00:49]");
-     *     Range quoted = Range.localDateTimeRange("[\"2014-04-28 16:00:49\",\"2015-04-28 16:00:49\"]");
-     *     Range iso = Range.localDateTimeRange("[\"2014-04-28T16:00:49.2358\",\"2015-04-28T16:00:49\"]");
-     * }
- *

- * The valid formats for bounds are: - *

    - *
  • yyyy-MM-dd HH:mm:ss[.SSSSSS]
  • - *
  • yyyy-MM-dd'T'HH:mm:ss[.SSSSSS]
  • - *
- * - * @param range The range string, for example {@literal "[2014-04-28 16:00:49,2015-04-28 16:00:49]"}. - * - * @return The range of {@code LocalDateTime}s. - * - * @throws DateTimeParseException when one of the bounds are invalid. - */ - public static Range localDateTimeRange(String range) { - return ofString(range, parseLocalDateTime().compose(unquote()), LocalDateTime.class); - } - - /** - * Creates the {@code LocalDate} range from provided string: - *
{@code
-     *     Range closed = Range.localDateRange("[2014-04-28,2015-04-289]");
-     *     Range quoted = Range.localDateRange("[\"2014-04-28\",\"2015-04-28\"]");
-     *     Range iso = Range.localDateRange("[\"2014-04-28\",\"2015-04-28\"]");
-     * }
- *

- * The valid formats for bounds are: - *

    - *
  • yyyy-MM-dd
  • - *
  • yyyy-MM-dd
  • - *
- * - * @param range The range string, for example {@literal "[2014-04-28,2015-04-28]"}. - * - * @return The range of {@code LocalDate}s. - * - * @throws DateTimeParseException when one of the bounds are invalid. - */ - public static Range localDateRange(String range) { - Function parseLocalDate = LocalDate::parse; - return ofString(range, parseLocalDate.compose(unquote()), LocalDate.class); - } - - /** - * Creates the {@code ZonedDateTime} range from provided string: - *
{@code
-     *     Range closed = Range.zonedDateTimeRange("[2007-12-03T10:15:30+01:00\",\"2008-12-03T10:15:30+01:00]");
-     *     Range quoted = Range.zonedDateTimeRange("[\"2007-12-03T10:15:30+01:00\",\"2008-12-03T10:15:30+01:00\"]");
-     *     Range iso = Range.zonedDateTimeRange("[2011-12-03T10:15:30+01:00[Europe/Paris], 2012-12-03T10:15:30+01:00[Europe/Paris]]");
-     * }
- *

- * The valid formats for bounds are: - *

    - *
  • yyyy-MM-dd HH:mm:ss[.SSSSSS]X
  • - *
  • yyyy-MM-dd'T'HH:mm:ss[.SSSSSS]X
  • - *
- * - * @param rangeStr The range string, for example {@literal "[2011-12-03T10:15:30+01:00,2012-12-03T10:15:30+01:00]"}. - * - * @return The range of {@code ZonedDateTime}s. - * - * @throws DateTimeParseException when one of the bounds are invalid. - * @throws IllegalArgumentException when bounds time zones are different. - */ - public static Range zonedDateTimeRange(String rangeStr) { - Range range = ofString(rangeStr, parseZonedDateTime().compose(unquote()), ZonedDateTime.class); - if (range.hasLowerBound() && range.hasUpperBound() && !EMPTY.equals(rangeStr)) { - ZoneId lowerZone = range.lower().getZone(); - ZoneId upperZone = range.upper().getZone(); - if (!lowerZone.equals(upperZone)) { - Duration lowerDst = ZoneId.systemDefault().getRules().getDaylightSavings(range.lower().toInstant()); - Duration upperDst = ZoneId.systemDefault().getRules().getDaylightSavings(range.upper().toInstant()); - long dstSeconds = upperDst.minus(lowerDst).getSeconds(); - if(dstSeconds < 0 ) { - dstSeconds *= -1; - } - long zoneDriftSeconds = ((ZoneOffset) lowerZone).getTotalSeconds() - ((ZoneOffset) upperZone).getTotalSeconds(); - if (zoneDriftSeconds < 0) { - zoneDriftSeconds *= -1; - } - - if (dstSeconds != zoneDriftSeconds) { - throw new IllegalArgumentException("The upper and lower bounds must be in same time zone!"); - } - } - } - return range; - } - - private static Function parseLocalDateTime() { - return s -> { - try { - return LocalDateTime.parse(s, LOCAL_DATE_TIME); - } catch (DateTimeParseException e) { - return LocalDateTime.parse(s); - } - }; - } - - private static Function parseZonedDateTime() { - return s -> { - try { - return ZonedDateTime.parse(s, ZONE_DATE_TIME); - } catch (DateTimeParseException e) { - return ZonedDateTime.parse(s); - } - }; - } - - private static Function unquote() { - return s -> { - if (s.charAt(0) == '\"' && s.charAt(s.length() - 1) == '\"') { - return s.substring(1, s.length() - 1); - } - - return s; - }; - } - - public boolean isBounded() { - return !hasMask(LOWER_INFINITE) && !hasMask(UPPER_INFINITE); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Range)) return false; - Range range = (Range) o; - return mask == range.mask && - Objects.equals(lower, range.lower) && - Objects.equals(upper, range.upper) && - Objects.equals(clazz, range.clazz); - } - - @Override - public int hashCode() { - return Objects.hash(lower, upper, mask, clazz); - } - - @Override - public String toString() { - return "Range{" + "lower=" + lower + - ", upper=" + upper + - ", mask=" + mask + - ", clazz=" + clazz + - '}'; - } - - public boolean hasMask(int flag) { - return (mask & flag) == flag; - } - - public boolean isLowerBoundClosed() { - return hasLowerBound() && hasMask(LOWER_INCLUSIVE); - } - - public boolean isUpperBoundClosed() { - return hasUpperBound() && hasMask(UPPER_INCLUSIVE); - } - - public boolean hasLowerBound() { - return !hasMask(LOWER_INFINITE); - } - - public boolean hasUpperBound() { - return !hasMask(UPPER_INFINITE); - } - - /** - * Returns the lower bound of this range. If {@code null} is returned then this range is left-unbounded. - * - * @return The lower bound. - */ - public T lower() { - return lower; - } - - /** - * Returns the upper bound of this range. If {@code null} is returned then this range is right-unbounded. - * - * @return The upper bound. - */ - public T upper() { - return upper; - } - - /** - * Determines whether this range contains this point or not. - *

- * For example: - *

{@code
-     *     assertTrue(integerRange("[1,2]").contains(1))
-     *     assertTrue(integerRange("[1,2]").contains(2))
-     *     assertTrue(integerRange("[-1,1]").contains(0))
-     *     assertTrue(infinity(Integer.class).contains(Integer.MAX_VALUE))
-     *     assertTrue(infinity(Integer.class).contains(Integer.MIN_VALUE))
-     *
-     *     assertFalse(integerRange("(1,2]").contains(1))
-     *     assertFalse(integerRange("(1,2]").contains(3))
-     *     assertFalse(integerRange("[-1,1]").contains(0))
-     * }
- * - * @param point The point to check. - * - * @return Whether {@code point} in this range or not. - */ - public boolean contains(T point) { - if (isEmpty()) { - return false; - } - - boolean l = hasLowerBound(); - boolean u = hasUpperBound(); - - if (l && u) { - boolean inLower = hasMask(LOWER_INCLUSIVE) ? lower.compareTo(point) <= 0 : lower.compareTo(point) < 0; - boolean inUpper = hasMask(UPPER_INCLUSIVE) ? upper.compareTo(point) >= 0 : upper.compareTo(point) > 0; - - return inLower && inUpper; - } else if (l) { - return hasMask(LOWER_INCLUSIVE) ? lower.compareTo(point) <= 0 : lower.compareTo(point) < 0; - } else if (u) { - return hasMask(UPPER_INCLUSIVE) ? upper.compareTo(point) >= 0 : upper.compareTo(point) > 0; - } - - // INFINITY - return true; - } - - /** - * Determines whether this range contains this range or not. - *

- * For example: - *

{@code
-     *     assertTrue(integerRange("[-2,2]").contains(integerRange("[-1,1]")))
-     *     assertTrue(integerRange("(,)").contains(integerRange("(,)"))
-     *
-     *     assertFalse(integerRange("[-2,2)").contains(integerRange("[-1,2]")))
-     *     assertFalse(integerRange("(-2,2]").contains(1))
-     * }
- * - * @param range The range to check. - * - * @return Whether {@code range} in this range or not. - */ - public boolean contains(Range range) { - return !isEmpty() && (!range.hasLowerBound() || contains(range.lower)) && (!range.hasUpperBound() || contains(range.upper)); - } - - /** - * Determines whether this range is empty or not. - *

- * For example: - *

{@code
-     *     assertFalse(integerRange("empty").contains(1))
-     * }
- * - * @return Whether {@code range} in this range or not. - */ - public boolean isEmpty() { - return isBoundedOpen() && hasEqualBounds(); - } - - public boolean hasEqualBounds() { - return lower == null && upper == null - || lower != null && upper != null && lower.compareTo(upper) == 0; - } - - public boolean isBoundedOpen() { - return isBounded() && !isLowerBoundClosed() && !isUpperBoundClosed(); - } - - public String asString() { - if (lower == null && upper == null && isBoundedOpen()) { - return EMPTY; - } - - StringBuilder sb = new StringBuilder(); - - sb.append(hasMask(LOWER_INCLUSIVE) ? '[' : '(') - .append(hasLowerBound() ? boundToString().apply(lower) : "") - .append(",") - .append(hasUpperBound() ? boundToString().apply(upper) : "") - .append(hasMask(UPPER_INCLUSIVE) ? ']' : ')'); - - return sb.toString(); - } - - private Function boundToString() { - return t -> { - if (clazz.equals(ZonedDateTime.class)) { - return ZONE_DATE_TIME.format((ZonedDateTime) t); - } - - return t.toString(); - }; - } - - Class getClazz() { - return clazz; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/guava/PostgreSQLGuavaRangeType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/guava/PostgreSQLGuavaRangeType.java deleted file mode 100644 index 5a2e8d6cc..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/range/guava/PostgreSQLGuavaRangeType.java +++ /dev/null @@ -1,531 +0,0 @@ -package io.hypersistence.utils.hibernate.type.range.guava; - -import com.google.common.collect.BoundType; -import com.google.common.collect.Range; -import io.hypersistence.utils.hibernate.type.ImmutableType; -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import org.hibernate.HibernateException; -import org.hibernate.annotations.common.reflection.XProperty; -import org.hibernate.annotations.common.reflection.java.JavaXMember; -import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.time.Duration; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.DateTimeParseException; -import java.time.temporal.ChronoField; -import java.util.Properties; -import java.util.function.Function; - -/** - * Maps a {@link Range} object type to a PostgreSQL range - * column type. - *

- * Supported range types: - *

    - *
  • int4range
  • - *
  • int8range
  • - *
  • numrange
  • - *
  • tsrange
  • - *
  • tstzrange
  • - *
  • daterange
  • - *
- * - * @author Edgar Asatryan - * @author Vlad Mihalcea - * @author Jan-Willem Gmelig Meyling - */ -public class PostgreSQLGuavaRangeType extends ImmutableType implements DynamicParameterizedType { - - /** - * An empty int range that satisfies {@link Range#isEmpty()} to map PostgreSQL's {@code empty} to. - */ - private static final Range EMPTY_INT_RANGE = Range.closedOpen(Integer.MIN_VALUE, Integer.MIN_VALUE); - - /** - * An empty int range that satisfies {@link Range#isEmpty()} to map PostgreSQL's {@code empty} to. - */ - private static final Range EMPTY_LONG_RANGE = Range.closedOpen(Long.MIN_VALUE, Long.MIN_VALUE); - - /** - * An empty int range that satisfies {@link Range#isEmpty()} to map PostgreSQL's {@code empty} to. - */ - private static final Range EMPTY_BIGDECIMAL_RANGE = Range.closedOpen(BigDecimal.ZERO, BigDecimal.ZERO); - - /** - * An empty int range that satisfies {@link Range#isEmpty()} to map PostgreSQL's {@code empty} to. - */ - private static final Range EMPTY_LOCALDATETIME_RANGE = Range.closedOpen(LocalDateTime.MIN, LocalDateTime.MIN); - - /** - * An empty int range that satisfies {@link Range#isEmpty()} to map PostgreSQL's {@code empty} to. - */ - private static final Range EMPTY_OFFSETDATETIME_RANGE = Range.closedOpen(OffsetDateTime.MIN, OffsetDateTime.MIN); - - /** - * An empty int range that satisfies {@link Range#isEmpty()} to map PostgreSQL's {@code empty} to. - */ - private static final Range EMPTY_ZONEDDATETIME_RANGE = Range.closedOpen(OffsetDateTime.MIN.toZonedDateTime(), OffsetDateTime.MIN.toZonedDateTime()); - - /** - * An empty int range that satisfies {@link Range#isEmpty()} to map PostgreSQL's {@code empty} to. - */ - private static final Range EMPTY_DATE_RANGE = Range.closedOpen(LocalDate.MIN, LocalDate.MIN); - - private static final DateTimeFormatter LOCAL_DATE_TIME = new DateTimeFormatterBuilder() - .appendPattern("yyyy-MM-dd HH:mm:ss") - .optionalStart() - .appendPattern(".") - .appendFraction(ChronoField.NANO_OF_SECOND, 1, 6, false) - .optionalEnd() - .toFormatter(); - - private static final DateTimeFormatter OFFSET_DATE_TIME = new DateTimeFormatterBuilder() - .appendPattern("yyyy-MM-dd HH:mm:ss") - .optionalStart() - .appendPattern(".") - .appendFraction(ChronoField.NANO_OF_SECOND, 1, 6, false) - .optionalEnd() - .appendPattern("X") - .toFormatter(); - - public static final PostgreSQLGuavaRangeType INSTANCE = new PostgreSQLGuavaRangeType(); - - private Type type; - - private Class elementType; - - public PostgreSQLGuavaRangeType() { - super(Range.class); - } - - public PostgreSQLGuavaRangeType(Class elementType) { - super(Range.class); - this.elementType = elementType; - } - - @Override - public int[] sqlTypes() { - return new int[]{Types.OTHER}; - } - - @Override - protected Range get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { - Object pgObject = rs.getObject(names[0]); - - if (pgObject == null) { - return null; - } - - String type = ReflectionUtils.invokeGetter(pgObject, "type"); - String value = ReflectionUtils.invokeGetter(pgObject, "value"); - - switch (type) { - case "int4range": - return integerRange(value); - case "int8range": - return longRange(value); - case "numrange": - return bigDecimalRange(value); - case "tsrange": - return localDateTimeRange(value); - case "tstzrange": - return ZonedDateTime.class.equals(elementType) ? zonedDateTimeRange(value) : offsetDateTimeRange(value); - case "daterange": - return localDateRange(value); - default: - throw new HibernateException( - new IllegalStateException("The range type [" + type + "] is not supported!") - ); - } - } - - @Override - protected void set(PreparedStatement st, Range range, int index, SharedSessionContractImplementor session) throws SQLException { - if (range == null) { - st.setNull(index, Types.OTHER); - } else { - Object holder = ReflectionUtils.newInstance("org.postgresql.util.PGobject"); - ReflectionUtils.invokeSetter(holder, "type", determineRangeType(range)); - ReflectionUtils.invokeSetter(holder, "value", asString(range)); - st.setObject(index, holder); - } - } - - private String determineRangeType(Range range) { - Type clazz = this.elementType; - - if (clazz == null) { - Object anyEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : - range.hasUpperBound() ? range.upperEndpoint() : null; - - if (anyEndpoint == null) { - throw new HibernateException( - new IllegalArgumentException("The range " + range + " doesn't have any upper or lower bound!") - ); - } - - clazz = anyEndpoint.getClass(); - } - - if (clazz.equals(Integer.class)) { - return "int4range"; - } else if (clazz.equals(Long.class)) { - return "int8range"; - } else if (clazz.equals(BigDecimal.class)) { - return "numrange"; - } else if (clazz.equals(LocalDateTime.class)) { - return "tsrange"; - } else if (clazz.equals(ZonedDateTime.class) || clazz.equals(OffsetDateTime.class)) { - return "tstzrange"; - } else if (clazz.equals(LocalDate.class)) { - return "daterange"; - } - - throw new HibernateException( - new IllegalStateException("The class [" + clazz + "] is not supported!") - ); - } - - public static > Range ofString(String str, Function converter, Class clazz) { - if ("empty".equals(str)) { - if (clazz.equals(Integer.class)) { - return (Range) EMPTY_INT_RANGE; - } else if (clazz.equals(Long.class)) { - return (Range) EMPTY_LONG_RANGE; - } else if (clazz.equals(BigDecimal.class)) { - return (Range) EMPTY_BIGDECIMAL_RANGE; - } else if (clazz.equals(LocalDateTime.class)) { - return (Range) EMPTY_LOCALDATETIME_RANGE; - } else if (clazz.equals(ZonedDateTime.class)) { - return (Range) EMPTY_ZONEDDATETIME_RANGE; - } else if (clazz.equals(OffsetDateTime.class)) { - return (Range) EMPTY_OFFSETDATETIME_RANGE; - } else if (clazz.equals(LocalDate.class)) { - return (Range) EMPTY_DATE_RANGE; - } - - throw new HibernateException( - new IllegalStateException("The class [" + clazz.getName() + "] is not supported!") - ); - } - - BoundType lowerBound = str.charAt(0) == '[' ? BoundType.CLOSED : BoundType.OPEN; - BoundType upperBound = str.charAt(str.length() - 1) == ']' ? BoundType.CLOSED : BoundType.OPEN; - - int delim = str.indexOf(','); - - if (delim == -1) { - throw new HibernateException( - new IllegalArgumentException("Cannot find comma character") - ); - } - - String lowerStr = str.substring(1, delim); - String upperStr = str.substring(delim + 1, str.length() - 1); - - T lower = null; - T upper = null; - - if (lowerStr.length() > 0) { - lower = converter.apply(lowerStr); - } - - if (upperStr.length() > 0) { - upper = converter.apply(upperStr); - } - - if (lower == null && upper == null && upperBound == BoundType.OPEN && lowerBound == BoundType.OPEN) { - return Range.all(); - } - - if (lowerStr.length() == 0) { - return upperBound == BoundType.CLOSED ? - Range.atMost(upper) : - Range.lessThan(upper); - } else if (upperStr.length() == 0) { - return lowerBound == BoundType.CLOSED ? - Range.atLeast(lower) : - Range.greaterThan(lower); - } else { - return Range.range(lower, lowerBound, upper, upperBound); - } - } - - /** - * Creates the {@code BigDecimal} range from provided string: - *
{@code
-     *     Range closed = Range.bigDecimalRange("[0.1,1.1]");
-     *     Range halfOpen = Range.bigDecimalRange("(0.1,1.1]");
-     *     Range open = Range.bigDecimalRange("(0.1,1.1)");
-     *     Range leftUnbounded = Range.bigDecimalRange("(,1.1)");
-     * }
- * - * @param range The range string, for example {@literal "[5.5,7.8]"}. - * - * @return The range of {@code BigDecimal}s. - * - * @throws NumberFormatException when one of the bounds are invalid. - */ - public static Range bigDecimalRange(String range) { - return ofString(range, BigDecimal::new, BigDecimal.class); - } - - /** - * Creates the {@code Integer} range from provided string: - *
{@code
-     *     Range closed = Range.integerRange("[1,5]");
-     *     Range halfOpen = Range.integerRange("(-1,1]");
-     *     Range open = Range.integerRange("(1,2)");
-     *     Range leftUnbounded = Range.integerRange("(,10)");
-     *     Range unbounded = Range.integerRange("(,)");
-     * }
- * - * @param range The range string, for example {@literal "[5,7]"}. - * - * @return The range of {@code Integer}s. - * - * @throws NumberFormatException when one of the bounds are invalid. - */ - public static Range integerRange(String range) { - return ofString(range, Integer::parseInt, Integer.class); - } - - /** - * Creates the {@code Long} range from provided string: - *
{@code
-     *     Range closed = Range.longRange("[1,5]");
-     *     Range halfOpen = Range.longRange("(-1,1]");
-     *     Range open = Range.longRange("(1,2)");
-     *     Range leftUnbounded = Range.longRange("(,10)");
-     *     Range unbounded = Range.longRange("(,)");
-     * }
- * - * @param range The range string, for example {@literal "[5,7]"}. - * - * @return The range of {@code Long}s. - * - * @throws NumberFormatException when one of the bounds are invalid. - */ - public static Range longRange(String range) { - return ofString(range, Long::parseLong, Long.class); - } - - /** - * Creates the {@code LocalDateTime} range from provided string: - *
{@code
-     *     Range closed = Range.localDateTimeRange("[2014-04-28 16:00:49,2015-04-28 16:00:49]");
-     *     Range quoted = Range.localDateTimeRange("[\"2014-04-28 16:00:49\",\"2015-04-28 16:00:49\"]");
-     *     Range iso = Range.localDateTimeRange("[\"2014-04-28T16:00:49.2358\",\"2015-04-28T16:00:49\"]");
-     * }
- *

- * The valid formats for bounds are: - *

    - *
  • yyyy-MM-dd HH:mm:ss[.SSSSSS]
  • - *
  • yyyy-MM-dd'T'HH:mm:ss[.SSSSSS]
  • - *
- * - * @param range The range string, for example {@literal "[2014-04-28 16:00:49,2015-04-28 16:00:49]"}. - * - * @return The range of {@code LocalDateTime}s. - * - * @throws DateTimeParseException when one of the bounds are invalid. - */ - public static Range localDateTimeRange(String range) { - return ofString(range, parseLocalDateTime().compose(unquote()), LocalDateTime.class); - } - - /** - * Creates the {@code LocalDate} range from provided string: - *
{@code
-     *     Range closed = Range.localDateRange("[2014-04-28,2015-04-289]");
-     *     Range quoted = Range.localDateRange("[\"2014-04-28\",\"2015-04-28\"]");
-     *     Range iso = Range.localDateRange("[\"2014-04-28\",\"2015-04-28\"]");
-     * }
- *

- * The valid formats for bounds are: - *

    - *
  • yyyy-MM-dd
  • - *
  • yyyy-MM-dd
  • - *
- * - * @param range The range string, for example {@literal "[2014-04-28,2015-04-28]"}. - * - * @return The range of {@code LocalDate}s. - * - * @throws DateTimeParseException when one of the bounds are invalid. - */ - public static Range localDateRange(String range) { - Function parseLocalDate = LocalDate::parse; - return ofString(range, parseLocalDate.compose(unquote()), LocalDate.class); - } - - /** - * Creates the {@code ZonedDateTime} range from provided string: - *
{@code
-     *     Range closed = Range.zonedDateTimeRange("[2007-12-03T10:15:30+01:00\",\"2008-12-03T10:15:30+01:00]");
-     *     Range quoted = Range.zonedDateTimeRange("[\"2007-12-03T10:15:30+01:00\",\"2008-12-03T10:15:30+01:00\"]");
-     *     Range iso = Range.zonedDateTimeRange("[2011-12-03T10:15:30+01:00[Europe/Paris], 2012-12-03T10:15:30+01:00[Europe/Paris]]");
-     * }
- *

- * The valid formats for bounds are: - *

    - *
  • yyyy-MM-dd HH:mm:ss[.SSSSSS]X
  • - *
  • yyyy-MM-dd'T'HH:mm:ss[.SSSSSS]X
  • - *
- * - * @param rangeStr The range string, for example {@literal "[2011-12-03T10:15:30+01:00,2012-12-03T10:15:30+01:00]"}. - * - * @return The range of {@code ZonedDateTime}s. - * - * @throws DateTimeParseException when one of the bounds are invalid. - * @throws IllegalArgumentException when bounds time zones are different. - */ - public static Range zonedDateTimeRange(String rangeStr) { - Range range = ofString(rangeStr, parseZonedDateTime().compose(unquote()), ZonedDateTime.class); - if (range.hasLowerBound() && range.hasUpperBound()) { - ZoneId lowerZone = range.lowerEndpoint().getZone(); - ZoneId upperZone = range.upperEndpoint().getZone(); - if (!lowerZone.equals(upperZone)) { - Duration lowerDst = ZoneId.systemDefault().getRules().getDaylightSavings(range.lowerEndpoint().toInstant()); - Duration upperDst = ZoneId.systemDefault().getRules().getDaylightSavings(range.upperEndpoint().toInstant()); - long dstSeconds = upperDst.minus(lowerDst).getSeconds(); - if (dstSeconds < 0) { - dstSeconds *= -1; - } - long zoneDriftSeconds = ((ZoneOffset) lowerZone).getTotalSeconds() - ((ZoneOffset) upperZone).getTotalSeconds(); - if (zoneDriftSeconds < 0) { - zoneDriftSeconds *= -1; - } - - if (dstSeconds != zoneDriftSeconds) { - throw new HibernateException( - new IllegalArgumentException("The upper and lower bounds must be in same time zone!") - ); - } - } - } - return range; - } - - /** - * Creates the {@code OffsetDateTime} range from provided string: - *
{@code
-     *     Range closed = Range.offsetDateTimeRange("[2007-12-03T10:15:30+01:00\",\"2008-12-03T10:15:30+01:00]");
-     *     Range quoted = Range.offsetDateTimeRange("[\"2007-12-03T10:15:30+01:00\",\"2008-12-03T10:15:30+01:00\"]");
-     *     Range iso = Range.offsetDateTimeRange("[2011-12-03T10:15:30+01:00[Europe/Paris], 2012-12-03T10:15:30+01:00[Europe/Paris]]");
-     * }
- *

- * The valid formats for bounds are: - *

    - *
  • yyyy-MM-dd HH:mm:ss[.SSSSSS]X
  • - *
  • yyyy-MM-dd'T'HH:mm:ss[.SSSSSS]X
  • - *
- * - * @param rangeStr The range string, for example {@literal "[2011-12-03T10:15:30+01:00,2012-12-03T10:15:30+01:00]"}. - * - * @return The range of {@code OffsetDateTime}s. - * - * @throws DateTimeParseException when one of the bounds are invalid. - * @throws IllegalArgumentException when bounds time zones are different. - */ - public static Range offsetDateTimeRange(String rangeStr) { - return ofString(rangeStr, parseOffsetDateTime().compose(unquote()), OffsetDateTime.class); - } - - private static Function parseLocalDateTime() { - return str -> { - try { - return LocalDateTime.parse(str, LOCAL_DATE_TIME); - } catch (DateTimeParseException e) { - return LocalDateTime.parse(str); - } - }; - } - - private static Function parseZonedDateTime() { - return s -> { - try { - return ZonedDateTime.parse(s, OFFSET_DATE_TIME); - } catch (DateTimeParseException e) { - return ZonedDateTime.parse(s); - } - }; - } - - private static Function parseOffsetDateTime() { - return s -> { - try { - return OffsetDateTime.parse(s, OFFSET_DATE_TIME); - } catch (DateTimeParseException e) { - return OffsetDateTime.parse(s); - } - }; - } - - private static Function unquote() { - return s -> { - if (s.charAt(0) == '\"' && s.charAt(s.length() - 1) == '\"') { - return s.substring(1, s.length() - 1); - } - - return s; - }; - } - - public String asString(Range range) { - if (range.isEmpty()) { - return "empty"; - } - - StringBuilder sb = new StringBuilder(); - - sb.append(range.hasLowerBound() && range.lowerBoundType() == BoundType.CLOSED ? '[' : '(') - .append(range.hasLowerBound() ? asString(range.lowerEndpoint()) : "") - .append(",") - .append(range.hasUpperBound() ? asString(range.upperEndpoint()) : "") - .append(range.hasUpperBound() && range.upperBoundType() == BoundType.CLOSED ? ']' : ')'); - - return sb.toString(); - } - - private String asString(Object value) { - if (value instanceof ZonedDateTime) { - return OFFSET_DATE_TIME.format((ZonedDateTime) value); - } - return value.toString(); - } - - @Override - public void setParameterValues(Properties parameters) { - final XProperty xProperty = (XProperty) parameters.get(DynamicParameterizedType.XPROPERTY); - if (xProperty instanceof JavaXMember) { - type = ((JavaXMember) xProperty).getJavaType(); - } else { - type = ((ParameterType) parameters.get(PARAMETER_TYPE)).getReturnedClass(); - } - - if (type instanceof ParameterizedType) { - elementType = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; - } - } - - public Class getElementType() { - return elementType; - } - -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/PostgreSQLTSVectorType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/PostgreSQLTSVectorType.java deleted file mode 100644 index aa916a54a..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/PostgreSQLTSVectorType.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.hypersistence.utils.hibernate.type.search; - -import io.hypersistence.utils.hibernate.type.search.internal.PostgreSQLTSVectorSqlTypeDescriptor; -import io.hypersistence.utils.hibernate.type.search.internal.PostgreSQLTSVectorTypeDescriptor; -import org.hibernate.type.AbstractSingleColumnStandardBasicType; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.util.Properties; - -/** - * Maps a {@link String} object type to a PostgreSQL TSVector column type. - * - * @author Vlad Mihalcea - * @author Philip Riecks - */ -public class PostgreSQLTSVectorType - extends AbstractSingleColumnStandardBasicType implements DynamicParameterizedType { - - public static final PostgreSQLTSVectorType INSTANCE = new PostgreSQLTSVectorType(); - - - public PostgreSQLTSVectorType() { - super(PostgreSQLTSVectorSqlTypeDescriptor.INSTANCE, new PostgreSQLTSVectorTypeDescriptor()); - } - - @Override - public String getName() { - return "tsvector"; - } - - @Override - public void setParameterValues(Properties parameters) { - ((PostgreSQLTSVectorTypeDescriptor) getJavaTypeDescriptor()).setParameterValues(parameters); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/internal/PostgreSQLTSVectorSqlTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/internal/PostgreSQLTSVectorSqlTypeDescriptor.java deleted file mode 100644 index dfe6858ec..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/internal/PostgreSQLTSVectorSqlTypeDescriptor.java +++ /dev/null @@ -1,70 +0,0 @@ -package io.hypersistence.utils.hibernate.type.search.internal; - -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import org.hibernate.type.descriptor.ValueBinder; -import org.hibernate.type.descriptor.ValueExtractor; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.JavaTypeDescriptor; -import org.hibernate.type.descriptor.sql.BasicBinder; -import org.hibernate.type.descriptor.sql.BasicExtractor; -import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; - -import java.sql.*; - -public class PostgreSQLTSVectorSqlTypeDescriptor implements SqlTypeDescriptor { - - public static final PostgreSQLTSVectorSqlTypeDescriptor INSTANCE = new PostgreSQLTSVectorSqlTypeDescriptor(); - - @Override - public int getSqlType() { - return Types.OTHER; - } - - @Override - public boolean canBeRemapped() { - return false; - } - - @Override - public ValueBinder getBinder(final JavaTypeDescriptor javaTypeDescriptor) { - return new BasicBinder(javaTypeDescriptor, this) { - @Override - protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { - Object holder = ReflectionUtils.newInstance("org.postgresql.util.PGobject"); - ReflectionUtils.invokeSetter(holder, "type", "tsvector"); - ReflectionUtils.invokeSetter(holder, "value", javaTypeDescriptor.unwrap(value, String.class, options)); - st.setObject(index, holder); - } - - @Override - protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) - throws SQLException { - Object holder = ReflectionUtils.newInstance("org.postgresql.util.PGobject"); - ReflectionUtils.invokeSetter(holder, "type", "tsvector"); - ReflectionUtils.invokeSetter(holder, "value", javaTypeDescriptor.unwrap(value, String.class, options)); - - st.setObject(name, holder); - } - }; - } - - @Override - public ValueExtractor getExtractor(final JavaTypeDescriptor javaTypeDescriptor) { - return new BasicExtractor(javaTypeDescriptor, this) { - @Override - protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException { - return javaTypeDescriptor.wrap(rs.getString( name ), options); - } - - @Override - protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException { - return javaTypeDescriptor.wrap(statement.getString(index), options); - } - - @Override - protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException { - return javaTypeDescriptor.wrap(statement.getString(name), options); - } - }; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/internal/PostgreSQLTSVectorTypeDescriptor.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/internal/PostgreSQLTSVectorTypeDescriptor.java deleted file mode 100644 index 2b3621644..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/search/internal/PostgreSQLTSVectorTypeDescriptor.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.hypersistence.utils.hibernate.type.search.internal; - -import org.hibernate.annotations.common.reflection.XProperty; -import org.hibernate.annotations.common.reflection.java.JavaXMember; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; -import org.hibernate.usertype.DynamicParameterizedType; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.util.Properties; - -public class PostgreSQLTSVectorTypeDescriptor extends AbstractTypeDescriptor implements DynamicParameterizedType { - - public PostgreSQLTSVectorTypeDescriptor() { - super(Object.class); - } - - private Type type; - - @Override - public void setParameterValues(Properties parameters) { - final XProperty xProperty = (XProperty) parameters.get(DynamicParameterizedType.XPROPERTY); - if (xProperty instanceof JavaXMember) { - type = ((JavaXMember) xProperty).getJavaType(); - } else { - type = ((ParameterType) parameters.get(PARAMETER_TYPE)).getReturnedClass(); - } - } - - @Override - public boolean areEqual(Object one, Object another) { - if (one == another) { - return true; - } - if (one == null || another == null) { - return false; - } - if (one instanceof String && another instanceof String) { - return one.equals(another); - } - return one.equals(another); - } - - @Override - public String toString(Object value) { - return value.toString(); - } - - @Override - public Object fromString(String string) { - if (String.class.isAssignableFrom(typeToClass())) { - return string; - } - return string; - } - - @SuppressWarnings({"unchecked"}) - @Override - public X unwrap(Object value, Class type, WrapperOptions options) { - if (value == null) { - return null; - } - if (String.class.isAssignableFrom(type)) { - return (X) toString(value); - } - throw unknownUnwrap(type); - } - - @Override - public Object wrap(X value, WrapperOptions options) { - if (value == null) { - return null; - } - return fromString(value.toString()); - } - - private Class typeToClass() { - Type classType = type; - if (type instanceof ParameterizedType) { - classType = ((ParameterizedType) type).getRawType(); - } else if (type instanceof TypeVariable) { - classType = ((TypeVariable) type).getGenericDeclaration().getClass(); - } - return (Class) classType; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ClassImportIntegrator.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ClassImportIntegrator.java deleted file mode 100644 index b0e16e841..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ClassImportIntegrator.java +++ /dev/null @@ -1,89 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import org.hibernate.boot.Metadata; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.integrator.spi.Integrator; -import org.hibernate.service.spi.SessionFactoryServiceRegistry; - -import java.util.List; - -/** - * The {@link ClassImportIntegrator} implements the Hibernate {@link Integrator} contract - * and allows you to provide a {@link List} of classes to be imported using their simple name. - * - * For instance, you could use a DTO simple class name, instead of the fully-qualified name - * when building a constructor expression in a JPQL query. - * - * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - */ -public class ClassImportIntegrator implements Integrator { - - private static final String DOT = "."; - - private final List classImportList; - - private String excludedPath; - - /** - * Builds a new integrator that can register the provided classes. - * - * @param classImportList list of classes to be imported - */ - public ClassImportIntegrator(List classImportList) { - this.classImportList = classImportList; - } - - /** - * Exclude the provided parent path and register the remaining relative path. - * If the {@link #excludedPath} is not set, then the package is excluded and - * only the simple class name is registered. - * - * For instance, if you provide the {@code io.hypersistence.utils.hibernate.type} path, - * and register a class whose fully-qualified name is {@code io.hypersistence.utils.hibernate.type.json.PostDTO}, - * then the class is going to be registered under the {@code json.PostDTO} alias. - * - * @param path path to be excluded. - * @return the {@link ClassImportIntegrator} object reference - */ - public ClassImportIntegrator excludePath(String path) { - this.excludedPath = path.endsWith(DOT) ? path : path + DOT; - return this; - } - - /** - * Register the provided classes by their simple name or relative package and class name. - * - * @param metadata metadata - * @param sessionFactory Hibernate session factory - * @param serviceRegistry Hibernate service registry - */ - @Override - public void integrate( - Metadata metadata, - SessionFactoryImplementor sessionFactory, - SessionFactoryServiceRegistry serviceRegistry) { - for(Class classImport : classImportList) { - String key; - if(excludedPath != null) { - key = classImport.getName().replace(excludedPath, ""); - } else { - key = classImport.getSimpleName(); - } - - metadata.getImports().put( - key, - classImport.getName() - ); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void disintegrate( - SessionFactoryImplementor sessionFactory, - SessionFactoryServiceRegistry serviceRegistry) {} -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/Configuration.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/Configuration.java deleted file mode 100644 index 3431f7fa2..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/Configuration.java +++ /dev/null @@ -1,270 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import io.hypersistence.utils.hibernate.util.ClassLoaderUtils; -import org.hibernate.cfg.Environment; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Properties; - -import static io.hypersistence.utils.hibernate.util.LogUtils.LOGGER; - -/** - * Configuration - It allows you to configure various Hibernate Types. - * - * @author Vlad Mihalcea - * @since 2.1.0 - */ -public class Configuration implements Serializable { - - public static final Configuration INSTANCE = new Configuration(); - - @Deprecated - public static final String DEPRECATED_PROPERTIES_FILE_PATH = "hibernate-types.properties.path"; - @Deprecated - public static final String DEPRECATED_PROPERTIES_FILE_NAME = "hibernate-types.properties"; - - public static final String PROPERTIES_FILE_PATH = "hypersistence-utils.properties.path"; - public static final String PROPERTIES_FILE_NAME = "hypersistence-utils.properties"; - public static final String APPLICATION_PROPERTIES_FILE_NAME = "application.properties"; - - /** - * Each Property has a well-defined key. - */ - public enum PropertyKey { - JACKSON_OBJECT_MAPPER( - "hypersistence.utils.jackson.object.mapper", - "hibernate.types.jackson.object.mapper" - ), - JSON_SERIALIZER( - "hypersistence.utils.json.serializer", - "hibernate.types.json.serializer" - ), - PRINT_BANNER( - "hypersistence.utils.print.banner", - "hibernate.types.print.banner" - ); - - private final String key; - @Deprecated - private final String deprecatedKey; - - PropertyKey(String key, String deprecatedKey) { - this.key = key; - this.deprecatedKey = deprecatedKey; - } - - public String resolve(Properties properties) { - String value = properties.getProperty(key); - if(value == null) { - value = properties.getProperty(deprecatedKey); - if(value != null) { - LOGGER.warn( - "The [{}] configuration property is deprecated. Use [{}] instead.", - deprecatedKey, - key - ); - } - } - return value; - } - } - - private final Properties properties = Environment.getProperties(); - - protected Configuration() { - load(); - } - - /** - * Load {@link Properties} from the resolved {@link InputStream} - */ - private void load() { - String customPropertiesFilePath = System.getProperty(DEPRECATED_PROPERTIES_FILE_PATH); - if(customPropertiesFilePath != null) { - LOGGER.warn( - "The [{}] System property is deprecated. Use [{}] instead.", - DEPRECATED_PROPERTIES_FILE_PATH, - PROPERTIES_FILE_PATH - ); - } else { - customPropertiesFilePath = System.getProperty(PROPERTIES_FILE_PATH); - } - - String[] propertiesFilePaths = new String[] { - APPLICATION_PROPERTIES_FILE_NAME, - DEPRECATED_PROPERTIES_FILE_NAME, - PROPERTIES_FILE_NAME, - customPropertiesFilePath - }; - - for (String propertiesFilePath : propertiesFilePaths) { - if (propertiesFilePath != null) { - InputStream propertiesInputStream = null; - try { - propertiesInputStream = propertiesInputStream(propertiesFilePath); - if (propertiesInputStream != null) { - properties.load(propertiesInputStream); - - if(DEPRECATED_PROPERTIES_FILE_NAME.equals(propertiesFilePath)) { - LOGGER.warn( - "The [{}] property file is deprecated. Use [{}] instead.", - DEPRECATED_PROPERTIES_FILE_NAME, - PROPERTIES_FILE_NAME - ); - } - } - } catch (IOException e) { - LOGGER.error("Can't load properties", e); - } finally { - try { - if (propertiesInputStream != null) { - propertiesInputStream.close(); - } - } catch (IOException e) { - LOGGER.error("Can't close the properties InputStream", e); - } - } - } - } - } - - /** - * Get {@link Properties} file {@link InputStream} - * - * @param propertiesFilePath properties file path - * @return {@link Properties} file {@link InputStream} - * @throws IOException the file couldn't be loaded properly - */ - private InputStream propertiesInputStream(String propertiesFilePath) throws IOException { - if (propertiesFilePath != null) { - URL propertiesFileUrl; - try { - propertiesFileUrl = new URL(propertiesFilePath); - } catch (MalformedURLException ignore) { - propertiesFileUrl = ClassLoaderUtils.getResource(propertiesFilePath); - if (propertiesFileUrl == null) { - File f = new File(propertiesFilePath); - if (f.exists() && f.isFile()) { - try { - propertiesFileUrl = f.toURI().toURL(); - } catch (MalformedURLException e) { - LOGGER.error( - "The property " + propertiesFilePath + " can't be resolved to either a URL, " + - "a classpath resource or a File" - ); - } - } - } - } - if (propertiesFileUrl != null) { - return propertiesFileUrl.openStream(); - } - } - return ClassLoaderUtils.getResourceAsStream(propertiesFilePath); - } - - /** - * Get all properties. - * - * @return properties. - */ - public Properties getProperties() { - return properties; - } - - /** - * Get Integer property value - * - * @param propertyKey property key - * @return Integer property value - */ - public Integer integerProperty(PropertyKey propertyKey) { - Integer value = null; - String property = propertyKey.resolve(properties); - if (property != null) { - value = Integer.valueOf(property); - } - return value; - } - - /** - * Get Long property value - * - * @param propertyKey property key - * @return Long property value - */ - public Long longProperty(PropertyKey propertyKey) { - Long value = null; - String property = propertyKey.resolve(properties); - if (property != null) { - value = Long.valueOf(property); - } - return value; - } - - /** - * Get Boolean property value - * - * @param propertyKey property key - * @return Boolean property value - */ - public Boolean booleanProperty(PropertyKey propertyKey) { - Boolean value = null; - String property = propertyKey.resolve(properties); - if (property != null) { - value = Boolean.valueOf(property); - } - return value; - } - - /** - * Get Class property value - * - * @param propertyKey property key - * @param class generic type - * @return Class property value - */ - public Class classProperty(PropertyKey propertyKey) { - Class clazz = null; - String property = propertyKey.resolve(properties); - if (property != null) { - try { - return ClassLoaderUtils.loadClass(property); - } catch (ClassNotFoundException e) { - LOGGER.error("Couldn't load the " + property + " class given by the " + propertyKey + " property", e); - } - } - return clazz; - } - - /** - * Instantiate class associated to the given property key - * - * @param propertyKey property key - * @param class parameter type - * @return class instance - */ - protected T instantiateClass(PropertyKey propertyKey) { - T object = null; - String property = propertyKey.resolve(properties); - if (property != null) { - try { - Class clazz = ClassLoaderUtils.loadClass(property); - LOGGER.debug("Instantiate {}", clazz); - object = clazz.newInstance(); - } catch (ClassNotFoundException e) { - LOGGER.error("Couldn't load the " + property + " class given by the " + propertyKey + " property", e); - } catch (InstantiationException e) { - LOGGER.error("Couldn't instantiate the " + property + " class given by the " + propertyKey + " property", e); - } catch (IllegalAccessException e) { - LOGGER.error("Couldn't access the " + property + " class given by the " + propertyKey + " property", e); - } - } - return object; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonConfiguration.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonConfiguration.java deleted file mode 100644 index 461d2cd6a..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonConfiguration.java +++ /dev/null @@ -1,73 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.util.function.Supplier; - -/** - * JsonConfiguration - It allows you to configure various JSON Hibernate Types.. - * - * @author Vlad Mihalcea - * @since 3.3.0 - */ -public class JsonConfiguration extends Configuration { - - public static final JsonConfiguration INSTANCE = new JsonConfiguration(); - - private final ObjectMapperWrapper objectMapperWrapper; - - public JsonConfiguration() { - super(); - - Object objectMapperPropertyInstance = instantiateClass(PropertyKey.JACKSON_OBJECT_MAPPER); - - ObjectMapperWrapper objectMapperWrapper = null; - - if (objectMapperPropertyInstance != null) { - if (objectMapperPropertyInstance instanceof ObjectMapperSupplier) { - ObjectMapperSupplier objectMapperSupplier = (ObjectMapperSupplier) objectMapperPropertyInstance; - objectMapperWrapper = new ObjectMapperWrapper(objectMapperSupplier); - } else if (objectMapperPropertyInstance instanceof Supplier) { - Supplier objectMapperSupplier = (Supplier) objectMapperPropertyInstance; - objectMapperWrapper = new ObjectMapperWrapper((ObjectMapperSupplier) () -> objectMapperSupplier.get()); - } else if (objectMapperPropertyInstance instanceof ObjectMapper) { - ObjectMapper objectMapper = (ObjectMapper) objectMapperPropertyInstance; - objectMapperWrapper = new ObjectMapperWrapper(objectMapper); - } - } - - if(objectMapperWrapper == null) { - objectMapperWrapper = new ObjectMapperWrapper(); - } - - Object jsonSerializerPropertyInstance = instantiateClass(PropertyKey.JSON_SERIALIZER); - - if (jsonSerializerPropertyInstance != null) { - JsonSerializer jsonSerializer = null; - - if (jsonSerializerPropertyInstance instanceof JsonSerializerSupplier) { - jsonSerializer = ((JsonSerializerSupplier) jsonSerializerPropertyInstance).get(); - } else if (jsonSerializerPropertyInstance instanceof Supplier) { - Supplier jsonSerializerSupplier = (Supplier) jsonSerializerPropertyInstance; - jsonSerializer = jsonSerializerSupplier.get(); - } else if (jsonSerializerPropertyInstance instanceof JsonSerializer) { - jsonSerializer = (JsonSerializer) jsonSerializerPropertyInstance; - } - - if (jsonSerializer != null) { - objectMapperWrapper.setJsonSerializer(jsonSerializer); - } - } - - this.objectMapperWrapper = objectMapperWrapper; - } - - /** - * Get {@link ObjectMapperWrapper} reference - * - * @return {@link ObjectMapperWrapper} reference - */ - public ObjectMapperWrapper getObjectMapperWrapper() { - return objectMapperWrapper; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonSerializer.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonSerializer.java deleted file mode 100644 index 0c58487d5..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonSerializer.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import java.io.Serializable; - -/** - * Contract for serializing JSON objects. - * - * @author Vlad Mihalcea - */ -public interface JsonSerializer extends Serializable { - - /** - * Clone JSON object. - * - * @param jsonObject JSON object - * @param JSON object parameterized type - * @return cloned JSON object - */ - T clone(T jsonObject); -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonSerializerSupplier.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonSerializerSupplier.java deleted file mode 100644 index 75287b69f..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/JsonSerializerSupplier.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import java.io.Serializable; - -/** - * Supplies a custom reference of a Jackson {@link JsonSerializer} - * - * @author Vlad Mihalcea - * @since 2.1.0 - */ -public interface JsonSerializerSupplier extends Serializable { - - /** - * Get custom {@link JsonSerializer} reference - * - * @return custom {@link JsonSerializer} reference - */ - JsonSerializer get(); -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperJsonSerializer.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperJsonSerializer.java deleted file mode 100644 index fbc895fb2..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperJsonSerializer.java +++ /dev/null @@ -1,81 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.type.TypeFactory; -import org.hibernate.internal.util.SerializationHelper; -import org.hibernate.type.SerializationException; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Map; - -/** - * @author Vlad Mihalcea - */ -public class ObjectMapperJsonSerializer implements JsonSerializer { - - private final ObjectMapperWrapper objectMapperWrapper; - - public ObjectMapperJsonSerializer(ObjectMapperWrapper objectMapperWrapper) { - this.objectMapperWrapper = objectMapperWrapper; - } - - @Override - public T clone(T object) { - if (object instanceof String) { - return object; - } else if (object instanceof Collection) { - Object firstElement = findFirstNonNullElement((Collection) object); - if (firstElement != null && !(firstElement instanceof Serializable)) { - JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), firstElement.getClass()); - return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type); - } - } else if (object instanceof Map) { - Map.Entry firstEntry = this.findFirstNonNullEntry((Map) object); - if (firstEntry != null) { - Object key = firstEntry.getKey(); - Object value = firstEntry.getValue(); - if (!(key instanceof Serializable) || !(value instanceof Serializable)) { - JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), key.getClass(), value.getClass()); - return (T) objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type); - } - } - } else if (object instanceof JsonNode) { - return (T) ((JsonNode) object).deepCopy(); - } - - if (object instanceof Serializable) { - try { - return (T) SerializationHelper.clone((Serializable) object); - } catch (SerializationException e) { - //it is possible that object itself implements java.io.Serializable, but underlying structure does not - //in this case we switch to the other JSON marshaling strategy which doesn't use the Java serialization - } - } - - return jsonClone(object); - } - - private Object findFirstNonNullElement(Collection collection) { - for (java.lang.Object element : collection) { - if (element != null) { - return element; - } - } - return null; - } - - private Map.Entry findFirstNonNullEntry(Map map) { - for (Map.Entry entry : map.entrySet()) { - if (entry.getKey() != null && entry.getValue() != null) { - return entry; - } - } - return null; - } - - private T jsonClone(T object) { - return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), (Class) object.getClass()); - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperSupplier.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperSupplier.java deleted file mode 100644 index 28e804a53..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperSupplier.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.Serializable; - -/** - * Supplies a custom reference of a Jackson {@link ObjectMapper} - * - * @author Vlad Mihalcea - * @since 2.1.0 - */ -public interface ObjectMapperSupplier extends Serializable { - - /** - * Get custom {@link ObjectMapper} reference - * - * @return custom {@link ObjectMapper} reference - */ - ObjectMapper get(); -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperWrapper.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperWrapper.java deleted file mode 100644 index 0a22657dc..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperWrapper.java +++ /dev/null @@ -1,189 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.databind.module.SimpleModule; -import org.hibernate.HibernateException; - -import java.io.IOException; -import java.io.Serializable; -import java.lang.reflect.Type; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.format.DateTimeParseException; -import java.util.Date; - -import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME; - -/** - * Wraps a Jackson {@link ObjectMapper} so that you can supply your own {@link ObjectMapper} reference. - * - * @author Vlad Mihalcea - * @since 2.1.0 - */ -public class ObjectMapperWrapper implements Serializable { - - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper() - .findAndRegisterModules() - .registerModule( - new SimpleModule() - .addSerializer(OffsetDateTime.class, OffsetDateTimeSerializer.INSTANCE) - .addDeserializer(OffsetDateTime.class, OffsetDateTimeDeserializer.INSTANCE) - ); - - public static final ObjectMapperWrapper INSTANCE = new ObjectMapperWrapper(); - - private ObjectMapper objectMapper; - - private ObjectMapperSupplier objectMapperSupplier; - - private JsonSerializer jsonSerializer = new ObjectMapperJsonSerializer(this); - - public ObjectMapperWrapper() { - this(OBJECT_MAPPER); - } - - public ObjectMapperWrapper(ObjectMapperSupplier objectMapperSupplier) { - this.objectMapperSupplier = objectMapperSupplier; - } - - public ObjectMapperWrapper(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } - - public void setJsonSerializer(JsonSerializer jsonSerializer) { - this.jsonSerializer = jsonSerializer; - } - - public ObjectMapper getObjectMapper() { - if(objectMapper == null && objectMapperSupplier != null) { - objectMapper = objectMapperSupplier.get(); - } - if(objectMapper == null) { - throw new HibernateException("The provided ObjectMapper is null!"); - } - return objectMapper; - } - - public void setObjectMapper(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } - - public T fromString(String string, Class clazz) { - try { - return getObjectMapper().readValue(string, clazz); - } catch (IOException e) { - throw new HibernateException( - new IllegalArgumentException("The given string value: " + string + " cannot be transformed to Json object", e) - ); - } - } - - public T fromString(String string, Type type) { - try { - return getObjectMapper().readValue(string, getObjectMapper().getTypeFactory().constructType(type)); - } catch (IOException e) { - throw new HibernateException( - new IllegalArgumentException("The given string value: " + string + " cannot be transformed to Json object", e) - ); - } - } - - public T fromBytes(byte[] value, Class clazz) { - try { - return getObjectMapper().readValue(value, clazz); - } catch (IOException e) { - throw new HibernateException( - new IllegalArgumentException("The given byte array cannot be transformed to Json object", e) - ); - } - } - - public T fromBytes(byte[] value, Type type) { - try { - return getObjectMapper().readValue(value, getObjectMapper().getTypeFactory().constructType(type)); - } catch (IOException e) { - throw new HibernateException( - new IllegalArgumentException("The given byte array cannot be transformed to Json object", e) - ); - } - } - - public String toString(Object value) { - try { - return getObjectMapper().writeValueAsString(value); - } catch (JsonProcessingException e) { - throw new HibernateException( - new IllegalArgumentException("The given Json object value: " + value + " cannot be transformed to a String", e) - ); - } - } - - public byte[] toBytes(Object value) { - try { - return getObjectMapper().writeValueAsBytes(value); - } catch (JsonProcessingException e) { - throw new HibernateException( - new IllegalArgumentException("The given Json object value: " + value + " cannot be transformed to a byte array", e) - ); - } - } - - public JsonNode toJsonNode(String value) { - try { - return getObjectMapper().readTree(value); - } catch (IOException e) { - throw new HibernateException( - new IllegalArgumentException(e) - ); - } - } - - public T clone(T value) { - return jsonSerializer.clone(value); - } - - public static class OffsetDateTimeSerializer extends com.fasterxml.jackson.databind.JsonSerializer { - - public static final OffsetDateTimeSerializer INSTANCE = new OffsetDateTimeSerializer(); - - @Override - public void serialize(OffsetDateTime offsetDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { - if (offsetDateTime == null) { - jsonGenerator.writeNull(); - } else { - jsonGenerator.writeString(offsetDateTime.format(ISO_OFFSET_DATE_TIME)); - } - } - - @Override - public Class handledType() { - return OffsetDateTime.class; - } - } - - public static class OffsetDateTimeDeserializer extends JsonDeserializer { - - public static final OffsetDateTimeDeserializer INSTANCE = new OffsetDateTimeDeserializer(); - - @Override - public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { - if (jsonParser.getText() != null) { - try { - return OffsetDateTime.parse(jsonParser.getText(), ISO_OFFSET_DATE_TIME); - } catch (DateTimeParseException e) { - Date date = new Date((long) jsonParser.getDoubleValue() * 1000); - return date.toInstant().atOffset(ZoneOffset.UTC); - } - } - return null; - } - - @Override - public Class handledType() { - return OffsetDateTime.class; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ParameterTypeUtils.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ParameterTypeUtils.java deleted file mode 100644 index 165107004..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ParameterTypeUtils.java +++ /dev/null @@ -1,103 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import io.hypersistence.utils.hibernate.util.StringUtils; -import org.hibernate.usertype.DynamicParameterizedType; - -import javax.persistence.Column; -import java.lang.annotation.Annotation; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -/** - * ParameterizedTypeUtils - {@link DynamicParameterizedType.ParameterType} utilities holder. - * - * @author Vlad Mihalcea - * @since 2.16.0 - */ -public class ParameterTypeUtils { - - private static final Pattern COLUMN_TYPE_PATTERN = Pattern.compile("([a-zA-Z0-9]+).*?"); - - private ParameterTypeUtils() { - throw new UnsupportedOperationException("StringUtils is not instantiable!"); - } - - /** - * Resolve the {@link DynamicParameterizedType.ParameterType} instance - * from the provided {@link Properties} object. - * - * @param properties configuration properties - * @return {@link DynamicParameterizedType.ParameterType} instance - */ - public static DynamicParameterizedType.ParameterType resolve(Properties properties) { - Object parameterTypeObject = properties.get(DynamicParameterizedType.PARAMETER_TYPE); - if (parameterTypeObject instanceof DynamicParameterizedType.ParameterType) { - return (DynamicParameterizedType.ParameterType) parameterTypeObject; - } - return null; - } - - /** - * Get the required annotation from the {@link DynamicParameterizedType.ParameterType} instance. - * - * @param parameterType {@link DynamicParameterizedType.ParameterType} instance - * @param annotationClass annotation class - * @return annotation - */ - @SuppressWarnings("unchecked") - public static A getAnnotationOrNull(DynamicParameterizedType.ParameterType parameterType, Class annotationClass) { - List annotations = getAnnotations(parameterType, annotationClass); - int annotationCount = annotations.size(); - if(annotationCount > 1) { - throw new IllegalArgumentException( - String.format( - "The provided ParameterType associated with the [%s] property contains more than one annotation of the [%s] type!", - parameterType.getReturnedClass(), - annotationClass.getName() - ) - ); - } - return annotationCount == 1 ? annotations.get(0) : null; - } - - /** - * Get the required annotations from the {@link DynamicParameterizedType.ParameterType} instance. - * - * @param parameterType {@link DynamicParameterizedType.ParameterType} instance - * @param annotationClass annotation class - * @return annotations - */ - @SuppressWarnings("unchecked") - public static List getAnnotations(DynamicParameterizedType.ParameterType parameterType, Class annotationClass) { - return Arrays.stream(parameterType.getAnnotationsMethod()) - .filter(a -> annotationClass.isAssignableFrom(a.annotationType())) - .map(a -> (A) a) - .collect(Collectors.toList()); - } - - /** - * Get the column type association from the {@link DynamicParameterizedType.ParameterType} instance. - * - * @param parameterType {@link DynamicParameterizedType.ParameterType} instance - * @return column type - */ - public static String getColumnType(DynamicParameterizedType.ParameterType parameterType) { - if (parameterType != null) { - Column columnAnnotation = ParameterTypeUtils.getAnnotationOrNull(parameterType, Column.class); - if(columnAnnotation != null) { - String columnDefinition = columnAnnotation.columnDefinition(); - if(!StringUtils.isBlank(columnDefinition)) { - Matcher matcher = COLUMN_TYPE_PATTERN.matcher(columnDefinition); - if (matcher.matches()) { - return StringUtils.toLowercase(matcher.group(1)); - } - } - } - } - return null; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ParameterizedParameterType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ParameterizedParameterType.java deleted file mode 100644 index cf559565c..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/type/util/ParameterizedParameterType.java +++ /dev/null @@ -1,55 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import org.hibernate.usertype.DynamicParameterizedType; - -import java.lang.annotation.Annotation; - -/** - * A stub {@code ParameterType} that returns sane values for {@link #getReturnedClass()} and - * {@link #getAnnotationsMethod()}. - * - * @author Jan-Willem Gmelig Meyling - */ -public class ParameterizedParameterType implements DynamicParameterizedType.ParameterType { - - private final Class clasz; - - public ParameterizedParameterType(Class clasz) { - this.clasz = clasz; - } - - @Override - public Class getReturnedClass() { - return clasz; - } - - @Override - public Annotation[] getAnnotationsMethod() { - return new Annotation[0]; - } - - @Override - public String getCatalog() { - throw new UnsupportedOperationException(); - } - - @Override - public String getSchema() { - throw new UnsupportedOperationException(); - } - - @Override - public String getTable() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isPrimaryKey() { - throw new UnsupportedOperationException(); - } - - @Override - public String[] getColumns() { - throw new UnsupportedOperationException(); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/ClassLoaderUtils.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/ClassLoaderUtils.java deleted file mode 100644 index ad29a6de3..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/ClassLoaderUtils.java +++ /dev/null @@ -1,77 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import java.io.InputStream; -import java.net.URL; - -/** - * ClassLoaderUtils - Class loading related utilities holder. - * - * @author Vlad Mihalcea - * @since 2.1.0 - */ -public final class ClassLoaderUtils { - - private ClassLoaderUtils() { - throw new UnsupportedOperationException("ClassLoaderUtils is not instantiable!"); - } - - /** - * Load the available ClassLoader - * - * @return ClassLoader - */ - public static ClassLoader getClassLoader() { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - return (classLoader != null) ? classLoader : ClassLoaderUtils.class.getClassLoader(); - } - - /** - * Load the Class denoted by the given string representation - * - * @param className class string representation - * @param class generic type - * @return Class - * @throws ClassNotFoundException if the class cannot be resolved - */ - @SuppressWarnings("unchecked") - public static Class loadClass(String className) throws ClassNotFoundException { - return (Class) getClassLoader().loadClass(className); - } - - /** - * Find if Class denoted by the given string representation is loadable - * - * @param className class string representation - * @return Class - */ - @SuppressWarnings("unchecked") - public static boolean findClass(String className) { - try { - return getClassLoader().loadClass(className) != null; - } catch (ClassNotFoundException e) { - return false; - } catch (NoClassDefFoundError e) { - return false; - } - } - - /** - * Get the resource URL - * - * @param resourceName resource name - * @return resource URL - */ - public static URL getResource(String resourceName) { - return getClassLoader().getResource(resourceName); - } - - /** - * Get the resource InputStream - * - * @param resourceName resource name - * @return resource InputStream - */ - public static InputStream getResourceAsStream(String resourceName) { - return getClassLoader().getResourceAsStream(resourceName); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/LogUtils.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/LogUtils.java deleted file mode 100644 index 49c9cbc19..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/LogUtils.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The {@link LogUtils} class unifies the framework logging capabilities. - * - * @author Vlad Mihalcea - * @since 2.9.5 - */ -public class LogUtils { - - public static final Logger LOGGER = LoggerFactory.getLogger("Hibernate Types"); -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/ReflectionUtils.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/ReflectionUtils.java deleted file mode 100644 index 6ef761f12..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/ReflectionUtils.java +++ /dev/null @@ -1,677 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import java.lang.reflect.*; -import java.util.LinkedHashSet; -import java.util.Set; - -/** - * ReflectionUtils - Reflection utilities holder. - * - * @author Vlad Mihalcea - * @since 1.0 - */ -public final class ReflectionUtils { - - private static final String GETTER_PREFIX = "get"; - - private static final String SETTER_PREFIX = "set"; - - /** - * Prevent any instantiation. - */ - private ReflectionUtils() { - throw new UnsupportedOperationException("The " + getClass() + " is not instantiable!"); - } - - /** - * Instantiate a new {@link Object} of the provided type. - * - * @param className The fully-qualified Java class name of the {@link Object} to instantiate - * @param class type - * @return new Java {@link Object} of the provided type - */ - public static T newInstance(String className) { - Class clazz = getClass(className); - return newInstance(clazz); - } - - /** - * Instantiate a new {@link Object} of the provided type. - * - * @param clazz The Java {@link Class} of the {@link Object} to instantiate - * @param class type - * @return new Java {@link Object} of the provided type - */ - @SuppressWarnings("unchecked") - public static T newInstance(Class clazz) { - try { - return (T) clazz.newInstance(); - } catch (InstantiationException e) { - throw handleException(e); - } catch (IllegalAccessException e) { - throw handleException(e); - } - } - - /** - * Instantiate a new {@link Object} of the provided type. - * - * @param clazz The Java {@link Class} of the {@link Object} to instantiate - * @param args The arguments that need to be passed to the constructor - * @param argsTypes The argument types that need to be passed to the constructor - * @param class type - * @return new Java {@link Object} of the provided type - */ - @SuppressWarnings("unchecked") - public static T newInstance(Class clazz, Object[] args, Class[] argsTypes) { - try { - Constructor constructor = clazz.getDeclaredConstructor(argsTypes); - constructor.setAccessible(true); - return constructor.newInstance(args); - } catch (InstantiationException e) { - throw handleException(e); - } catch (IllegalAccessException e) { - throw handleException(e); - } catch (NoSuchMethodException e) { - throw handleException(e); - } catch (InvocationTargetException e) { - throw handleException(e); - } - } - - /** - * Get the {@link Field} with the given name belonging to the provided Java {@link Class}. - * - * @param targetClass the provided Java {@link Class} the field belongs to - * @param fieldName the {@link Field} name - * @return the {@link Field} matching the given name - */ - public static Field getField(Class targetClass, String fieldName) { - Field field = null; - - try { - field = targetClass.getDeclaredField(fieldName); - } catch (NoSuchFieldException e) { - try { - field = targetClass.getField(fieldName); - } catch (NoSuchFieldException ignore) { - } - - if (!targetClass.getSuperclass().equals(Object.class)) { - return getField(targetClass.getSuperclass(), fieldName); - } else { - throw handleException(e); - } - } finally { - if (field != null) { - field.setAccessible(true); - } - } - - return field; - } - - /** - * Get the {@link Field} with the given name belonging to the provided Java {@link Class} or {@code null} - * if no {@link Field} was found. - * - * @param targetClass the provided Java {@link Class} the field belongs to - * @param fieldName the {@link Field} name - * @return the {@link Field} matching the given name or {@code null} - */ - public static Field getFieldOrNull(Class targetClass, String fieldName) { - try { - return getField(targetClass, fieldName); - } catch (IllegalArgumentException e) { - return null; - } - } - - /** - * Get the the value of {@link Field} with the given name belonging to the provided Java {@link Class} or {@code null} - * if no {@link Field} was found. - * - * @param targetClass the provided Java {@link Class} the field belongs to - * @param fieldName the {@link Field} name - * @return the value of {@link Field} matching the given name or {@code null} - */ - public static T getFieldValueOrNull(Class targetClass, String fieldName) { - try { - Field field = getField(targetClass, fieldName); - T returnValue = (T) field.get(null); - return returnValue; - } catch (IllegalArgumentException | IllegalAccessException e) { - return null; - } - } - - /** - * Get the value of the field matching the given name and belonging to target {@link Object}. - * - * @param target target {@link Object} whose field we are retrieving the value from - * @param fieldName field name - * @param field type - * @return field value - */ - public static T getFieldValue(Object target, String fieldName) { - try { - Field field = getField(target.getClass(), fieldName); - @SuppressWarnings("unchecked") - T returnValue = (T) field.get(target); - return returnValue; - } catch (IllegalAccessException e) { - throw handleException(e); - } - } - - /** - * Get the value of the field matching the given name and belonging to target {@link Object} or {@code null} - * if no {@link Field} was found.. - * - * @param target target {@link Object} whose field we are retrieving the value from - * @param fieldName field name - * @param field type - * @return field value matching the given name or {@code null} - */ - public static T getFieldValueOrNull(Object target, String fieldName) { - try { - Field field = getField(target.getClass(), fieldName); - @SuppressWarnings("unchecked") - T returnValue = (T) field.get(target); - return returnValue; - } catch (IllegalAccessException e) { - return null; - } - } - - /** - * Set the value of the field matching the given name and belonging to target {@link Object}. - * - * @param target target object - * @param fieldName field name - * @param value field value - */ - public static void setFieldValue(Object target, String fieldName, Object value) { - try { - Field field = getField(target.getClass(), fieldName); - field.set(target, value); - } catch (IllegalAccessException e) { - throw handleException(e); - } - } - - /** - * Get the {@link Method} with the given signature (name and parameter types) belonging to - * the provided Java {@link Object}. - * - * @param target target {@link Object} - * @param methodName method name - * @param parameterTypes method parameter types - * @return return {@link Method} matching the provided signature - */ - public static Method getMethod(Object target, String methodName, Class... parameterTypes) { - return getMethod(target.getClass(), methodName, parameterTypes); - } - - /** - * Get the {@link Method} with the given signature (name and parameter types) belonging to - * the provided Java {@link Object} or {@code null} if no {@link Method} was found. - * - * @param target target {@link Object} - * @param methodName method name - * @param parameterTypes method parameter types - * @return return {@link Method} matching the provided signature or {@code null} - */ - public static Method getMethodOrNull(Object target, String methodName, Class... parameterTypes) { - try { - return getMethod(target.getClass(), methodName, parameterTypes); - } catch (RuntimeException e) { - return null; - } - } - - /** - * Get the {@link Method} with the given signature (name and parameter types) belonging to - * the provided Java {@link Class}. - * - * @param targetClass target {@link Class} - * @param methodName method name - * @param parameterTypes method parameter types - * @return the {@link Method} matching the provided signature - */ - @SuppressWarnings("unchecked") - public static Method getMethod(Class targetClass, String methodName, Class... parameterTypes) { - try { - return targetClass.getDeclaredMethod(methodName, parameterTypes); - } catch (NoSuchMethodException e) { - try { - return targetClass.getMethod(methodName, parameterTypes); - } catch (NoSuchMethodException ignore) { - } - - if (!targetClass.getSuperclass().equals(Object.class)) { - return getMethod(targetClass.getSuperclass(), methodName, parameterTypes); - } else { - throw handleException(e); - } - } - } - - /** - * Get the {@link Method} with the given signature (name and parameter types) belonging to - * the provided Java {@link Object} or {@code null} if no {@link Method} was found. - * - * @param targetClass target {@link Class} - * @param methodName method name - * @param parameterTypes method parameter types - * @return return {@link Method} matching the provided signature or {@code null} - */ - public static Method getMethodOrNull(Class targetClass, String methodName, Class... parameterTypes) { - try { - return getMethod(targetClass, methodName, parameterTypes); - } catch (RuntimeException e) { - return null; - } - } - - /** - * Get the {@link Method} with the given signature (name and parameter types) belonging to - * the provided Java {@link Class}, excluding inherited ones, or {@code null} if no {@link Method} was found. - * - * @param targetClass target {@link Class} - * @param methodName method name - * @param parameterTypes method parameter types - * @return return {@link Method} matching the provided signature or {@code null} - */ - public static Method getDeclaredMethodOrNull(Class targetClass, String methodName, Class... parameterTypes) { - try { - return targetClass.getDeclaredMethod(methodName, parameterTypes); - } catch (NoSuchMethodException e) { - return null; - } - } - - /** - * Check if the provided Java {@link Class} contains a method matching - * the given signature (name and parameter types). - * - * @param targetClass target {@link Class} - * @param methodName method name - * @param parameterTypes method parameter types - * @return the provided Java {@link Class} contains a method with the given signature - */ - public static boolean hasMethod(Class targetClass, String methodName, Class... parameterTypes) { - try { - targetClass.getMethod(methodName, parameterTypes); - return true; - } catch (NoSuchMethodException e) { - return false; - } - } - - /** - * Get the property setter {@link Method} with the given signature (name and parameter types) - * belonging to the provided Java {@link Object}. - * - * @param target target {@link Object} - * @param propertyName property name - * @param parameterType setter property type - * @return the setter {@link Method} matching the provided signature - */ - public static Method getSetter(Object target, String propertyName, Class parameterType) { - String setterMethodName = SETTER_PREFIX + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); - Method setter = getMethod(target, setterMethodName, parameterType); - setter.setAccessible(true); - return setter; - } - - /** - * Get the property getter {@link Method} with the given name belonging to - * the provided Java {@link Object}. - * - * @param target target {@link Object} - * @param propertyName property name - * @return the getter {@link Method} matching the provided name - */ - public static Method getGetter(Object target, String propertyName) { - String getterMethodName = GETTER_PREFIX + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); - Method getter = getMethod(target, getterMethodName); - getter.setAccessible(true); - return getter; - } - - /** - * Invoke the provided {@link Method} on the given Java {@link Object}. - * - * @param target target {@link Object} whose method we are invoking - * @param method method to invoke - * @param parameters parameters passed to the method call - * @param return value object type - * @return the value return by the {@link Method} invocation - */ - public static T invokeMethod(Object target, Method method, Object... parameters) { - try { - method.setAccessible(true); - @SuppressWarnings("unchecked") - T returnValue = (T) method.invoke(target, parameters); - return returnValue; - } catch (InvocationTargetException e) { - throw handleException(e); - } catch (IllegalAccessException e) { - throw handleException(e); - } - } - - /** - * Invoke the method with the provided signature (name and parameter types) - * on the given Java {@link Object}. - * - * @param target target {@link Object} whose method we are invoking - * @param methodName method name to invoke - * @param parameters parameters passed to the method call - * @param return value object type - * @return the value return by the method invocation - */ - public static T invokeMethod(Object target, String methodName, Object... parameters) { - try { - Class[] parameterClasses = new Class[parameters.length]; - - for (int i = 0; i < parameters.length; i++) { - parameterClasses[i] = parameters[i].getClass(); - } - - Method method = getMethod(target, methodName, parameterClasses); - method.setAccessible(true); - @SuppressWarnings("unchecked") - T returnValue = (T) method.invoke(target, parameters); - return returnValue; - } catch (InvocationTargetException e) { - throw handleException(e); - } catch (IllegalAccessException e) { - throw handleException(e); - } - } - - /** - * Invoke the property getter with the provided name on the given Java {@link Object}. - * - * @param target target {@link Object} whose property getter we are invoking - * @param propertyName property name whose getter we are invoking - * @param return value object type - * @return the value return by the getter invocation - */ - public static T invokeGetter(Object target, String propertyName) { - Method setter = getGetter(target, propertyName); - try { - return (T) setter.invoke(target); - } catch (IllegalAccessException e) { - throw handleException(e); - } catch (InvocationTargetException e) { - throw handleException(e); - } - } - - /** - * Invoke the property setter with the provided signature (name and parameter types) - * on the given Java {@link Object}. - * - * @param target target {@link Object} whose property setter we are invoking - * @param propertyName property name whose setter we are invoking - * @param parameter parameter passed to the setter call - */ - public static void invokeSetter(Object target, String propertyName, Object parameter) { - Method setter = getSetter(target, propertyName, parameter.getClass()); - try { - setter.invoke(target, parameter); - } catch (IllegalAccessException e) { - throw handleException(e); - } catch (InvocationTargetException e) { - throw handleException(e); - } - } - - /** - * Invoke the {@link boolean} property setter with the provided name - * on the given Java {@link Object}. - * - * @param target target {@link Object} whose property setter we are invoking - * @param propertyName property name whose setter we are invoking - * @param parameter {@link boolean} parameter passed to the setter call - */ - public static void invokeSetter(Object target, String propertyName, boolean parameter) { - Method setter = getSetter(target, propertyName, boolean.class); - try { - setter.invoke(target, parameter); - } catch (IllegalAccessException e) { - throw handleException(e); - } catch (InvocationTargetException e) { - throw handleException(e); - } - } - - /** - * Invoke the {@link int} property setter with the provided name - * on the given Java {@link Object}. - * - * @param target target {@link Object} whose property setter we are invoking - * @param propertyName property name whose setter we are invoking - * @param parameter {@link int} parameter passed to the setter call - */ - public static void invokeSetter(Object target, String propertyName, int parameter) { - Method setter = getSetter(target, propertyName, int.class); - try { - setter.invoke(target, parameter); - } catch (IllegalAccessException e) { - throw handleException(e); - } catch (InvocationTargetException e) { - throw handleException(e); - } - } - - /** - * Invoke the {@code static} {@link Method} with the provided parameters. - * - * @param method target {@code static} {@link Method} to invoke - * @param parameters parameters passed to the method call - * @param return value object type - * @return the value return by the method invocation - */ - public static T invokeStaticMethod(Method method, Object... parameters) { - try { - method.setAccessible(true); - @SuppressWarnings("unchecked") - T returnValue = (T) method.invoke(null, parameters); - return returnValue; - } catch (InvocationTargetException e) { - throw handleException(e); - } catch (IllegalAccessException e) { - throw handleException(e); - } - } - - /** - * Get the Java {@link Class} with the given fully-qualified name. - * - * @param className the Java {@link Class} name to be retrieved - * @param {@link Class} type - * @return the Java {@link Class} object - */ - @SuppressWarnings("unchecked") - public static Class getClass(String className) { - try { - return (Class) Class.forName(className, false, Thread.currentThread().getContextClassLoader()); - } catch (ClassNotFoundException e) { - throw handleException(e); - } - } - - /** - * Get the Java {@link Class} with the given fully-qualified name or or {@code null} - * if no {@link Class} was found matching the provided name. - * - * @param className the Java {@link Class} name to be retrieved - * @param {@link Class} type - * @return the Java {@link Class} object or {@code null} - */ - @SuppressWarnings("unchecked") - public static Class getClassOrNull(String className) { - try { - return (Class) getClass(className); - } catch (Exception e) { - return null; - } - } - - /** - * Get the Java Wrapper {@link Class} associated to the given primitive type. - * - * @param clazz primitive class - * @return the Java Wrapper {@link Class} - */ - public static Class getWrapperClass(Class clazz) { - if (!clazz.isPrimitive()) - return clazz; - - if (clazz == Integer.TYPE) - return Integer.class; - if (clazz == Long.TYPE) - return Long.class; - if (clazz == Boolean.TYPE) - return Boolean.class; - if (clazz == Byte.TYPE) - return Byte.class; - if (clazz == Character.TYPE) - return Character.class; - if (clazz == Float.TYPE) - return Float.class; - if (clazz == Double.TYPE) - return Double.class; - if (clazz == Short.TYPE) - return Short.class; - if (clazz == Void.TYPE) - return Void.class; - - return clazz; - } - - /** - * Get the first super class matching the provided package name. - * - * @param clazz Java class - * @param packageName package name - * @param class generic type - * @return the first super class matching the provided package name or {@code null}. - */ - public static Class getFirstSuperClassFromPackage(Class clazz, String packageName) { - if (clazz.getPackage().getName().equals(packageName)) { - return clazz; - } else { - Class superClass = clazz.getSuperclass(); - return (superClass == null || superClass.equals(Object.class)) ? - null : - (Class) getFirstSuperClassFromPackage(superClass, packageName); - } - } - - /** - * Get the generic types of a given Class. - * - * @param parameterizedType parameterized Type - * @return generic types for the given Class. - */ - public static Set getGenericTypes(ParameterizedType parameterizedType) { - Set genericTypes = new LinkedHashSet<>(); - for(Type genericType : parameterizedType.getActualTypeArguments()) { - if (genericType instanceof Class) { - genericTypes.add((Class) genericType); - } - } - return genericTypes; - } - - /** - * Get the {@link Member} with the given name belonging to the provided Java {@link Class} or {@code null} - * if no {@link Member} was found. - * - * @param targetClass the provided Java {@link Class} the field or method belongs to - * @param memberName the {@link Field} or {@link Method} name - * @return the {@link Field} or {@link Method} matching the given name or {@code null} - */ - public static Member getMemberOrNull(Class targetClass, String memberName) { - Field field = getFieldOrNull(targetClass, memberName); - return (field != null) ? field : getMethodOrNull(targetClass, memberName); - } - - /** - * Get the generic {@link Type} of the {@link Member} with the given name belonging to the provided Java {@link Class} or {@code null} - * if no {@link Member} was found. - * - * @param targetClass the provided Java {@link Class} the field or method belongs to - * @param memberName the {@link Field} or {@link Method} name - * @return the generic {@link Type} of the {@link Field} or {@link Method} matching the given name or {@code null} - */ - public static Type getMemberGenericTypeOrNull(Class targetClass, String memberName) { - Field field = getFieldOrNull(targetClass, memberName); - return (field != null) ? field.getGenericType() : getMethodOrNull(targetClass, memberName).getGenericReturnType(); - } - - /** - * Handle the {@link NoSuchFieldException} by rethrowing it as an {@link IllegalArgumentException}. - * - * @param e the original {@link NoSuchFieldException} - * @return the {@link IllegalArgumentException} wrapping exception - */ - private static IllegalArgumentException handleException(NoSuchFieldException e) { - return new IllegalArgumentException(e); - } - - /** - * Handle the {@link NoSuchMethodException} by rethrowing it as an {@link IllegalArgumentException}. - * - * @param e the original {@link NoSuchMethodException} - * @return the {@link IllegalArgumentException} wrapping exception - */ - private static IllegalArgumentException handleException(NoSuchMethodException e) { - return new IllegalArgumentException(e); - } - - /** - * Handle the {@link IllegalAccessException} by rethrowing it as an {@link IllegalArgumentException}. - * - * @param e the original {@link IllegalAccessException} - * @return the {@link IllegalArgumentException} wrapping exception - */ - private static IllegalArgumentException handleException(IllegalAccessException e) { - return new IllegalArgumentException(e); - } - - /** - * Handle the {@link InvocationTargetException} by rethrowing it as an {@link IllegalArgumentException}. - * - * @param e the original {@link InvocationTargetException} - * @return the {@link IllegalArgumentException} wrapping exception - */ - private static IllegalArgumentException handleException(InvocationTargetException e) { - return new IllegalArgumentException(e); - } - - /** - * Handle the {@link ClassNotFoundException} by rethrowing it as an {@link IllegalArgumentException}. - * - * @param e the original {@link ClassNotFoundException} - * @return the {@link IllegalArgumentException} wrapping exception - */ - private static IllegalArgumentException handleException(ClassNotFoundException e) { - return new IllegalArgumentException(e); - } - - /** - * Handle the {@link InstantiationException} by rethrowing it as an {@link IllegalArgumentException}. - * - * @param e the original {@link InstantiationException} - * @return the {@link IllegalArgumentException} wrapping exception - */ - private static IllegalArgumentException handleException(InstantiationException e) { - return new IllegalArgumentException(e); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/StringUtils.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/StringUtils.java deleted file mode 100644 index 20c8d5c5b..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/hibernate/util/StringUtils.java +++ /dev/null @@ -1,64 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import java.util.Locale; - -/** - * StringUtils - String utilities holder. - * - * @author Vlad Mihalcea - * @since 2.5.1 - */ -public class StringUtils { - - public static final String LINE_SEPARATOR = System.getProperty("line.separator"); - - private StringUtils() { - throw new UnsupportedOperationException("StringUtils is not instantiable!"); - } - - /** - * Join the provided {@code elements} separated by the {@code delimiter}. - * - * @param delimiter delimiter - * @param elements elements to join - * @return the {link @String} result obtained from joining all elements - */ - public static String join(CharSequence delimiter, CharSequence... elements) { - StringBuilder builder = new StringBuilder(); - - boolean first = true; - - for (CharSequence element : elements) { - if(first) { - first = false; - } else { - builder.append(delimiter); - } - builder.append(element); - } - - return builder.toString(); - } - - /** - * Check if the String value is null, empty or contains only whitespace characters. - * @param value String value - * @return if the string is blank - */ - public static boolean isBlank(String value) { - return value == null || value.isEmpty() || value.trim().isEmpty(); - } - - /** - * Transform string to lowercase. - * - * @param value String value - * @return String value in lowercase - */ - public static String toLowercase(String value) { - if(isBlank(value)) { - return value; - } - return value.toLowerCase(Locale.ROOT); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/SQLStatementCountMismatchException.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/SQLStatementCountMismatchException.java deleted file mode 100644 index 89ba77820..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/SQLStatementCountMismatchException.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.hypersistence.utils.jdbc.validator; - -/** - * SQLStatementCountMismatchException - Thrown whenever there is a mismatch between - * the expected statements count and the ones being executed. - * - * @author Vlad Mihalcea - * @since 3.0.2 - */ -public class SQLStatementCountMismatchException extends RuntimeException { - - private final long expected; - private final long recorded; - - public SQLStatementCountMismatchException( - StatementType statementType, - long expected, - long recorded) { - super(statementType.toString(expected, recorded)); - this.expected = expected; - this.recorded = recorded; - } - - public long getExpected() { - return expected; - } - - public long getRecorded() { - return recorded; - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/SQLStatementCountValidator.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/SQLStatementCountValidator.java deleted file mode 100644 index 114e5d8e5..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/SQLStatementCountValidator.java +++ /dev/null @@ -1,72 +0,0 @@ -package io.hypersistence.utils.jdbc.validator; - -import net.ttddyy.dsproxy.QueryCountHolder; - -/** - * SQLStatementCountValidator - Validates recorded statements count. - * - * First you execute some operations against your database and then you check how many statements were executed. - * This is a useful tool against the "N+1" problem or suboptimal DML statements. - * - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - * @since 3.0.2 - */ -public class SQLStatementCountValidator { - - private SQLStatementCountValidator() {} - - /** - * Reset the statement recorder - */ - public static void reset() { - QueryCountHolder.clear(); - } - - /** - * Assert select statement count - * - * @param expectedCount expected select statement count - */ - public static void assertSelectCount(int expectedCount) { - StatementType.SELECT.validate(expectedCount); - } - - /** - * Assert insert statement count - * - * @param expectedCount expected insert statement count - */ - public static void assertInsertCount(int expectedCount) { - StatementType.INSERT.validate(expectedCount); - } - - /** - * Assert update statement count - * - * @param expectedCount expected update statement count - */ - public static void assertUpdateCount(int expectedCount) { - StatementType.UPDATE.validate(expectedCount); - } - - /** - * Assert delete statement count - * - * @param expectedCount expected delete statement count - */ - public static void assertDeleteCount(int expectedCount) { - StatementType.DELETE.validate(expectedCount); - } - - /** - * Assert the total statement count - * - * @param expectedCount expected total statement count - */ - public static void assertTotalCount(int expectedCount) { - StatementType.TOTAL.validate(expectedCount); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/StatementType.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/StatementType.java deleted file mode 100644 index 7169aa11e..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/jdbc/validator/StatementType.java +++ /dev/null @@ -1,85 +0,0 @@ -package io.hypersistence.utils.jdbc.validator; - -import net.ttddyy.dsproxy.QueryCount; -import net.ttddyy.dsproxy.QueryCountHolder; - -/** - * StatementType - The type of statements that got validated. - * - * @author Vlad Mihalcea - * @since 3.0.2 - */ -enum StatementType { - SELECT { - @Override - protected long recordedCount() { - QueryCount queryCount = QueryCountHolder.getGrandTotal(); - return queryCount.getSelect(); - } - }, - INSERT { - @Override - protected long recordedCount() { - QueryCount queryCount = QueryCountHolder.getGrandTotal(); - return queryCount.getInsert(); - } - }, - UPDATE { - @Override - protected long recordedCount() { - QueryCount queryCount = QueryCountHolder.getGrandTotal(); - return queryCount.getUpdate(); - } - }, - DELETE { - @Override - protected long recordedCount() { - QueryCount queryCount = QueryCountHolder.getGrandTotal(); - return queryCount.getDelete(); - } - }, - TOTAL { - @Override - protected long recordedCount() { - QueryCount queryCount = QueryCountHolder.getGrandTotal(); - return queryCount.getTotal(); - } - - @Override - protected String toString(long expectedCount, long recordedCount) { - return String.format( - "Expected a total of [%d] statement(s) but recorded [%d] instead!", - expectedCount, - recordedCount - ); - } - }; - - protected abstract long recordedCount(); - - protected String toString(long expectedCount, long recordedCount) { - return String.format( - "Expected [%d] %s statement%s but recorded [%d] instead!", - expectedCount, - name(), - expectedCount > 1 ? "s" : "", - recordedCount - ); - } - - /** - * Validate if the expected statements match the record ones. - * - * @param expectedCount expected SQL statements - */ - void validate(long expectedCount) { - long recordedCount = recordedCount(); - if (expectedCount != recordedCount) { - throw new SQLStatementCountMismatchException( - this, - expectedCount, - recordedCount - ); - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/annotation/Retry.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/annotation/Retry.java deleted file mode 100644 index 9da8550a4..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/annotation/Retry.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.hypersistence.utils.spring.annotation; - -import java.lang.annotation.*; - -/** - * The Retry annotation instructs Spring to retry - * a method execution when catching a given {@link Throwable}. - * - * @author Vlad Mihalcea - * @since 3.1.0 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -@Inherited -public @interface Retry { - - /** - * Declare the throwable types the retry will be executed for. - * - * @return throwable types triggering a retry - */ - Class[] on(); - - /** - * The number of retry attempts - * - * @return retry attempts - */ - int times() default 1; -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/aop/RetryAspect.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/aop/RetryAspect.java deleted file mode 100644 index 3243e9279..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/aop/RetryAspect.java +++ /dev/null @@ -1,110 +0,0 @@ -package io.hypersistence.utils.spring.aop; - -import io.hypersistence.utils.spring.annotation.Retry; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.reflect.MethodSignature; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.stereotype.Component; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.Arrays; - -/** - * Aspect to retry method execution. - * - * @author Vlad Mihalcea - */ -@Aspect -@Component -public class RetryAspect { - - private static final Logger LOGGER = LoggerFactory.getLogger(RetryAspect.class); - - @Around("@annotation(io.hypersistence.utils.spring.annotation.Retry)") - public Object retry(ProceedingJoinPoint pjp) throws Throwable { - Retry retryAnnotation = getAnnotation(pjp, Retry.class); - return (retryAnnotation != null) ? proceed(pjp, retryAnnotation) : proceed(pjp); - } - - private Object proceed(ProceedingJoinPoint pjp) throws Throwable { - return pjp.proceed(); - } - - private Object proceed(ProceedingJoinPoint pjp, Retry retryAnnotation) throws Throwable { - int times = retryAnnotation.times(); - Class[] retryOn = retryAnnotation.on(); - if (times <= 0) { - throw new IllegalArgumentException( - "@Retry{times} should be greater than 0!" - ); - } - if (retryOn.length <= 0) { - throw new IllegalArgumentException( - "@Retry{on} should have at least one Throwable!" - ); - } - - LOGGER.trace("Proceed with {} retries on {}", times, Arrays.toString(retryOn)); - - return tryProceeding(pjp, times, retryOn); - } - - private Object tryProceeding(ProceedingJoinPoint pjp, int times, Class[] retryOn) - throws Throwable { - try { - return proceed(pjp); - } catch (Throwable throwable) { - if (isRetryThrowable(throwable, retryOn) && times-- > 0) { - LOGGER.info( - "Retryable failure was caught, {} remaining retr{} on {}", - times, - (times == 1 ? "y" : "ies"), - Arrays.toString(retryOn) - ); - return tryProceeding(pjp, times, retryOn); - } - throw throwable; - } - } - - private boolean isRetryThrowable(Throwable throwable, Class[] retryOn) { - Throwable cause = throwable; - do { - for (Class retryThrowable : retryOn) { - if (retryThrowable.isAssignableFrom(cause.getClass())) { - return true; - } - } - - if (cause.getCause() == null || cause.getCause() == cause) { - break; - } else { - cause = cause.getCause(); - } - } - while (true); - return false; - } - - private T getAnnotation(ProceedingJoinPoint pjp, Class annotationClass) - throws NoSuchMethodException { - MethodSignature signature = (MethodSignature) pjp.getSignature(); - Method method = signature.getMethod(); - T annotation = AnnotationUtils.findAnnotation(method, annotationClass); - - if (annotation != null) { - return annotation; - } - - method = pjp.getTarget().getClass().getMethod( - pjp.getSignature().getName(), - signature.getParameterTypes() - ); - return AnnotationUtils.findAnnotation(method, annotationClass); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/BaseJpaRepository.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/BaseJpaRepository.java deleted file mode 100644 index 3294a304e..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/BaseJpaRepository.java +++ /dev/null @@ -1,172 +0,0 @@ -package io.hypersistence.utils.spring.repository; - -import javax.persistence.LockModeType; -import org.springframework.data.repository.NoRepositoryBean; -import org.springframework.data.repository.Repository; -import org.springframework.data.repository.query.QueryByExampleExecutor; - -import java.util.List; -import java.util.Optional; - -/** - * The {@code BaseJpaRepository} fixes many of the problems that the default Spring Data {@code JpaRepository} - * suffers from. - *

- * For more details about how to use it, check out this article on vladmihalcea.com. - * - * @author Vlad Mihalcea - * @version 2.21.0 - */ -@NoRepositoryBean -public interface BaseJpaRepository extends Repository, QueryByExampleExecutor { - - Optional findById(ID id); - - boolean existsById(ID id); - - T getReferenceById(ID id); - - List findAllById(Iterable ids); - - long count(); - - void delete(T entity); - - void deleteAllInBatch(Iterable entities); - - void deleteById(ID id); - - void deleteAllByIdInBatch(Iterable ids); - - void flush(); - - /** - * The persist method allows you to pass the provided entity to the {@code persist} method of the - * underlying JPA {@code EntityManager}. - * - * @param entity entity to persist - * @param entity type - * @return entity - */ - S persist(S entity); - - /** - * The persistAndFlush method allows you to pass the provided entity to the {@code persist} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entity entity to persist - * @param entity type - * @return entity - */ - S persistAndFlush(S entity); - - /** - * The persistAll method allows you to pass the provided entities to the {@code persist} method of the - * underlying JPA {@code EntityManager}. - * - * @param entities entities to persist - * @param entity type - * @return entities - */ - List persistAll(Iterable entities); - - /** - * The persistAll method allows you to pass the provided entities to the {@code persist} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entities entities to persist - * @param entity type - * @return entities - */ - List persistAllAndFlush(Iterable entities); - - /** - * The persist method allows you to pass the provided entity to the {@code merge} method of the - * underlying JPA {@code EntityManager}. - * - * @param entity entity to merge - * @param entity type - * @return entity - */ - S merge(S entity); - - /** - * The mergeAndFlush method allows you to pass the provided entity to the {@code merge} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entity entity to merge - * @param entity type - * @return entity - */ - S mergeAndFlush(S entity); - - /** - * The mergeAll method allows you to pass the provided entities to the {@code merge} method of the - * underlying JPA {@code EntityManager}. - * - * @param entities entities to merge - * @param entity type - * @return entities - */ - List mergeAll(Iterable entities); - - /** - * The mergeAllAndFlush method allows you to pass the provided entities to the {@code merge} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entities entities to persist - * @param entity type - * @return entities - */ - List mergeAllAndFlush(Iterable entities); - - /** - * The update method allows you to pass the provided entity to the {@code update} method of the - * underlying JPA {@code EntityManager}. - * - * @param entity entity to update - * @param entity type - * @return entity - */ - S update(S entity); - - /** - * The updateAndFlush method allows you to pass the provided entity to the {@code update} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entity entity to update - * @param entity type - * @return entity - */ - S updateAndFlush(S entity); - - /** - * The updateAll method allows you to pass the provided entities to the {@code update} method of the - * underlying JPA {@code EntityManager}. - * - * @param entities entities to update - * @param entity type - * @return entities - */ - List updateAll(Iterable entities); - - /** - * The updateAllAndFlush method allows you to pass the provided entities to the {@code update} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entities entities to update - * @param entity type - * @return entities - */ - List updateAllAndFlush(Iterable entities); - - /** - * Lock the entity with the provided identifier. - * - * @param id entity identifier - * @param lockMode entity lock mode - * @return entity - */ - T lockById(ID id, LockModeType lockMode); -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/BaseJpaRepositoryImpl.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/BaseJpaRepositoryImpl.java deleted file mode 100644 index 5be8cd7c0..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/BaseJpaRepositoryImpl.java +++ /dev/null @@ -1,174 +0,0 @@ -package io.hypersistence.utils.spring.repository; - -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import org.hibernate.Session; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.internal.AbstractSharedSessionContract; -import org.springframework.data.jpa.repository.support.JpaEntityInformation; -import org.springframework.data.jpa.repository.support.SimpleJpaRepository; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.Assert; - -import javax.persistence.EntityManager; -import javax.persistence.LockModeType; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Supplier; - -/** - * @author Vlad Mihalcea - */ -public class BaseJpaRepositoryImpl extends SimpleJpaRepository - implements BaseJpaRepository { - - private static final String ID_MUST_NOT_BE_NULL = ReflectionUtils.getFieldValueOrNull(SimpleJpaRepository.class, "ID_MUST_NOT_BE_NULL"); - - private final EntityManager entityManager; - private final JpaEntityInformation entityInformation; - - public BaseJpaRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { - super(entityInformation, entityManager); - this.entityInformation = entityInformation; - this.entityManager = entityManager; - } - - @Transactional - public S persist(S entity) { - entityManager.persist(entity); - return entity; - } - - @Transactional - public S persistAndFlush(S entity) { - persist(entity); - entityManager.flush(); - return entity; - } - - @Transactional - public List persistAll(Iterable entities) { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(persist(entity)); - } - return result; - } - - @Transactional - public List persistAllAndFlush(Iterable entities) { - return executeBatch(() -> { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(persist(entity)); - } - entityManager.flush(); - return result; - }); - } - - @Transactional - public S merge(S entity) { - return entityManager.merge(entity); - } - - @Transactional - public S mergeAndFlush(S entity) { - S result = merge(entity); - entityManager.flush(); - return result; - } - - @Transactional - public List mergeAll(Iterable entities) { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(merge(entity)); - } - return result; - } - - @Transactional - public List mergeAllAndFlush(Iterable entities) { - return executeBatch(() -> { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(merge(entity)); - } - entityManager.flush(); - return result; - }); - } - - @Transactional - public S update(S entity) { - session().update(entity); - return entity; - } - - @Transactional - public S updateAndFlush(S entity) { - update(entity); - entityManager.flush(); - return entity; - } - - @Transactional - public List updateAll(Iterable entities) { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(update(entity)); - } - return result; - } - - @Transactional - public List updateAllAndFlush(Iterable entities) { - return executeBatch(() -> { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(update(entity)); - } - entityManager.flush(); - return result; - }); - } - - @Override - public T getReferenceById(ID id) { - Assert.notNull(id, ID_MUST_NOT_BE_NULL); - return entityManager.getReference(getDomainClass(), id); - } - - @Override - public T lockById(ID id, LockModeType lockMode) { - return (T) entityManager.find(entityInformation.getJavaType(), id, lockMode); - } - - protected Integer getBatchSize(Session session) { - SessionFactoryImplementor sessionFactory = session.getSessionFactory().unwrap(SessionFactoryImplementor.class); - final JdbcServices jdbcServices = sessionFactory.getServiceRegistry().getService(JdbcServices.class); - if(!jdbcServices.getExtractedMetaDataSupport().supportsBatchUpdates()) { - return Integer.MIN_VALUE; - } - return session.unwrap(AbstractSharedSessionContract.class).getConfiguredJdbcBatchSize(); - } - - protected R executeBatch(Supplier callback) { - Session session = session(); - Integer jdbcBatchSize = getBatchSize(session); - Integer originalSessionBatchSize = session.getJdbcBatchSize(); - try { - if (jdbcBatchSize == null) { - session.setJdbcBatchSize(10); - } - return callback.get(); - } finally { - session.setJdbcBatchSize(originalSessionBatchSize); - } - } - - protected Session session() { - return entityManager.unwrap(Session.class); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/HibernateRepository.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/HibernateRepository.java deleted file mode 100644 index 6544083b5..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/HibernateRepository.java +++ /dev/null @@ -1,181 +0,0 @@ -package io.hypersistence.utils.spring.repository; - -import java.util.List; - -/** - * The {@code HibernateRepository} fixes the problems that the default Spring Data {@code JpaRepository} - * suffers from. - *

- * For more details about how to use it, check out this article. - * - * @author Vlad Mihalcea - * @version 2.17.0 - */ -public interface HibernateRepository { - - /** - * The findAll method is a terrible Anti-Pattern. - *

- * For more details about why you should not use the {@code findAll} method by default, - * check out this article. - * - * @return all the records from the database table this entity is mapped to - */ - @Deprecated - List findAll(); - - //The save methods will trigger an UnsupportedOperationException - - /** - * The save method should be avoided. - *

- * For more details about how to use it, check out this article. - */ - @Deprecated - S save(S entity); - - /** - * The save method should be avoided. - *

- * For more details about how to use it, check out this article. - */ - @Deprecated - List saveAll(Iterable entities); - - /** - * The saveAndFlush method should be avoided. - *

- * For more details about how to use it, check out this article. - */ - @Deprecated - S saveAndFlush(S entity); - - /** - * The saveAllAndFlush method should be avoided. - *

- * For more details about how to use it, check out this article. - */ - @Deprecated - List saveAllAndFlush(Iterable entities); - - /** - * The persist method allows you to pass the provided entity to the {@code persist} method of the - * underlying JPA {@code EntityManager}. - * - * @param entity entity to persist - * @param entity type - * @return entity - */ - S persist(S entity); - - /** - * The persistAndFlush method allows you to pass the provided entity to the {@code persist} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entity entity to persist - * @param entity type - * @return entity - */ - S persistAndFlush(S entity); - - /** - * The persistAll method allows you to pass the provided entities to the {@code persist} method of the - * underlying JPA {@code EntityManager}. - * - * @param entities entities to persist - * @param entity type - * @return entities - */ - List persistAll(Iterable entities); - - /** - * The persistAll method allows you to pass the provided entities to the {@code persist} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entities entities to persist - * @param entity type - * @return entities - */ - List persistAllAndFlush(Iterable entities); - - /** - * The persist method allows you to pass the provided entity to the {@code merge} method of the - * underlying JPA {@code EntityManager}. - * - * @param entity entity to merge - * @param entity type - * @return entity - */ - S merge(S entity); - - /** - * The mergeAndFlush method allows you to pass the provided entity to the {@code merge} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entity entity to merge - * @param entity type - * @return entity - */ - S mergeAndFlush(S entity); - - /** - * The mergeAll method allows you to pass the provided entities to the {@code merge} method of the - * underlying JPA {@code EntityManager}. - * - * @param entities entities to merge - * @param entity type - * @return entities - */ - List mergeAll(Iterable entities); - - /** - * The mergeAllAndFlush method allows you to pass the provided entities to the {@code merge} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entities entities to persist - * @param entity type - * @return entities - */ - List mergeAllAndFlush(Iterable entities); - - /** - * The update method allows you to pass the provided entity to the {@code update} method of the - * underlying JPA {@code EntityManager}. - * - * @param entity entity to update - * @param entity type - * @return entity - */ - S update(S entity); - - /** - * The updateAndFlush method allows you to pass the provided entity to the {@code update} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entity entity to update - * @param entity type - * @return entity - */ - S updateAndFlush(S entity); - - /** - * The updateAll method allows you to pass the provided entities to the {@code update} method of the - * underlying JPA {@code EntityManager}. - * - * @param entities entities to update - * @param entity type - * @return entities - */ - List updateAll(Iterable entities); - - /** - * The updateAllAndFlush method allows you to pass the provided entities to the {@code update} method of the - * underlying JPA {@code EntityManager} and call {@code flush} afterwards. - * - * @param entities entities to update - * @param entity type - * @return entities - */ - List updateAllAndFlush(Iterable entities); -} diff --git a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/HibernateRepositoryImpl.java b/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/HibernateRepositoryImpl.java deleted file mode 100644 index 7e65bb04b..000000000 --- a/hypersistence-utils-hibernate-52/src/main/java/io/hypersistence/utils/spring/repository/HibernateRepositoryImpl.java +++ /dev/null @@ -1,174 +0,0 @@ -package io.hypersistence.utils.spring.repository; - -import org.hibernate.Session; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.internal.AbstractSharedSessionContract; - -import javax.persistence.EntityManager; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Supplier; - -/** - * @author Vlad Mihalcea - */ -public class HibernateRepositoryImpl implements HibernateRepository { - - private final EntityManager entityManager; - - public HibernateRepositoryImpl(EntityManager entityManager) { - this.entityManager = entityManager; - } - - @Override - public List findAll() { - throw new UnsupportedOperationException("Fetching all records from a given database table is a terrible idea!"); - } - - @Override - public S save(S entity) { - return unsupportedSave(); - } - - @Override - public List saveAll(Iterable entities) { - return unsupportedSave(); - } - - @Override - public S saveAndFlush(S entity) { - return unsupportedSave(); - } - - @Override - public List saveAllAndFlush(Iterable entities) { - return unsupportedSave(); - } - - public S persist(S entity) { - entityManager.persist(entity); - return entity; - } - - public S persistAndFlush(S entity) { - persist(entity); - entityManager.flush(); - return entity; - } - - public List persistAll(Iterable entities) { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(persist(entity)); - } - return result; - } - - public List persistAllAndFlush(Iterable entities) { - return executeBatch(() -> { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(persist(entity)); - } - entityManager.flush(); - return result; - }); - } - - public S merge(S entity) { - return entityManager.merge(entity); - } - - @Override - public S mergeAndFlush(S entity) { - S result = merge(entity); - entityManager.flush(); - return result; - } - - @Override - public List mergeAll(Iterable entities) { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(merge(entity)); - } - return result; - } - - @Override - public List mergeAllAndFlush(Iterable entities) { - return executeBatch(() -> { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(merge(entity)); - } - entityManager.flush(); - return result; - }); - } - - public S update(S entity) { - session().update(entity); - return entity; - } - - @Override - public S updateAndFlush(S entity) { - update(entity); - entityManager.flush(); - return entity; - } - - @Override - public List updateAll(Iterable entities) { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(update(entity)); - } - return result; - } - - @Override - public List updateAllAndFlush(Iterable entities) { - return executeBatch(() -> { - List result = new ArrayList<>(); - for(S entity : entities) { - result.add(update(entity)); - } - entityManager.flush(); - return result; - }); - } - - protected Integer getBatchSize(Session session) { - SessionFactoryImplementor sessionFactory = session.getSessionFactory().unwrap(SessionFactoryImplementor.class); - final JdbcServices jdbcServices = sessionFactory.getServiceRegistry().getService(JdbcServices.class); - if(!jdbcServices.getExtractedMetaDataSupport().supportsBatchUpdates()) { - return Integer.MIN_VALUE; - } - return session.unwrap(AbstractSharedSessionContract.class).getConfiguredJdbcBatchSize(); - } - - protected R executeBatch(Supplier callback) { - Session session = session(); - Integer jdbcBatchSize = getBatchSize(session); - Integer originalSessionBatchSize = session.getJdbcBatchSize(); - try { - if (jdbcBatchSize == null) { - session.setJdbcBatchSize(10); - } - return callback.get(); - } finally { - session.setJdbcBatchSize(originalSessionBatchSize); - } - } - - protected Session session() { - return entityManager.unwrap(Session.class); - } - - protected S unsupportedSave() { - throw new UnsupportedOperationException("There's no such thing as a save method in JPA, so don't use this hack!"); - } -} diff --git a/hypersistence-utils-hibernate-52/src/main/resources/META-INF/services/org.hibernate.boot.model.TypeContributor b/hypersistence-utils-hibernate-52/src/main/resources/META-INF/services/org.hibernate.boot.model.TypeContributor deleted file mode 100644 index 32d44102b..000000000 --- a/hypersistence-utils-hibernate-52/src/main/resources/META-INF/services/org.hibernate.boot.model.TypeContributor +++ /dev/null @@ -1 +0,0 @@ -io.hypersistence.utils.hibernate.type.HibernateTypesContributor \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/AbstractBatchSequenceGeneratorTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/AbstractBatchSequenceGeneratorTest.java deleted file mode 100644 index 325fcbf10..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/AbstractBatchSequenceGeneratorTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package io.hypersistence.utils.hibernate.id; - -import io.hypersistence.utils.hibernate.util.AbstractTest; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import net.ttddyy.dsproxy.QueryCount; -import net.ttddyy.dsproxy.QueryCountHolder; -import org.hibernate.annotations.GenericGenerator; -import org.hibernate.annotations.Parameter; -import org.hibernate.cfg.AvailableSettings; -import org.junit.Test; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import java.util.List; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -/** - * @author Philippe Marschall - */ -public abstract class AbstractBatchSequenceGeneratorTest extends AbstractTest { - - private static final int BATCH_SIZE = 50; - - @Override - protected Class[] entities() { - return new Class[]{ - Post.class - }; - } - - @Override - protected abstract DataSourceProvider dataSourceProvider(); - - @Override - protected void additionalProperties(Properties properties) { - properties.put(AvailableSettings.BATCH_VERSIONED_DATA, true); - properties.put(AvailableSettings.STATEMENT_BATCH_SIZE, BATCH_SIZE); - properties.put(AvailableSettings.ORDER_UPDATES, true); - properties.put(AvailableSettings.ORDER_INSERTS, true); - } - - @Test - public void test() { - QueryCountHolder.clear(); - - doInJPA(entityManager -> { - for (int i = 0; i < BATCH_SIZE; i++) { - Post post = new Post(); - - post.setTitle("Post " + i + 1); - entityManager.persist(post); - } - }); - - QueryCount queryCount = QueryCountHolder.getGrandTotal(); - assertEquals(1L, queryCount.getInsert()); - assertEquals(1L, getSelectCount(queryCount)); - assertEquals(2L, queryCount.getTotal()); - - doInJPA(entityManager -> { - List posts = entityManager.createQuery("SELECT p FROM Post p", Post.class).getResultList(); - assertEquals(BATCH_SIZE, posts.size()); - }); - } - - /** - * Recursive CTEs are not always recognized as OTHER instead of SELECT by datasource-proxy. - * See @link https://github.com/ttddyy/datasource-proxy/issues/76 - * - * @param queryCount query count - * @return select statement count - */ - protected long getSelectCount(QueryCount queryCount) { - switch (dataSourceProvider().database()) { - case ORACLE: - case POSTGRESQL: - return queryCount.getSelect(); - case SQLSERVER: - case H2: - return queryCount.getOther(); - } - throw new UnsupportedOperationException( - "Unsupported database: " + dataSourceProvider().database() - ); - } - - @Entity(name = "Post") - @Table(name = "post") - public static class Post { - - @Id - @GenericGenerator( - name = "post_sequence", - strategy = "io.hypersistence.utils.hibernate.id.BatchSequenceGenerator", - parameters = { - @Parameter(name = "sequence", value = "SEQ_PARENT_ID"), - @Parameter(name = "fetch_size", value = "" + BATCH_SIZE) - } - ) - @GeneratedValue(generator = "post_sequence") - private Long id; - - private String title; - - public Long getId() { - return id; - } - - public Post setId(Long id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public Post setTitle(String title) { - this.title = title; - return this; - } - } - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/H2BatchSequenceGeneratorTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/H2BatchSequenceGeneratorTest.java deleted file mode 100644 index e503723df..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/H2BatchSequenceGeneratorTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.hypersistence.utils.hibernate.id; - -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.H2DataSourceProvider; - -import static org.junit.Assert.assertEquals; - -/** - * @author Philippe Marschall - */ -public class H2BatchSequenceGeneratorTest extends AbstractBatchSequenceGeneratorTest { - - @Override - protected DataSourceProvider dataSourceProvider() { - return new H2DataSourceProvider(); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/OracleBatchSequenceGeneratorTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/OracleBatchSequenceGeneratorTest.java deleted file mode 100644 index bda2d7742..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/OracleBatchSequenceGeneratorTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.hypersistence.utils.hibernate.id; - -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.OracleDataSourceProvider; - -/** - * @author Philippe Marschall - */ -public class OracleBatchSequenceGeneratorTest extends AbstractBatchSequenceGeneratorTest { - - @Override - protected DataSourceProvider dataSourceProvider() { - return new OracleDataSourceProvider(); - } - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/PostgreSQLBatchSequenceGeneratorTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/PostgreSQLBatchSequenceGeneratorTest.java deleted file mode 100644 index 896ca34da..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/PostgreSQLBatchSequenceGeneratorTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.hypersistence.utils.hibernate.id; - -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; - -/** - * @author Philippe Marschall - */ -public class PostgreSQLBatchSequenceGeneratorTest extends AbstractBatchSequenceGeneratorTest { - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider(); - } - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/SQLServerBatchSequenceGeneratorTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/SQLServerBatchSequenceGeneratorTest.java deleted file mode 100644 index a723cac35..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/SQLServerBatchSequenceGeneratorTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.hypersistence.utils.hibernate.id; - -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.SQLServerDataSourceProvider; - -/** - * @author Philippe Marschall - */ -public class SQLServerBatchSequenceGeneratorTest extends AbstractBatchSequenceGeneratorTest { - - @Override - protected DataSourceProvider dataSourceProvider() { - return new SQLServerDataSourceProvider(); - } - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/TsidIdentifierTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/TsidIdentifierTest.java deleted file mode 100644 index a3dcd9717..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/id/TsidIdentifierTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package io.hypersistence.utils.hibernate.id; - -import io.hypersistence.tsid.TSID; -import io.hypersistence.utils.hibernate.util.AbstractTest; -import org.hibernate.annotations.GenericGenerator; -import org.hibernate.annotations.Parameter; -import org.junit.Test; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import java.util.function.Supplier; - -public class TsidIdentifierTest extends AbstractTest { - - @Override - protected Class[] entities() { - return new Class[] { - Post.class, - Tag.class - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - entityManager.persist( - new Post() - .setTitle("High-Performance Java Persistence") - ); - entityManager.flush(); - entityManager.merge( - new Post() - .setTitle("High-Performance Java Persistence") - ); - }); - } - - @Entity(name = "Post") - @Table(name = "post") - public static class Post { - - @Id - @GeneratedValue(generator = "tsid") - @GenericGenerator( - name = "tsid", - strategy = "io.hypersistence.utils.hibernate.id.TsidGenerator" - ) - private Long id; - - private String title; - - public Long getId() { - return id; - } - - public Post setId(Long id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public Post setTitle(String title) { - this.title = title; - return this; - } - } - - @Entity(name = "Tag") - @Table(name = "tag") - public static class Tag { - - @Id - @GeneratedValue(generator = "tsid") - @GenericGenerator( - name = "tsid", - strategy = "io.hypersistence.utils.hibernate.id.TsidGenerator", - parameters = @Parameter( - name = TsidGenerator.TSID_FACTORY_SUPPLIER_PARAM, - value = "io.hypersistence.utils.hibernate.id.TsidIdentifierTest$CustomTsidSupplier" - ) - ) - private Long id; - - private String name; - - public Long getId() { - return id; - } - - public Tag setId(Long id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Tag setName(String name) { - this.name = name; - return this; - } - } - - public static class CustomTsidSupplier implements Supplier { - - @Override - public TSID.Factory get() { - return TSID.Factory.builder() - .withNodeBits(1) - .build(); - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/naming/CamelCaseToSnakeCaseNamingStrategyTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/naming/CamelCaseToSnakeCaseNamingStrategyTest.java deleted file mode 100644 index f9b08048d..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/naming/CamelCaseToSnakeCaseNamingStrategyTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package io.hypersistence.utils.hibernate.naming; - -import io.hypersistence.utils.hibernate.util.AbstractTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.junit.Test; - -import javax.persistence.*; -import java.time.LocalDate; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class CamelCaseToSnakeCaseNamingStrategyTest extends AbstractTest { - - @Override - protected Class[] entities() { - return new Class[] { - BookAuthor.class, - PaperBackBook.class, - }; - } - - @Override - protected void additionalProperties(Properties properties) { - properties.put( - "hibernate.physical_naming_strategy", - CamelCaseToSnakeCaseNamingStrategy.INSTANCE - ); - } - - @Test - public void test() { - doInJPA(entityManager -> { - BookAuthor author = new BookAuthor(); - author.setId(1L); - author.setFirstName("Vlad"); - author.setLastName("Mihalcea"); - - entityManager.persist(author); - - PaperBackBook book = new PaperBackBook(); - book.setISBN("978-9730228236"); - book.setTitle("High-Performance Java Persistence"); - book.setPublishedOn(LocalDate.of(2016, 10, 12)); - book.setPublishedBy(author); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - - PaperBackBook book = session.bySimpleNaturalId(PaperBackBook.class).load("978-9730228236"); - assertEquals("High-Performance Java Persistence", book.getTitle()); - - assertEquals("Vlad Mihalcea", book.getPublishedBy().getFullName()); - }); - } - - @Entity(name = "BookAuthor") - public static class BookAuthor { - - @Id - private Long id; - - private String firstName; - - private String lastName; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getFullName() { - return firstName + " " + lastName; - } - } - - @Entity(name = "PaperBackBook") - public static class PaperBackBook { - - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE) - private Long id; - - @NaturalId - private String ISBN; - - private String title; - - private LocalDate publishedOn; - - @ManyToOne(fetch = FetchType.LAZY) - private BookAuthor publishedBy; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getISBN() { - return ISBN; - } - - public void setISBN(String ISBN) { - this.ISBN = ISBN; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public LocalDate getPublishedOn() { - return publishedOn; - } - - public void setPublishedOn(LocalDate publishedOn) { - this.publishedOn = publishedOn; - } - - public BookAuthor getPublishedBy() { - return publishedBy; - } - - public void setPublishedBy(BookAuthor publishedBy) { - this.publishedBy = publishedBy; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/ListResultTransformerTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/ListResultTransformerTest.java deleted file mode 100644 index 591647dce..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/ListResultTransformerTest.java +++ /dev/null @@ -1,212 +0,0 @@ -package io.hypersistence.utils.hibernate.query; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.transform.ResultTransformer; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import java.time.LocalDate; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class ListResultTransformerTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Post.class - }; - } - - @Override - public void afterInit() { - doInJPA(entityManager -> { - entityManager.persist( - new Post() - .setId(1L) - .setTitle( - "High-Performance Java Persistence " + - "eBook has been released!") - .setCreatedOn(LocalDate.of(2016, 8, 30)) - ); - - entityManager.persist( - new Post() - .setId(2L) - .setTitle( - "High-Performance Java Persistence " + - "paperback has been released!") - .setCreatedOn(LocalDate.of(2016, 10, 12)) - ); - - entityManager.persist( - new Post() - .setId(3L) - .setTitle( - "High-Performance Java Persistence " + - "Mach 1 video course has been released!") - .setCreatedOn(LocalDate.of(2018, 1, 30)) - ); - - entityManager.persist( - new Post() - .setId(4L) - .setTitle( - "High-Performance Java Persistence " + - "Mach 2 video course has been released!") - .setCreatedOn(LocalDate.of(2018, 5, 8)) - ); - - entityManager.persist( - new Post() - .setId(5L) - .setTitle( - "Hypersistence Optimizer has been released!") - .setCreatedOn(LocalDate.of(2019, 3, 19)) - ); - }); - } - - public static class PostCountByYear { - - private final int year; - - private final int postCount; - - public PostCountByYear(int year, int postCount) { - this.year = year; - this.postCount = postCount; - } - - public int getYear() { - return year; - } - - public int getPostCount() { - return postCount; - } - } - - @Test - public void testTransformer() { - doInJPA(entityManager -> { - List postCountByYearMap = (List) entityManager - .createQuery( - "select " + - " YEAR(p.createdOn) as year, " + - " count(p) as postCount " + - "from Post p " + - "group by " + - " YEAR(p.createdOn) " + - "order by " + - " YEAR(p.createdOn)") - .unwrap(org.hibernate.query.Query.class) - .setResultTransformer( - new ResultTransformer() { - @Override - public Object transformTuple(Object[] tuple, String[] aliases) { - return new PostCountByYear( - ((Number) tuple[0]).intValue(), - ((Number) tuple[1]).intValue() - ); - } - - @Override - public List transformList(List tuples) { - return tuples; - } - } - ) - .getResultList(); - - assertEquals(2016, postCountByYearMap.get(0).getYear()); - assertEquals(2, postCountByYearMap.get(0).getPostCount()); - - assertEquals(2018, postCountByYearMap.get(1).getYear()); - assertEquals(2, postCountByYearMap.get(1).getPostCount()); - - assertEquals(2019, postCountByYearMap.get(2).getYear()); - assertEquals(1, postCountByYearMap.get(2).getPostCount()); - }); - } - - @Test - public void testListResultTransformer() { - doInJPA(entityManager -> { - List postCountByYearMap = (List) entityManager - .createQuery( - "select " + - " YEAR(p.createdOn) as year, " + - " count(p) as postCount " + - "from Post p " + - "group by " + - " YEAR(p.createdOn) " + - "order by " + - " YEAR(p.createdOn)") - .unwrap(org.hibernate.query.Query.class) - .setResultTransformer( - (ListResultTransformer) (tuple, aliases) -> new PostCountByYear( - ((Number) tuple[0]).intValue(), - ((Number) tuple[1]).intValue() - ) - ) - .getResultList(); - - assertEquals(2016, postCountByYearMap.get(0).getYear()); - assertEquals(2, postCountByYearMap.get(0).getPostCount()); - - assertEquals(2018, postCountByYearMap.get(1).getYear()); - assertEquals(2, postCountByYearMap.get(1).getPostCount()); - - assertEquals(2019, postCountByYearMap.get(2).getYear()); - assertEquals(1, postCountByYearMap.get(2).getPostCount()); - }); - } - - @Entity(name = "Post") - @Table(name = "post") - public static class Post { - - @Id - private Long id; - - private String title; - - @Column(name = "created_on") - private LocalDate createdOn; - - public Long getId() { - return id; - } - - public Post setId(Long id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public Post setTitle(String title) { - this.title = title; - return this; - } - - public LocalDate getCreatedOn() { - return createdOn; - } - - public Post setCreatedOn(LocalDate createdOn) { - this.createdOn = createdOn; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/MapResultTransformerTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/MapResultTransformerTest.java deleted file mode 100644 index 0161cdc7a..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/MapResultTransformerTest.java +++ /dev/null @@ -1,219 +0,0 @@ -package io.hypersistence.utils.hibernate.query; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.junit.Test; - -import javax.persistence.*; -import java.time.LocalDate; -import java.util.Map; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class MapResultTransformerTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Post.class - }; - } - - @Override - public void afterInit() { - doInJPA(entityManager -> { - entityManager.persist( - new Post() - .setId(1L) - .setTitle( - "High-Performance Java Persistence eBook " + - "has been released!" - ) - .setCreatedOn(LocalDate.of(2016, 8, 30)) - ); - - entityManager.persist( - new Post() - .setId(2L) - .setTitle( - "High-Performance Java Persistence paperback " + - "has been released!" - ) - .setCreatedOn(LocalDate.of(2016, 10, 12)) - ); - - entityManager.persist( - new Post() - .setId(3L) - .setTitle( - "High-Performance Java Persistence Mach 1 video course " + - "has been released!" - ) - .setCreatedOn(LocalDate.of(2018, 1, 30)) - ); - - entityManager.persist( - new Post() - .setId(4L) - .setTitle( - "High-Performance Java Persistence Mach 2 video course " + - "has been released!" - ) - .setCreatedOn(LocalDate.of(2018, 5, 8)) - ); - - entityManager.persist( - new Post() - .setId(5L) - .setTitle( - "Hypersistence Optimizer " + - "has been released!" - ) - .setCreatedOn(LocalDate.of(2019, 3, 19)) - ); - }); - } - - @Test - public void testGroupByStreamCollector() { - doInJPA(entityManager -> { - Map postCountByYearMap = entityManager - .createQuery( - "select " + - " YEAR(p.createdOn) as year, " + - " count(p) as postCount " + - "from " + - " Post p " + - "group by " + - " YEAR(p.createdOn)", Tuple.class) - .getResultStream() - .collect( - Collectors.toMap( - tuple -> ((Number) tuple.get("year")).intValue(), - tuple -> ((Number) tuple.get("postCount")).intValue() - ) - ); - - assertEquals(2, postCountByYearMap.get(2016).intValue()); - assertEquals(2, postCountByYearMap.get(2018).intValue()); - assertEquals(1, postCountByYearMap.get(2019).intValue()); - }); - } - - @Test - public void testGroupByListStreamCollector() { - doInJPA(entityManager -> { - Map postCountByYearMap = entityManager - .createQuery( - "select " + - " YEAR(p.createdOn) as year, " + - " count(p) as postCount " + - "from " + - " Post p " + - "group by " + - " YEAR(p.createdOn)", Tuple.class) - .getResultList() - .stream() - .collect( - Collectors.toMap( - tuple -> ((Number) tuple.get("year")).intValue(), - tuple -> ((Number) tuple.get("postCount")).intValue() - ) - ); - - assertEquals(2, postCountByYearMap.get(2016).intValue()); - assertEquals(2, postCountByYearMap.get(2018).intValue()); - assertEquals(1, postCountByYearMap.get(2019).intValue()); - }); - } - - @Test - public void testMapResultTransformerImplicitAlias() { - doInJPA(entityManager -> { - Map postCountByYearMap = (Map) entityManager - .createQuery( - "select " + - " YEAR(p.createdOn) as year, " + - " count(p) as postCount " + - "from " + - " Post p " + - "group by " + - " YEAR(p.createdOn)") - .unwrap(org.hibernate.query.Query.class) - .setResultTransformer( - new MapResultTransformer() - ) - .getSingleResult(); - - assertEquals(2, postCountByYearMap.get(2016).intValue()); - assertEquals(2, postCountByYearMap.get(2018).intValue()); - assertEquals(1, postCountByYearMap.get(2019).intValue()); - }); - } - - @Test - public void testMapResultTransformerExplicitAlias() { - doInJPA(entityManager -> { - Map postCountByYearMap = (Map) entityManager - .createQuery( - "select " + - " count(p) as map_value, " + - " YEAR(p.createdOn) as map_key " + - "from Post p " + - "group by " + - " YEAR(p.createdOn)") - .unwrap(org.hibernate.query.Query.class) - .setResultTransformer( - new MapResultTransformer() - ) - .getSingleResult(); - - assertEquals(2, postCountByYearMap.get(2016).intValue()); - assertEquals(2, postCountByYearMap.get(2018).intValue()); - assertEquals(1, postCountByYearMap.get(2019).intValue()); - }); - } - - @Entity(name = "Post") - @Table(name = "post") - public static class Post { - - @Id - private Long id; - - private String title; - - @Column(name = "created_on") - private LocalDate createdOn; - - public Long getId() { - return id; - } - - public Post setId(Long id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public Post setTitle(String title) { - this.title = title; - return this; - } - - public LocalDate getCreatedOn() { - return createdOn; - } - - public Post setCreatedOn(LocalDate createdOn) { - this.createdOn = createdOn; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/QueryStackTraceLoggerTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/QueryStackTraceLoggerTest.java deleted file mode 100644 index fb70fbe8e..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/QueryStackTraceLoggerTest.java +++ /dev/null @@ -1,151 +0,0 @@ -package io.hypersistence.utils.hibernate.query; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.junit.Test; - -import javax.persistence.*; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Join; -import javax.persistence.criteria.Root; -import java.time.LocalDate; -import java.util.Properties; - -/** - * @author Vlad Mihalcea - */ -public class QueryStackTraceLoggerTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Post.class, - PostComment.class - }; - } - - @Override - protected void additionalProperties(Properties properties) { - properties.put( - "hibernate.session_factory.statement_inspector", - new QueryStackTraceLogger("io.hypersistence.utils.hibernate.query") - ); - } - - @Test - public void testJPQL() { - doInJPA(entityManager -> { - entityManager.createQuery( - "select " + - " YEAR(p.createdOn) as year, " + - " count(p) as postCount " + - "from " + - " Post p " + - "group by " + - " YEAR(p.createdOn)", Tuple.class) - .getResultList(); - }); - } - - @Test - public void testCriteriaAPI() { - doInJPA(entityManager -> { - CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - - CriteriaQuery criteria = builder.createQuery(PostComment.class); - - Root postComment = criteria.from(PostComment.class); - Join post = postComment.join("post"); - - criteria.where( - builder.like(post.get("title"), "%Java%") - ); - - criteria.orderBy( - builder.asc(postComment.get("id")) - ); - - entityManager.createQuery(criteria).getResultList(); - }); - } - - @Entity(name = "Post") - @Table(name = "post") - public static class Post { - - @Id - private Long id; - - private String title; - - @Column(name = "created_on") - private LocalDate createdOn; - - public Long getId() { - return id; - } - - public Post setId(Long id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public Post setTitle(String title) { - this.title = title; - return this; - } - - public LocalDate getCreatedOn() { - return createdOn; - } - - public Post setCreatedOn(LocalDate createdOn) { - this.createdOn = createdOn; - return this; - } - } - - @Entity(name = "PostComment") - @Table(name = "post_comment") - public static class PostComment { - - @Id - private Long id; - - @ManyToOne(fetch = FetchType.LAZY) - private Post post; - - private String review; - - public Long getId() { - return id; - } - - public PostComment setId(Long id) { - this.id = id; - return this; - } - - public Post getPost() { - return post; - } - - public PostComment setPost(Post post) { - this.post = post; - return this; - } - - public String getReview() { - return review; - } - - public PostComment setReview(String review) { - this.review = review; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/SQLExtractorTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/SQLExtractorTest.java deleted file mode 100644 index 3b092da9a..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/query/SQLExtractorTest.java +++ /dev/null @@ -1,164 +0,0 @@ -package io.hypersistence.utils.hibernate.query; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.junit.Test; - -import javax.persistence.*; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Join; -import javax.persistence.criteria.Root; -import java.time.LocalDate; - -import static org.junit.Assert.assertNotNull; - -/** - * @author Vlad Mihalcea - */ -public class SQLExtractorTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Post.class, - PostComment.class - }; - } - - @Test - public void testJPQL() { - doInJPA(entityManager -> { - Query jpql = entityManager - .createQuery( - "select " + - " YEAR(p.createdOn) as year, " + - " count(p) as postCount " + - "from " + - " Post p " + - "group by " + - " YEAR(p.createdOn)", Tuple.class); - - String sql = SQLExtractor.from(jpql); - - assertNotNull(sql); - - LOGGER.info( - "The JPQL query: [\n{}\n]\ngenerates the following SQL query: [\n{}\n]", - jpql.unwrap(org.hibernate.query.Query.class).getQueryString(), - sql - ); - }); - } - - @Test - public void testCriteriaAPI() { - doInJPA(entityManager -> { - CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - - CriteriaQuery criteria = builder.createQuery(PostComment.class); - - Root postComment = criteria.from(PostComment.class); - Join post = postComment.join("post"); - - criteria.where( - builder.like(post.get("title"), "%Java%") - ); - - criteria.orderBy( - builder.asc(postComment.get("id")) - ); - - Query criteriaQuery = entityManager.createQuery(criteria); - - String sql = SQLExtractor.from(criteriaQuery); - - assertNotNull(sql); - - LOGGER.info( - "The Criteria API query: [\n{}\n]\ngenerates the following SQL query: [\n{}\n]", - criteriaQuery.unwrap(org.hibernate.query.Query.class).getQueryString(), - sql - ); - }); - } - - @Entity(name = "Post") - @Table(name = "post") - public static class Post { - - @Id - private Long id; - - private String title; - - @Column(name = "created_on") - private LocalDate createdOn; - - public Long getId() { - return id; - } - - public Post setId(Long id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public Post setTitle(String title) { - this.title = title; - return this; - } - - public LocalDate getCreatedOn() { - return createdOn; - } - - public Post setCreatedOn(LocalDate createdOn) { - this.createdOn = createdOn; - return this; - } - } - - @Entity(name = "PostComment") - @Table(name = "post_comment") - public static class PostComment { - - @Id - private Long id; - - @ManyToOne(fetch = FetchType.LAZY) - private Post post; - - private String review; - - public Long getId() { - return id; - } - - public PostComment setId(Long id) { - this.id = id; - return this; - } - - public Post getPost() { - return post; - } - - public PostComment setPost(Post post) { - this.post = post; - return this; - } - - public String getReview() { - return review; - } - - public PostComment setReview(String review) { - this.review = review; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ArrayTypeNativeQueryTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ArrayTypeNativeQueryTest.java deleted file mode 100644 index 3d159b037..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ArrayTypeNativeQueryTest.java +++ /dev/null @@ -1,159 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.Parameter; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class ArrayTypeNativeQueryTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Override - protected List additionalTypes() { - return Arrays.asList( - StringArrayType.INSTANCE, - IntArrayType.INSTANCE - ); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorNames(new String[]{"Temperature", "Pressure"}); - event.setSensorValues(new int[]{12, 756}); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - List events = entityManager - .createNamedQuery("EventIdSensorValues", EventSensors.class) - .getResultList(); - - assertEquals(2, events.size()); - }); - } - - @Entity(name = "Event") - @TypeDef(name = "sensor-state-array", typeClass = EnumArrayType.class, parameters = { - @Parameter(name = AbstractArrayType.SQL_ARRAY_TYPE, value = "sensor_state")} - ) - @Table(name = "event") - @NamedNativeQuery( - name = "EventIdSensorValues", - query = "select " + - " id, " + - " sensor_names, " + - " sensor_values " + - "from event ", - resultSetMapping = "EventIdSensorValues" - ) - @SqlResultSetMapping( - name = "EventIdSensorValues", - classes = @ConstructorResult( - targetClass = EventSensors.class, - columns = { - @ColumnResult( - name = "id", - type = Long.class - ), - @ColumnResult( - name = "sensor_names", - type = String[].class - ), - @ColumnResult( - name = "sensor_values", - type = int[].class - ) - } - ) - ) - public static class Event extends BaseEntity { - - @Type(type = "string-array") - @Column(name = "sensor_names", columnDefinition = "text[]") - private String[] sensorNames; - - @Type(type = "int-array") - @Column(name = "sensor_values", columnDefinition = "integer[]") - private int[] sensorValues; - - public String[] getSensorNames() { - return sensorNames; - } - - public void setSensorNames(String[] sensorNames) { - this.sensorNames = sensorNames; - } - - public int[] getSensorValues() { - return sensorValues; - } - - public void setSensorValues(int[] sensorValues) { - this.sensorValues = sensorValues; - } - } - - public static class EventSensors { - - private Long id; - - private String[] sensorNames; - - private int[] sensorValues; - - public EventSensors(Long id, String[] sensorNames, int[] sensorValues) { - this.id = id; - this.sensorNames = sensorNames; - this.sensorValues = sensorValues; - } - - public Long getId() { - return id; - } - - public String[] getSensorNames() { - return sensorNames; - } - - public int[] getSensorValues() { - return sensorValues; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ArrayTypeTest.java deleted file mode 100644 index 84db63dc9..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ArrayTypeTest.java +++ /dev/null @@ -1,332 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.Parameter; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Tuple; -import javax.sql.DataSource; -import java.math.BigDecimal; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - * @author Guillaume Briand - */ -public class ArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - public void init() { - DataSource dataSource = newDataSource(); - try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { - try { - statement.executeUpdate( - "DROP TYPE sensor_state CASCADE" - ); - } catch (SQLException ignore) { - } - statement.executeUpdate( - "CREATE TYPE sensor_state AS ENUM ('ONLINE', 'OFFLINE', 'UNKNOWN')" - ); - statement.executeUpdate( - "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"" - ); - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Test - public void test() { - - Date date1 = Date.from(LocalDate.of(1991, 12, 31).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); - Date date2 = Date.from(LocalDate.of(1990, 1, 1).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorIds(new UUID[]{UUID.fromString("c65a3bcb-8b36-46d4-bddb-ae96ad016eb1"), UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800")}); - event.setSensorNames(new String[]{"Temperature", "Pressure"}); - event.setSensorValues(new int[]{12, 756}); - event.setSensorLongValues(new long[]{42L, 9223372036854775800L}); - event.setSensorDoubleValues(new double[]{0.123, 456.789}); - event.setSensorFloatValues(new float[]{1.2f, 4.35f}); - event.setSensorStates(new SensorState[]{SensorState.ONLINE, SensorState.OFFLINE, SensorState.ONLINE, SensorState.UNKNOWN}); - event.setDateValues(new Date[]{date1, date2}); - event.setTimestampValues(new Date[]{date1, date2}); - event.setDecimalValues(new BigDecimal[]{BigDecimal.ONE, BigDecimal.ZERO, BigDecimal.TEN}); - event.setLocalDateValues(new LocalDate[]{LocalDate.of(2022, 3, 22), LocalDate.of(2021, 4, 21)}); - event.setLocalDateTimeValues(new LocalDateTime[]{LocalDateTime.of(2022, 3, 22, 11, 22, 33), LocalDateTime.of(2021, 4, 21, 22, 33, 44)}); - event.setSensorBooleanValues(new Boolean[]{false, true, true}); - - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new UUID[]{UUID.fromString("c65a3bcb-8b36-46d4-bddb-ae96ad016eb1"), UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800")}, event.getSensorIds()); - assertArrayEquals(new String[]{"Temperature", "Pressure"}, event.getSensorNames()); - assertArrayEquals(new int[]{12, 756}, event.getSensorValues()); - assertArrayEquals(new long[]{42L, 9223372036854775800L}, event.getSensorLongValues()); - assertArrayEquals(new double[]{0.123, 456.789}, event.getSensorDoubleValues(), 0.01); - assertArrayEquals(new float[]{1.2f, 4.35f}, event.getSensorFloatValues(), 0.01f); - assertArrayEquals(new SensorState[]{SensorState.ONLINE, SensorState.OFFLINE, SensorState.ONLINE, SensorState.UNKNOWN}, event.getSensorStates()); - assertArrayEquals(new Date[]{date1, date2}, event.getDateValues()); - assertArrayEquals(new Date[]{date1, date2}, event.getTimestampValues()); - assertArrayEquals(new BigDecimal[]{BigDecimal.ONE, BigDecimal.ZERO, BigDecimal.TEN}, event.getDecimalValues()); - assertArrayEquals(new LocalDate[]{LocalDate.of(2022, 3, 22), LocalDate.of(2021, 4, 21)}, event.getLocalDateValues()); - assertArrayEquals(new LocalDateTime[]{LocalDateTime.of(2022, 3, 22, 11, 22, 33), LocalDateTime.of(2021, 4, 21, 22, 33, 44)}, event.getLocalDateTimeValues()); - assertArrayEquals(new Boolean[]{false, true, true}, event.getSensorBooleanValues()); - }); - - doInJPA(entityManager -> { - List events = entityManager.createNativeQuery( - "select " + - " id, " + - " sensor_ids, " + - " sensor_names, " + - " sensor_values, " + - " date_values " + - "from event ", Tuple.class) - .unwrap(org.hibernate.query.NativeQuery.class) - .addScalar("sensor_ids", UUIDArrayType.INSTANCE) - .addScalar("sensor_names", StringArrayType.INSTANCE) - .addScalar("sensor_values", IntArrayType.INSTANCE) - .addScalar("date_values", DateArrayType.INSTANCE) - .getResultList(); - - assertEquals(2, events.size()); - }); - } - - @Test - public void testLargeArray() { - int[] sensorValues = new int[100]; - - Arrays.fill(sensorValues, 0, 10, 123); - Arrays.fill(sensorValues, 10, 50, 456); - Arrays.fill(sensorValues, 50, 90, 789); - Arrays.fill(sensorValues, 90, 100, 0); - - doInJPA(entityManager -> { - Event event = new Event(); - event.setId(0L); - event.setSensorValues(sensorValues); - - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 0L); - - assertArrayEquals(sensorValues, event.getSensorValues()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - @TypeDef(name = "sensor-state-array", typeClass = EnumArrayType.class, parameters = { - @Parameter(name = AbstractArrayType.SQL_ARRAY_TYPE, value = "sensor_state")} - ) - public static class Event extends BaseEntity { - @Type(type = "uuid-array") - @Column(name = "sensor_ids", columnDefinition = "uuid[]") - private UUID[] sensorIds; - - @Type(type = "string-array") - @Column(name = "sensor_names", columnDefinition = "text[]") - private String[] sensorNames; - - @Type(type = "int-array") - @Column(name = "sensor_values", columnDefinition = "integer[]") - private int[] sensorValues; - - @Type(type = "long-array") - @Column(name = "sensor_long_values", columnDefinition = "bigint[]") - private long[] sensorLongValues; - - @Type(type = "boolean-array") - @Column(name = "sensor_boolean_values", columnDefinition = "boolean[]") - private Boolean[] sensorBooleanValues; - - @Type(type = "double-array") - @Column(name = "sensor_double_values", columnDefinition = "float8[]") - private double[] sensorDoubleValues; - - @Type(type = "float-array") - @Column(name = "sensor_float_values", columnDefinition = "float4[]") - private float[] sensorFloatValues; - - @Type(type = "date-array") - @Column(name = "date_values", columnDefinition = "date[]") - private Date[] dateValues; - - @Type(type = "timestamp-array") - @Column(name = "timestamp_values", columnDefinition = "timestamp[]") - private Date[] timestampValues; - - @Type(type = "decimal-array") - @Column(name = "decimal_values", columnDefinition = "decimal[]") - private BigDecimal[] decimalValues; - - @Type(type = "localdate-array") - @Column(name = "localdate_values", columnDefinition = "date[]") - private LocalDate[] localDateValues; - - @Type(type = "localdatetime-array") - @Column(name = "localdatetime_values", columnDefinition = "timestamp[]") - private LocalDateTime[] localDateTimeValues; - - @Type(type = "sensor-state-array") - @Column(name = "sensor_states", columnDefinition = "sensor_state[]") - private SensorState[] sensorStates; - - public UUID[] getSensorIds() { - return sensorIds; - } - - public void setSensorIds(UUID[] sensorIds) { - this.sensorIds = sensorIds; - } - - public String[] getSensorNames() { - return sensorNames; - } - - public void setSensorNames(String[] sensorNames) { - this.sensorNames = sensorNames; - } - - public int[] getSensorValues() { - return sensorValues; - } - - public void setSensorValues(int[] sensorValues) { - this.sensorValues = sensorValues; - } - - public long[] getSensorLongValues() { - return sensorLongValues; - } - - public void setSensorLongValues(long[] sensorLongValues) { - this.sensorLongValues = sensorLongValues; - } - - public Boolean[] getSensorBooleanValues() { return sensorBooleanValues; } - - public void setSensorBooleanValues(Boolean[] sensorBooleanValues) { this.sensorBooleanValues = sensorBooleanValues; } - - public double[] getSensorDoubleValues() { - return sensorDoubleValues; - } - - public void setSensorDoubleValues(double[] sensorDoubleValues) { - this.sensorDoubleValues = sensorDoubleValues; - } - - public float[] getSensorFloatValues() { - return sensorFloatValues; - } - - public void setSensorFloatValues(float[] sensorFloatValues) { - this.sensorFloatValues = sensorFloatValues; - } - - public SensorState[] getSensorStates() { - return sensorStates; - } - - public void setSensorStates(SensorState[] sensorStates) { - this.sensorStates = sensorStates; - } - - public Date[] getDateValues() { - return dateValues; - } - - public void setDateValues(Date[] dateValues) { - this.dateValues = dateValues; - } - - public Date[] getTimestampValues() { - return timestampValues; - } - - public void setTimestampValues(Date[] timestampValues) { - this.timestampValues = timestampValues; - } - - public BigDecimal[] getDecimalValues() { - return decimalValues; - } - - public void setDecimalValues(BigDecimal[] decimalValues) { - this.decimalValues = decimalValues; - } - - public LocalDate[] getLocalDateValues() { - return localDateValues; - } - - public void setLocalDateValues(LocalDate[] localDateValues) { - this.localDateValues = localDateValues; - } - - public LocalDateTime[] getLocalDateTimeValues() { - return localDateTimeValues; - } - - public void setLocalDateTimeValues(LocalDateTime[] localDateTimeValues) { - this.localDateTimeValues = localDateTimeValues; - } - } - - public enum SensorState { - ONLINE, OFFLINE, UNKNOWN; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/BindArrayTypeQueryParameterTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/BindArrayTypeQueryParameterTest.java deleted file mode 100644 index efac29f36..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/BindArrayTypeQueryParameterTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.ExceptionUtil; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.TypeDef; -import org.hibernate.jpa.TypedParameterValue; -import org.hibernate.query.Query; -import org.junit.Test; - -import javax.persistence.*; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.ParameterExpression; -import javax.persistence.criteria.Root; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - -import static org.junit.Assert.*; - -/** - * @author Stanislav Gubanov - */ -public class BindArrayTypeQueryParameterTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - public void init() { - DataSource dataSource = newDataSource(); - try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { - statement.executeUpdate( - "CREATE OR REPLACE FUNCTION " + - " fn_array_contains(" + - " left_array integer[], " + - " right_array integer[]" + - ") RETURNS " + - " boolean AS " + - "$$ " + - "BEGIN " + - " return left_array @> right_array; " + - "END; " + - "$$ LANGUAGE 'plpgsql';" - ); - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - Event event = new Event(); - event.setId(1L); - event.setName("Temperature"); - event.setValues(new int[]{1, 2, 3}); - entityManager.persist(event); - }); - } - - @Test - public void testJPQLWithDefaultParameterBiding() { - try { - doInJPA(entityManager -> { - Event event = entityManager - .createQuery( - "select e " + - "from Event e " + - "where " + - " fn_array_contains(e.values, :arrayValues) = true", Event.class) - .setParameter("arrayValues", new int[]{2, 3}) - .getSingleResult(); - }); - } catch (Exception e) { - Exception rootCause = ExceptionUtil.rootCause(e); - assertTrue(rootCause.getMessage().contains("ERROR: function fn_array_contains(integer[], bytea) does not exist")); - } - } - - @Test - public void testJPQLWithExplicitParameterTypeBinding() { - doInJPA(entityManager -> { - Event event = (Event) entityManager - .createQuery( - "select e " + - "from Event e " + - "where " + - " fn_array_contains(e.values, :arrayValues) = true", Event.class) - .unwrap(org.hibernate.query.Query.class) - .setParameter("arrayValues", new int[]{2, 3}, IntArrayType.INSTANCE) - .getSingleResult(); - - assertArrayEquals(new int[]{1, 2, 3}, event.getValues()); - }); - } - - @Test - public void testJPQLWithTypedParameterValue() { - doInJPA(entityManager -> { - Event event = entityManager - .createQuery( - "select e " + - "from Event e " + - "where " + - " fn_array_contains(e.values, :arrayValues) = true", Event.class) - .setParameter("arrayValues", new TypedParameterValue(IntArrayType.INSTANCE, new int[]{2, 3})) - .getSingleResult(); - - assertArrayEquals(new int[]{1, 2, 3}, event.getValues()); - }); - } - - @Test - public void testCriteriaAPI() { - doInJPA(entityManager -> { - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(Event.class); - Root root = cq.from(Event.class); - cq.select(root); - - ParameterExpression containValues = cb.parameter(int[].class, "arrayValues"); - cq.where( - cb.equal( - cb.function( - "fn_array_contains", - Boolean.class, - root.get("values"), containValues - ), - Boolean.TRUE - ) - ); - - Event event = (Event) entityManager - .createQuery(cq) - .unwrap(Query.class) - .setParameter("arrayValues", new int[]{2, 3}, IntArrayType.INSTANCE) - .getSingleResult(); - - assertArrayEquals(new int[]{1, 2, 3}, event.getValues()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - @TypeDef( - typeClass = IntArrayType.class, - defaultForType = int[].class - ) - public static class Event { - - @Id - private Long id; - - private String name; - - @Column( - name = "event_values", - columnDefinition = "integer[]" - ) - private int[] values; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int[] getValues() { - return values; - } - - public void setValues(int[] values) { - this.values = values; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/DefaultEmptyListArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/DefaultEmptyListArrayTypeTest.java deleted file mode 100644 index 9e6a0a4f7..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/DefaultEmptyListArrayTypeTest.java +++ /dev/null @@ -1,189 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.Parameter; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class DefaultEmptyListArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - public void init() { - DataSource dataSource = newDataSource(); - try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { - try { - statement.executeUpdate( - "DROP TYPE sensor_state CASCADE" - ); - } catch (SQLException ignore) { - } - statement.executeUpdate( - "CREATE TYPE sensor_state AS ENUM ('ONLINE', 'OFFLINE', 'UNKNOWN')" - ); - statement.executeUpdate( - "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"" - ); - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Test - public void testEmptyArrays() { - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new UUID[]{}, event.getSensorIds().toArray()); - assertArrayEquals(new String[]{}, event.getSensorNames().toArray()); - assertArrayEquals(new Integer[]{}, event.getSensorValues().toArray()); - assertArrayEquals(new Long[]{}, event.getSensorLongValues().toArray()); - assertArrayEquals(new SensorState[]{}, event.getSensorStates().toArray()); - assertArrayEquals(new Date[]{}, event.getDateValues().toArray()); - assertArrayEquals(new Date[]{}, event.getTimestampValues().toArray()); - }); - } - - @Entity(name = "Event") - @TypeDef(name = "list-array", typeClass = ListArrayType.class) - @TypeDef(name = "sensor-state-array", typeClass = ListArrayType.class, parameters = { - @Parameter(name = ListArrayType.SQL_ARRAY_TYPE, value = "sensor_state")} - ) - @Table(name = "event") - public static class Event extends BaseEntity { - @Type(type = "list-array") - @Column(name = "sensor_ids", columnDefinition = "uuid[]") - private List sensorIds = new ArrayList<>(); - - @Type(type = "list-array") - @Column(name = "sensor_names", columnDefinition = "text[]") - private List sensorNames = new ArrayList<>();; - - @Type(type = "list-array") - @Column(name = "sensor_values", columnDefinition = "integer[]") - private List sensorValues = new ArrayList<>();; - - @Type(type = "list-array") - @Column(name = "sensor_long_values", columnDefinition = "bigint[]") - private List sensorLongValues = new ArrayList<>();; - - @Type(type = "sensor-state-array") - @Column(name = "sensor_states", columnDefinition = "sensor_state[]") - private List sensorStates = new ArrayList<>();; - - @Type(type = "list-array") - @Column(name = "date_values", columnDefinition = "date[]") - private List dateValues = new ArrayList<>();; - - @Type(type = "list-array") - @Column(name = "timestamp_values", columnDefinition = "timestamp[]") - private List timestampValues = new ArrayList<>();; - - public List getSensorIds() { - return sensorIds; - } - - public void setSensorIds(List sensorIds) { - this.sensorIds = sensorIds; - } - - public List getSensorNames() { - return sensorNames; - } - - public void setSensorNames(List sensorNames) { - this.sensorNames = sensorNames; - } - - public List getSensorValues() { - return sensorValues; - } - - public void setSensorValues(List sensorValues) { - this.sensorValues = sensorValues; - } - - public List getSensorLongValues() { - return sensorLongValues; - } - - public void setSensorLongValues(List sensorLongValues) { - this.sensorLongValues = sensorLongValues; - } - - public List getSensorStates() { - return sensorStates; - } - - public void setSensorStates(List sensorStates) { - this.sensorStates = sensorStates; - } - - public List getDateValues() { - return dateValues; - } - - public void setDateValues(List dateValues) { - this.dateValues = dateValues; - } - - public List getTimestampValues() { - return timestampValues; - } - - public void setTimestampValues(List timestampValues) { - this.timestampValues = timestampValues; - } - } - - public enum SensorState { - ONLINE, OFFLINE, UNKNOWN; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/EhcacheListArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/EhcacheListArrayTypeTest.java deleted file mode 100644 index 1106c3a78..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/EhcacheListArrayTypeTest.java +++ /dev/null @@ -1,351 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.annotations.Parameter; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class EhcacheListArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - protected void additionalProperties(Properties properties) { - properties.setProperty("hibernate.cache.use_second_level_cache", "true"); - properties.setProperty("hibernate.cache.use_query_cache", "true"); - properties.setProperty("hibernate.cache.region.factory_class", "ehcache"); - } - - @Override - public void init() { - DataSource dataSource = newDataSource(); - try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { - try { - statement.executeUpdate( - "DROP TYPE sensor_state CASCADE" - ); - } catch (SQLException ignore) { - } - statement.executeUpdate( - "CREATE TYPE sensor_state AS ENUM ('ONLINE', 'OFFLINE', 'UNKNOWN')" - ); - statement.executeUpdate( - "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"" - ); - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Test - public void test() { - - Date date1 = Date.from(LocalDate.of(1991, 12, 31).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); - Date date2 = Date.from(LocalDate.of(1990, 1, 1).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorIds(Arrays.asList(UUID.fromString("c65a3bcb-8b36-46d4-bddb-ae96ad016eb1"), UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800"))); - event.setSensorNames(Arrays.asList("Temperature", "Pressure")); - event.setSensorValues(Arrays.asList(12, 756)); - event.setSensorLongValues(Arrays.asList(42L, 9223372036854775800L)); - event.setSensorStates(Arrays.asList(SensorState.ONLINE, SensorState.OFFLINE, SensorState.ONLINE, SensorState.UNKNOWN)); - event.setDateValues(Arrays.asList(date1, date2)); - event.setTimestampValues(Arrays.asList(date1, date2)); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new UUID[]{UUID.fromString("c65a3bcb-8b36-46d4-bddb-ae96ad016eb1"), UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800")}, event.getSensorIds().toArray()); - assertArrayEquals(new String[]{"Temperature", "Pressure"}, event.getSensorNames().toArray()); - assertArrayEquals(new Integer[]{12, 756}, event.getSensorValues().toArray()); - assertArrayEquals(new Long[]{42L, 9223372036854775800L}, event.getSensorLongValues().toArray()); - assertArrayEquals(new SensorState[]{SensorState.ONLINE, SensorState.OFFLINE, SensorState.ONLINE, SensorState.UNKNOWN}, event.getSensorStates().toArray()); - assertArrayEquals(new Date[]{date1, date2}, event.getDateValues().toArray()); - assertArrayEquals(new Date[]{date1, date2}, event.getTimestampValues().toArray()); - }); - - doInJPA(entityManager -> { - List events = entityManager.createNativeQuery( - "select " + - " id, " + - " sensor_ids, " + - " sensor_names, " + - " sensor_values " + - "from event ", Tuple.class) - .unwrap(org.hibernate.query.NativeQuery.class) - .addScalar("sensor_ids", UUIDArrayType.INSTANCE) - .addScalar("sensor_names", StringArrayType.INSTANCE) - .addScalar("sensor_values", IntArrayType.INSTANCE) - .getResultList(); - - assertEquals(2, events.size()); - }); - } - - @Test - public void testMixingNullValues() { - - Date date = Date.from(LocalDate.of(1990, 1, 1).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorIds(Arrays.asList(null, UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800"))); - event.setSensorNames(Arrays.asList("Temperature", null)); - event.setSensorValues(Arrays.asList(null, 756)); - event.setSensorLongValues(Arrays.asList(null, 9223372036854775800L)); - event.setSensorStates(Arrays.asList(null, SensorState.OFFLINE, SensorState.ONLINE, null)); - event.setDateValues(Arrays.asList(null, date)); - event.setTimestampValues(Arrays.asList(null, date)); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new UUID[]{null, UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800")}, event.getSensorIds().toArray()); - assertArrayEquals(new String[]{"Temperature", null}, event.getSensorNames().toArray()); - assertArrayEquals(new Integer[]{null, 756}, event.getSensorValues().toArray()); - assertArrayEquals(new Long[]{null, 9223372036854775800L}, event.getSensorLongValues().toArray()); - assertArrayEquals(new SensorState[]{null, SensorState.OFFLINE, SensorState.ONLINE, null}, event.getSensorStates().toArray()); - assertArrayEquals(new Date[]{null, date}, event.getDateValues().toArray()); - assertArrayEquals(new Date[]{null, date}, event.getTimestampValues().toArray()); - }); - } - - @Test - public void testNullValues() { - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorIds(Arrays.asList(null, null)); - event.setSensorNames(Arrays.asList(null, null)); - event.setSensorValues(Arrays.asList(null, null)); - event.setSensorLongValues(Arrays.asList(null, null)); - event.setSensorStates(Arrays.asList(null, null)); - event.setDateValues(Arrays.asList(null, null)); - event.setTimestampValues(Arrays.asList(null, null)); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new UUID[]{null, null}, event.getSensorIds().toArray()); - assertArrayEquals(new String[]{null, null}, event.getSensorNames().toArray()); - assertArrayEquals(new Integer[]{null, null}, event.getSensorValues().toArray()); - assertArrayEquals(new Long[]{null, null}, event.getSensorLongValues().toArray()); - assertArrayEquals(new SensorState[]{null, null}, event.getSensorStates().toArray()); - assertArrayEquals(new Date[]{null, null}, event.getDateValues().toArray()); - assertArrayEquals(new Date[]{null, null}, event.getTimestampValues().toArray()); - }); - } - - @Test - public void testEmptyArrays() { - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorIds(Collections.emptyList()); - event.setSensorNames(Collections.emptyList()); - event.setSensorValues(Collections.emptyList()); - event.setSensorLongValues(Collections.emptyList()); - event.setSensorStates(Collections.emptyList()); - event.setDateValues(Collections.emptyList()); - event.setTimestampValues(Collections.emptyList()); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new UUID[]{}, event.getSensorIds().toArray()); - assertArrayEquals(new String[]{}, event.getSensorNames().toArray()); - assertArrayEquals(new Integer[]{}, event.getSensorValues().toArray()); - assertArrayEquals(new Long[]{}, event.getSensorLongValues().toArray()); - assertArrayEquals(new SensorState[]{}, event.getSensorStates().toArray()); - assertArrayEquals(new Date[]{}, event.getDateValues().toArray()); - assertArrayEquals(new Date[]{}, event.getTimestampValues().toArray()); - }); - } - - @Test - public void testNullArrays() { - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertEquals(null, event.getSensorIds()); - assertEquals(null, event.getSensorNames()); - assertEquals(null, event.getSensorLongValues()); - assertEquals(null, event.getSensorStates()); - assertEquals(null, event.getDateValues()); - assertEquals(null, event.getTimestampValues()); - }); - } - - @Entity(name = "Event") - @TypeDef(name = "list-array", typeClass = ListArrayType.class) - @TypeDef(name = "sensor-state-array", typeClass = ListArrayType.class, parameters = { - @Parameter(name = ListArrayType.SQL_ARRAY_TYPE, value = "sensor_state")} - ) - @Table(name = "event") - @Cacheable - @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - public static class Event extends BaseEntity { - @Type(type = "list-array") - @Column(name = "sensor_ids", columnDefinition = "uuid[]") - private List sensorIds; - - @Type(type = "list-array") - @Column(name = "sensor_names", columnDefinition = "text[]") - private List sensorNames; - - @Type(type = "list-array") - @Column(name = "sensor_values", columnDefinition = "integer[]") - private List sensorValues; - - @Type(type = "list-array") - @Column(name = "sensor_long_values", columnDefinition = "bigint[]") - private List sensorLongValues; - - @Type(type = "sensor-state-array") - @Column(name = "sensor_states", columnDefinition = "sensor_state[]") - private List sensorStates; - - @Type(type = "list-array") - @Column(name = "date_values", columnDefinition = "date[]") - private List dateValues; - - @Type(type = "list-array") - @Column(name = "timestamp_values", columnDefinition = "timestamp[]") - private List timestampValues; - - public List getSensorIds() { - return sensorIds; - } - - public void setSensorIds(List sensorIds) { - this.sensorIds = sensorIds; - } - - public List getSensorNames() { - return sensorNames; - } - - public void setSensorNames(List sensorNames) { - this.sensorNames = sensorNames; - } - - public List getSensorValues() { - return sensorValues; - } - - public void setSensorValues(List sensorValues) { - this.sensorValues = sensorValues; - } - - public List getSensorLongValues() { - return sensorLongValues; - } - - public void setSensorLongValues(List sensorLongValues) { - this.sensorLongValues = sensorLongValues; - } - - public List getSensorStates() { - return sensorStates; - } - - public void setSensorStates(List sensorStates) { - this.sensorStates = sensorStates; - } - - public List getDateValues() { - return dateValues; - } - - public void setDateValues(List dateValues) { - this.dateValues = dateValues; - } - - public List getTimestampValues() { - return timestampValues; - } - - public void setTimestampValues(List timestampValues) { - this.timestampValues = timestampValues; - } - } - - public enum SensorState { - ONLINE, OFFLINE, UNKNOWN; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/HSQLDBArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/HSQLDBArrayTypeTest.java deleted file mode 100644 index b1597b809..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/HSQLDBArrayTypeTest.java +++ /dev/null @@ -1,201 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractTest; -import org.hibernate.annotations.Parameter; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.annotations.TypeDefs; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Tuple; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.Date; -import java.util.List; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class HSQLDBArrayTypeTest extends AbstractTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Test - public void test() { - - Date date1 = Date.from(LocalDate.of(1991, 12, 31).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); - Date date2 = Date.from(LocalDate.of(1990, 1, 1).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorNames(new String[]{"Temperature", "Pressure"}); - event.setSensorValues(new int[]{12, 756}); - event.setSensorLongValues(new long[]{42L, 9223372036854775800L}); - event.setSensorDoubleValues(new double[]{0.123, 456.789}); - event.setSensorFloatValues(new float[]{1.23f, 45.789f}); - event.setDateValues(new Date[]{date1, date2}); - event.setTimestampValues(new Date[]{date1, date2}); - - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new String[]{"Temperature", "Pressure"}, event.getSensorNames()); - assertArrayEquals(new int[]{12, 756}, event.getSensorValues()); - assertArrayEquals(new long[]{42L, 9223372036854775800L}, event.getSensorLongValues()); - assertArrayEquals(new double[]{0.123, 456.789}, event.getSensorDoubleValues(), 0.01); - assertArrayEquals(new float[]{1.23f, 45.789f}, event.getSensorFloatValues(), 0.01f); - assertArrayEquals(new Date[]{date1, date2}, event.getDateValues()); - assertArrayEquals(new Date[]{date1, date2}, event.getTimestampValues()); - }); - - doInJPA(entityManager -> { - List events = entityManager.createNativeQuery( - "select " + - " id, " + - " sensor_names, " + - " sensor_values, " + - " date_values " + - "from event ", Tuple.class) - .unwrap(org.hibernate.query.NativeQuery.class) - .addScalar("sensor_names", StringArrayType.INSTANCE) - .addScalar("sensor_values", IntArrayType.INSTANCE) - .addScalar("date_values", DateArrayType.INSTANCE) - .getResultList(); - - assertEquals(2, events.size()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - @TypeDefs({ - @TypeDef( - name = "hsqldb-double-array", - typeClass = DoubleArrayType.class, - parameters = { - @Parameter(name = AbstractArrayType.SQL_ARRAY_TYPE, value = "double") - } - ), - @TypeDef( - name = "hsqldb-float-array", - typeClass = FloatArrayType.class, - parameters = { - @Parameter(name = AbstractArrayType.SQL_ARRAY_TYPE, value = "float") - } - ), - @TypeDef( - name = "hsqldb-string-array", - typeClass = StringArrayType.class, - parameters = { - @Parameter(name = AbstractArrayType.SQL_ARRAY_TYPE, value = "varchar") - } - ) - }) - public static class Event extends BaseEntity { - - @Type(type = "hsqldb-string-array") - @Column(name = "sensor_names", columnDefinition = "VARCHAR(20) ARRAY[10]") - private String[] sensorNames; - - @Type(type = "int-array") - @Column(name = "sensor_values", columnDefinition = "INT ARRAY DEFAULT ARRAY[]") - private int[] sensorValues; - - @Type(type = "long-array") - @Column(name = "sensor_long_values", columnDefinition = "BIGINT ARRAY DEFAULT ARRAY[]") - private long[] sensorLongValues; - - @Type(type = "hsqldb-double-array") - @Column(name = "sensor_double_values", columnDefinition = "DOUBLE ARRAY DEFAULT ARRAY[]") - private double[] sensorDoubleValues; - - @Type(type = "hsqldb-float-array") - @Column(name = "sensor_float_values", columnDefinition = "FLOAT ARRAY DEFAULT ARRAY[]") - private float[] sensorFloatValues; - - @Type(type = "date-array") - @Column(name = "date_values", columnDefinition = "DATE ARRAY DEFAULT ARRAY[]") - private Date[] dateValues; - - @Type(type = "timestamp-array") - @Column(name = "timestamp_values", columnDefinition = "TIMESTAMP ARRAY DEFAULT ARRAY[]") - private Date[] timestampValues; - - public String[] getSensorNames() { - return sensorNames; - } - - public void setSensorNames(String[] sensorNames) { - this.sensorNames = sensorNames; - } - - public int[] getSensorValues() { - return sensorValues; - } - - public void setSensorValues(int[] sensorValues) { - this.sensorValues = sensorValues; - } - - public long[] getSensorLongValues() { - return sensorLongValues; - } - - public void setSensorLongValues(long[] sensorLongValues) { - this.sensorLongValues = sensorLongValues; - } - - public double[] getSensorDoubleValues() { - return sensorDoubleValues; - } - - public void setSensorDoubleValues(double[] sensorDoubleValues) { - this.sensorDoubleValues = sensorDoubleValues; - } - - public float[] getSensorFloatValues() { - return sensorFloatValues; - } - - public void setSensorFloatValues(float[] sensorFloatValues) { - this.sensorFloatValues = sensorFloatValues; - } - - public Date[] getDateValues() { - return dateValues; - } - - public void setDateValues(Date[] dateValues) { - this.dateValues = dateValues; - } - - public Date[] getTimestampValues() { - return timestampValues; - } - - public void setTimestampValues(Date[] timestampValues) { - this.timestampValues = timestampValues; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ListArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ListArrayTypeTest.java deleted file mode 100644 index 936c9eefc..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/ListArrayTypeTest.java +++ /dev/null @@ -1,689 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.Parameter; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import javax.sql.DataSource; -import java.math.BigDecimal; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class ListArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - public void init() { - DataSource dataSource = newDataSource(); - try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { - try { - statement.executeUpdate( - "DROP TYPE sensor_state CASCADE" - ); - } catch (SQLException ignore) { - } - statement.executeUpdate( - "CREATE TYPE sensor_state AS ENUM ('ONLINE', 'OFFLINE', 'UNKNOWN')" - ); - statement.executeUpdate( - "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"" - ); - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Test - public void test() { - - doInJPA(entityManager -> { - entityManager.persist( - new Event() - .setId(0L) - ); - - entityManager.persist( - new Event() - .setId(1L) - .setSensorIds( - Arrays.asList( - UUID.fromString("c65a3bcb-8b36-46d4-bddb-ae96ad016eb1"), - UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800") - ) - ) - .setSensorNames(Arrays.asList("Temperature", "Pressure")) - .setSensorValues(Arrays.asList(12, 756)) - .setSensorLongValues(Arrays.asList(42L, 9223372036854775800L)) - .setSensorBooleanValues(Arrays.asList(true, false)) - .setSensorDoubleValues(Arrays.asList(0.123D, 456.789D)) - .setSensorStates( - Arrays.asList( - SensorState.ONLINE, SensorState.OFFLINE, - SensorState.ONLINE, SensorState.UNKNOWN - ) - ) - .setDateValues( - Arrays.asList( - java.sql.Date.valueOf(LocalDate.of(1991, 12, 31)), - java.sql.Date.valueOf(LocalDate.of(1990, 1, 1)) - ) - ) - .setTimestampValues( - Arrays.asList( - Date.from( - LocalDate.of(1991, 12, 31) - .atStartOfDay() - .atZone(ZoneId.systemDefault()) - .toInstant() - ), - Date.from( - LocalDate.of(1990, 1, 1) - .atStartOfDay() - .atZone(ZoneId.systemDefault()) - .toInstant() - ) - ) - ) - .setDecimalValues( - Arrays.asList( - BigDecimal.ONE, - BigDecimal.ZERO, - BigDecimal.TEN - ) - ) - .setLocalDateValues( - Arrays.asList( - LocalDate.of(2022, 3, 22), - LocalDate.of(2021, 4, 21) - ) - ) - .setLocalDateTimeValues( - Arrays.asList( - LocalDateTime.of(2022, 3, 22, 11, 22, 33), - LocalDateTime.of(2021, 4, 21, 22, 33, 44) - ) - ) - .setLocalDateTimeSetValues( - new LinkedHashSet<>( - Arrays.asList( - LocalDateTime.of(2022, 3, 22, 11, 22, 33), - LocalDateTime.of(2022, 3, 22, 11, 22, 33), - LocalDateTime.of(2021, 4, 21, 22, 33, 44) - ) - ) - ) - ); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertEquals( - Arrays.asList( - UUID.fromString("c65a3bcb-8b36-46d4-bddb-ae96ad016eb1"), - UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800") - ), - event.getSensorIds() - ); - assertEquals( - Arrays.asList("Temperature", "Pressure"), - event.getSensorNames() - ); - assertEquals( - Arrays.asList(12, 756), - event.getSensorValues() - ); - assertEquals( - Arrays.asList(42L, 9223372036854775800L), - event.getSensorLongValues() - ); - assertEquals( - Arrays.asList(true, false), - event.getSensorBooleanValues() - ); - assertEquals( - Arrays.asList(0.123D, 456.789D), - event.getSensorDoubleValues() - ); - assertEquals( - Arrays.asList( - SensorState.ONLINE, SensorState.OFFLINE, - SensorState.ONLINE, SensorState.UNKNOWN - ), - event.getSensorStates() - ); - assertEquals( - Arrays.asList( - java.sql.Date.valueOf(LocalDate.of(1991, 12, 31)), - java.sql.Date.valueOf(LocalDate.of(1990, 1, 1)) - ), - event.getDateValues() - ); - assertEquals( - Arrays.asList( - Date.from( - LocalDate.of(1991, 12, 31) - .atStartOfDay() - .atZone(ZoneId.systemDefault()) - .toInstant() - ), - Date.from( - LocalDate.of(1990, 1, 1) - .atStartOfDay() - .atZone(ZoneId.systemDefault()) - .toInstant() - ) - ), - event.getTimestampValues() - ); - assertEquals( - Arrays.asList( - BigDecimal.ONE, - BigDecimal.ZERO, - BigDecimal.TEN - ), - event.getDecimalValues() - ); - assertEquals( - Arrays.asList( - LocalDate.of(2022, 3, 22), - LocalDate.of(2021, 4, 21) - ), - event.getLocalDateValues() - ); - assertEquals( - Arrays.asList( - LocalDateTime.of(2022, 3, 22, 11, 22, 33), - LocalDateTime.of(2021, 4, 21, 22, 33, 44) - ), - event.getLocalDateTimeValues() - ); - assertEquals( - new HashSet<>( - Arrays.asList( - LocalDateTime.of(2022, 3, 22, 11, 22, 33), - LocalDateTime.of(2021, 4, 21, 22, 33, 44) - ) - ), - event.getLocalDateTimeSetValues() - ); - }); - - doInJPA(entityManager -> { - List events = entityManager.createNativeQuery( - "select " + - " id, " + - " sensor_ids, " + - " sensor_names, " + - " sensor_values, " + - " sensor_states " + - "from event ", Tuple.class) - .unwrap(org.hibernate.query.NativeQuery.class) - .addScalar("sensor_ids", UUIDArrayType.INSTANCE) - .addScalar("sensor_names", StringArrayType.INSTANCE) - .addScalar("sensor_values", IntArrayType.INSTANCE) - .addScalar( - "sensor_states", - new EnumArrayType( - SensorState[].class, - "sensor_state" - ) - ) - .getResultList(); - - assertEquals(2, events.size()); - }); - - Event _event = doInJPA(entityManager -> { - return entityManager.find(Event.class, 1L); - }); - - String newString = "New"; - LocalDateTime newTimestamp = LocalDateTime.of(2024, 6, 4, 11, 22, 33); - - assertEquals(2, _event.getSensorNames().size()); - assertEquals(2, _event.getLocalDateTimeSetValues().size()); - _event.getSensorNames().add(newString); - _event.getLocalDateTimeSetValues().add(newTimestamp); - - doInJPA(entityManager -> { - entityManager.merge(_event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - assertEquals(3, event.getSensorNames().size()); - assertTrue(event.getSensorNames().contains(newString)); - assertEquals(3, event.getLocalDateTimeSetValues().size()); - assertTrue(event.getLocalDateTimeSetValues().contains(newTimestamp)); - }); - } - - @Test - public void testMixingNullValues() { - - Date date = Date.from(LocalDate.of(1990, 1, 1).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorIds(Arrays.asList(null, UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800"))); - event.setSensorNames(Arrays.asList("Temperature", null)); - event.setSensorValues(Arrays.asList(null, 756)); - event.setSensorLongValues(Arrays.asList(null, 9223372036854775800L)); - event.setSensorBooleanValues(Arrays.asList(null, false)); - event.setSensorDoubleValues(Arrays.asList(null, 456.789D)); - event.setSensorStates(Arrays.asList(null, SensorState.OFFLINE, SensorState.ONLINE, null)); - event.setDateValues(Arrays.asList(null, date)); - event.setTimestampValues(Arrays.asList(null, date)); - event.setDecimalValues(Arrays.asList(null, BigDecimal.TEN)); - event.setLocalDateValues(Arrays.asList(null, LocalDate.of(2021, 4, 21))); - event.setLocalDateTimeValues(Arrays.asList(null, LocalDateTime.of(2021, 4, 21, 22, 33, 44))); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new UUID[]{null, UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800")}, event.getSensorIds().toArray()); - assertArrayEquals(new String[]{"Temperature", null}, event.getSensorNames().toArray()); - assertArrayEquals(new Integer[]{null, 756}, event.getSensorValues().toArray()); - assertArrayEquals(new Long[]{null, 9223372036854775800L}, event.getSensorLongValues().toArray()); - assertArrayEquals(new Boolean[]{null, false}, event.getSensorBooleanValues().toArray()); - assertArrayEquals(new Double[]{null, 456.789D}, event.getSensorDoubleValues().toArray()); - assertArrayEquals(new SensorState[]{null, SensorState.OFFLINE, SensorState.ONLINE, null}, event.getSensorStates().toArray()); - assertArrayEquals(new Date[]{null, date}, event.getDateValues().toArray()); - assertArrayEquals(new Date[]{null, date}, event.getTimestampValues().toArray()); - assertArrayEquals(new BigDecimal[]{null, BigDecimal.TEN}, event.getDecimalValues().toArray()); - assertArrayEquals(new LocalDate[]{null, LocalDate.of(2021, 4, 21)}, event.getLocalDateValues().toArray()); - assertArrayEquals(new LocalDateTime[]{null, LocalDateTime.of(2021, 4, 21, 22, 33, 44)}, event.getLocalDateTimeValues().toArray()); - }); - } - - @Test - public void testNullValues() { - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorIds(Arrays.asList(null, null)); - event.setSensorNames(Arrays.asList(null, null)); - event.setSensorValues(Arrays.asList(null, null)); - event.setSensorLongValues(Arrays.asList(null, null)); - event.setSensorBooleanValues(Arrays.asList(null, null)); - event.setSensorDoubleValues(Arrays.asList(null, null)); - event.setSensorStates(Arrays.asList(null, null)); - event.setDateValues(Arrays.asList(null, null)); - event.setTimestampValues(Arrays.asList(null, null)); - event.setDecimalValues(Arrays.asList(null, null)); - event.setLocalDateValues(Arrays.asList(null, null)); - event.setLocalDateTimeValues(Arrays.asList(null, null)); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new UUID[]{null, null}, event.getSensorIds().toArray()); - assertArrayEquals(new String[]{null, null}, event.getSensorNames().toArray()); - assertArrayEquals(new Integer[]{null, null}, event.getSensorValues().toArray()); - assertArrayEquals(new Long[]{null, null}, event.getSensorLongValues().toArray()); - assertArrayEquals(new Boolean[]{null, null}, event.getSensorBooleanValues().toArray()); - assertArrayEquals(new Double[]{null, null}, event.getSensorDoubleValues().toArray()); - assertArrayEquals(new SensorState[]{null, null}, event.getSensorStates().toArray()); - assertArrayEquals(new Date[]{null, null}, event.getDateValues().toArray()); - assertArrayEquals(new Date[]{null, null}, event.getTimestampValues().toArray()); - assertArrayEquals(new BigDecimal[]{null, null}, event.getDecimalValues().toArray()); - assertArrayEquals(new LocalDate[]{null, null}, event.getLocalDateValues().toArray()); - assertArrayEquals(new LocalDateTime[]{null, null}, event.getLocalDateTimeValues().toArray()); - }); - } - - @Test - public void testEmptyArrays() { - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorIds(Collections.emptyList()); - event.setSensorNames(Collections.emptyList()); - event.setSensorValues(Collections.emptyList()); - event.setSensorLongValues(Collections.emptyList()); - event.setSensorBooleanValues(Collections.emptyList()); - event.setSensorDoubleValues(Collections.emptyList()); - event.setSensorStates(Collections.emptyList()); - event.setDateValues(Collections.emptyList()); - event.setTimestampValues(Collections.emptyList()); - event.setDecimalValues(Collections.emptyList()); - event.setLocalDateValues(Collections.emptyList()); - event.setLocalDateTimeValues(Collections.emptyList()); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new UUID[]{}, event.getSensorIds().toArray()); - assertArrayEquals(new String[]{}, event.getSensorNames().toArray()); - assertArrayEquals(new Integer[]{}, event.getSensorValues().toArray()); - assertArrayEquals(new Long[]{}, event.getSensorLongValues().toArray()); - assertArrayEquals(new Boolean[]{}, event.getSensorBooleanValues().toArray()); - assertArrayEquals(new Double[]{}, event.getSensorDoubleValues().toArray()); - assertArrayEquals(new SensorState[]{}, event.getSensorStates().toArray()); - assertArrayEquals(new Date[]{}, event.getDateValues().toArray()); - assertArrayEquals(new Date[]{}, event.getTimestampValues().toArray()); - assertArrayEquals(new BigDecimal[]{}, event.getDecimalValues().toArray()); - assertArrayEquals(new LocalDate[]{}, event.getLocalDateValues().toArray()); - assertArrayEquals(new LocalDateTime[]{}, event.getLocalDateTimeValues().toArray()); - }); - } - - - @Entity(name = "Event") - @Table(name = "event") - @TypeDef(name = "list-array", typeClass = ListArrayType.class) - public static class Event { - - @Id - private Long id; - - @Type(type = "list-array") - @Column( - name = "sensor_ids", - columnDefinition = "uuid[]" - ) - private List sensorIds; - - @Type(type = "list-array") - @Column( - name = "sensor_names", - columnDefinition = "text[]" - ) - private List sensorNames; - - @Type(type = "list-array") - @Column( - name = "sensor_values", - columnDefinition = "integer[]" - ) - private List sensorValues; - - @Type(type = "list-array") - @Column( - name = "sensor_long_values", - columnDefinition = "bigint[]" - ) - private List sensorLongValues; - - @Type(type = "list-array") - @Column( - name = "sensor_boolean_values", - columnDefinition = "boolean[]" - ) - private List sensorBooleanValues; - - @Type(type = "list-array") - @Column( - name = "sensor_double_values", - columnDefinition = "float8[]" - ) - private List sensorDoubleValues; - - @Type( - type = "io.hypersistence.utils.hibernate.type.array.ListArrayType", - parameters = { - @Parameter( - name = ListArrayType.SQL_ARRAY_TYPE, - value = "sensor_state" - ) - } - ) - @Column( - name = "sensor_states", - columnDefinition = "sensor_state[]" - ) - private List sensorStates; - - @Type(type = "list-array") - @Column( - name = "date_values", - columnDefinition = "date[]" - ) - private List dateValues; - - @Type(type = "list-array") - @Column( - name = "timestamp_values", - columnDefinition = "timestamp[]" - ) - private List timestampValues; - - @Type(type = "list-array") - @Column( - name = "decimal_values", - columnDefinition = "decimal[]" - ) - private List decimalValues; - - @Type(type = "list-array") - @Column( - name = "localdate_values", - columnDefinition = "date[]" - ) - private List localDateValues; - - @Type(type = "list-array") - @Column( - name = "localdatetime_values", - columnDefinition = "timestamp[]" - ) - private List localDateTimeValues; - - @Type(type = "list-array") - @Column( - name = "localdatetime_set_values", - columnDefinition = "timestamp[]" - ) - private Set localDateTimeSetValues; - - public Long getId() { - return id; - } - - public Event setId(Long id) { - this.id = id; - return this; - } - - public List getSensorIds() { - return sensorIds; - } - - public Event setSensorIds(List sensorIds) { - this.sensorIds = sensorIds; - return this; - } - - public List getSensorNames() { - return sensorNames; - } - - public Event setSensorNames(List sensorNames) { - this.sensorNames = sensorNames; - return this; - } - - public List getSensorValues() { - return sensorValues; - } - - public Event setSensorValues(List sensorValues) { - this.sensorValues = sensorValues; - return this; - } - - public List getSensorLongValues() { - return sensorLongValues; - } - - public Event setSensorLongValues(List sensorLongValues) { - this.sensorLongValues = sensorLongValues; - return this; - } - - public List getSensorBooleanValues() { - return sensorBooleanValues; - } - - public Event setSensorBooleanValues(List sensorBooleanValues) { - this.sensorBooleanValues = sensorBooleanValues; - return this; - } - - public List getSensorDoubleValues() { - return sensorDoubleValues; - } - - public Event setSensorDoubleValues(List sensorDoubleValues) { - this.sensorDoubleValues = sensorDoubleValues; - return this; - } - - public List getSensorStates() { - return sensorStates; - } - - public Event setSensorStates(List sensorStates) { - this.sensorStates = sensorStates; - return this; - } - - public List getDateValues() { - return dateValues; - } - - public Event setDateValues(List dateValues) { - this.dateValues = dateValues; - return this; - } - - public List getTimestampValues() { - return timestampValues; - } - - public Event setTimestampValues(List timestampValues) { - this.timestampValues = timestampValues; - return this; - } - - public List getDecimalValues() { - return decimalValues; - } - - public Event setDecimalValues(List decimalValues) { - this.decimalValues = decimalValues; - return this; - } - - public List getLocalDateValues() { - return localDateValues; - } - - public Event setLocalDateValues(List localDateValues) { - this.localDateValues = localDateValues; - return this; - } - - public List getLocalDateTimeValues() { - return localDateTimeValues; - } - - public Event setLocalDateTimeValues(List localDateTimeValues) { - this.localDateTimeValues = localDateTimeValues; - return this; - } - - public Set getLocalDateTimeSetValues() { - return localDateTimeSetValues; - } - - public Event setLocalDateTimeSetValues(Set localDateTimeSetValues) { - this.localDateTimeSetValues = localDateTimeSetValues; - return this; - } - } - - @Test - public void testNullArrays() { - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertEquals(null, event.getSensorIds()); - assertEquals(null, event.getSensorNames()); - assertEquals(null, event.getSensorLongValues()); - assertEquals(null, event.getSensorStates()); - assertEquals(null, event.getDateValues()); - assertEquals(null, event.getTimestampValues()); - }); - } - - public enum SensorState { - ONLINE, OFFLINE, UNKNOWN; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MappedSuperclassListArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MappedSuperclassListArrayTypeTest.java deleted file mode 100644 index ed5f31489..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MappedSuperclassListArrayTypeTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertArrayEquals; - -/** - * @author Vlad Mihalcea - */ -public class MappedSuperclassListArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Test - public void test() { - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorNames(Arrays.asList("Temperature", "Pressure")); - event.setSensorValues(Arrays.asList(12, 756)); - - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new String[]{"Temperature", "Pressure"}, event.getSensorNames().toArray()); - assertArrayEquals(new Integer[]{12, 756}, event.getSensorValues().toArray()); - }); - } - - @MappedSuperclass - public static class BaseEntity { - - @Id - private Long id; - - @Type(type = "list-array") - @Column(name = "sensor_names", columnDefinition = "text[]") - private List sensorNames; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public List getSensorNames() { - return sensorNames; - } - - public void setSensorNames(List sensorNames) { - this.sensorNames = sensorNames; - } - } - - @Entity(name = "Event") - @TypeDef(name = "list-array", typeClass = ListArrayType.class) - @Table(name = "event") - public static class Event extends BaseEntity { - - @Type(type = "list-array") - @Column(name = "sensor_values", columnDefinition = "integer[]") - private List sensorValues; - - public List getSensorValues() { - return sensorValues; - } - - public void setSensorValues(List sensorValues) { - this.sensorValues = sensorValues; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MatrixArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MatrixArrayTypeTest.java deleted file mode 100644 index fc6569527..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MatrixArrayTypeTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.TypeDef; -import org.hibernate.annotations.TypeDefs; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -import static org.junit.Assert.assertArrayEquals; - -/** - * @author Vlad Mihalcea - */ -public class MatrixArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Test - public void testNonEmptyArray() { - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - entityManager.persist( - new Event() - .setId(1L) - .setMatrix(new String[][]{ - {"A", "B", "C"}, - {"1", "2", "3"}, - }) - ); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - assertArrayEquals( - new String[][]{ - {"A", "B", "C"}, - {"1", "2", "3"}, - }, - event.getMatrix() - ); - }); - } - - @Test - public void testEmptyArray() { - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - entityManager.persist( - new Event() - .setId(1L) - .setMatrix(new String[][]{}) - ); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - assertArrayEquals( - new String[][]{}, - event.getMatrix() - ); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - @TypeDefs({ - @TypeDef( - typeClass = StringArrayType.class, - defaultForType = String[][].class - ) - }) - public static class Event { - - @Id - private Long id; - - @Column(name = "test_2d_array", columnDefinition = "text[]") - private String[][] matrix; - - public Long getId() { - return id; - } - - public Event setId(Long id) { - this.id = id; - return this; - } - - public String[][] getMatrix() { - return matrix; - } - - public Event setMatrix(String[][] matrix) { - this.matrix = matrix; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalArrayTypeTest.java deleted file mode 100644 index f18c53720..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalArrayTypeTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.Parameter; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.type.LongType; -import org.hibernate.type.StringType; -import org.junit.Before; -import org.junit.Test; - -import javax.persistence.*; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * @author Vlad Mihalcea - */ -public class MultiDimensionalArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[] { - Plane.class, - }; - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Before - public void init() { - DataSource dataSource = newDataSource(); - try (Connection connection = dataSource.getConnection()) { - try (Statement statement = connection.createStatement()){ - statement.executeUpdate("DROP TABLE IF EXISTS plane;"); - statement.executeUpdate("DROP TYPE IF EXISTS seat_status CASCADE;"); - statement.executeUpdate("CREATE TYPE seat_status AS ENUM ('UNRESERVED', 'RESERVED', 'BLOCKED');"); - } - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Test - public void test() { - doInJPA(entityManager -> { - entityManager.persist( - new Plane() - .setId(1L) - .setName("ATR-42") - .setSeatGrid( - new SeatStatus[][] { - {SeatStatus.BLOCKED, SeatStatus.BLOCKED, SeatStatus.BLOCKED, SeatStatus.BLOCKED}, - {SeatStatus.UNRESERVED, SeatStatus.UNRESERVED, SeatStatus.RESERVED, SeatStatus.UNRESERVED}, - {SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED}, - {SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED}, - {SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED}, - {SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED}, - {SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED}, - {SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED}, - {SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED}, - {SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED}, - {SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED, SeatStatus.RESERVED}, - {SeatStatus.BLOCKED, SeatStatus.BLOCKED, SeatStatus.BLOCKED, SeatStatus.BLOCKED} - } - ) - ); - }); - - doInJPA(entityManager -> { - Plane plane = entityManager.find(Plane.class, 1L); - - assertEquals("ATR-42", plane.getName()); - assertEquals(SeatStatus.BLOCKED, plane.getSeatStatus(1, 'A')); - assertEquals(SeatStatus.BLOCKED, plane.getSeatStatus(1, 'B')); - assertEquals(SeatStatus.BLOCKED, plane.getSeatStatus(1, 'C')); - assertEquals(SeatStatus.BLOCKED, plane.getSeatStatus(1, 'D')); - assertEquals(SeatStatus.UNRESERVED, plane.getSeatStatus(2, 'A')); - assertEquals(SeatStatus.UNRESERVED, plane.getSeatStatus(2, 'B')); - assertEquals(SeatStatus.RESERVED, plane.getSeatStatus(2, 'C')); - assertEquals(SeatStatus.UNRESERVED, plane.getSeatStatus(2, 'D')); - }); - - doInJPA(entityManager -> { - List tuples = entityManager - .createNativeQuery( - "SELECT * " + - " FROM plane ", Tuple.class) - .unwrap(org.hibernate.query.NativeQuery.class) - .addScalar( - "seat_grid", - new EnumArrayType( - (Class) ReflectionUtils.getField(Plane.class, "seatGrid").getType(), - "seat_status_array" - ) - ) - .addScalar("name", StringType.INSTANCE) - .addScalar("id", LongType.INSTANCE) - .getResultList(); - - Tuple plane = tuples.get(0); - assertEquals("ATR-42", plane.get("name")); - }); - } - - public enum SeatStatus { - UNRESERVED, - RESERVED, - BLOCKED, - } - - @Entity(name = "Plane") - @Table(name = "plane") - @TypeDef(name = "seat_status_array", typeClass = EnumArrayType.class) - public static class Plane { - - @Id - private Long id; - - private String name; - - @Type( - type = "seat_status_array", - parameters = @Parameter( - name = "sql_array_type", - value = "seat_status" - ) - ) - @Column(name = "seat_grid", columnDefinition = "seat_status[][]") - private SeatStatus[][] seatGrid; - - public Long getId() { - return id; - } - - public Plane setId(Long id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Plane setName(String name) { - this.name = name; - return this; - } - - public SeatStatus[][] getSeatGrid() { - return seatGrid; - } - - public Plane setSeatGrid(SeatStatus[][] seatGrid) { - this.seatGrid = seatGrid; - return this; - } - - public SeatStatus getSeatStatus(int row, char letter) { - return seatGrid[row - 1][letter - 65]; - } - } - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalIntegerArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalIntegerArrayTypeTest.java deleted file mode 100644 index 7335b3d71..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalIntegerArrayTypeTest.java +++ /dev/null @@ -1,147 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.type.LongType; -import org.hibernate.type.StringType; -import org.junit.Test; - -import javax.persistence.*; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class MultiDimensionalIntegerArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[] { - Plane.class, - }; - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - entityManager.persist( - new Plane() - .setId(1L) - .setName("ATR-42") - .setSeatGrid( - new Integer[][] { - {1, 1, 1, 1}, - {0, 0, 2, 0}, - {2, 2, 2, 2}, - {2, 2, 2, 2}, - {2, 2, 2, 2}, - {2, 2, 2, 2}, - {2, 2, 2, 2}, - {2, 2, 2, 2}, - {2, 2, 2, 2}, - {2, 2, 2, 2}, - {2, 2, 2, 2}, - {1, 1, 1, 1} - } - ) - ); - }); - - doInJPA(entityManager -> { - Plane plane = entityManager.find(Plane.class, 1L); - - assertEquals("ATR-42", plane.getName()); - assertEquals(1, plane.getSeatStatus(1, 'A')); - assertEquals(1, plane.getSeatStatus(1, 'B')); - assertEquals(1, plane.getSeatStatus(1, 'C')); - assertEquals(1, plane.getSeatStatus(1, 'D')); - assertEquals(0, plane.getSeatStatus(2, 'A')); - assertEquals(0, plane.getSeatStatus(2, 'B')); - assertEquals(2, plane.getSeatStatus(2, 'C')); - assertEquals(0, plane.getSeatStatus(2, 'D')); - }); - - doInJPA(entityManager -> { - List tuples = entityManager - .createNativeQuery( - "SELECT * " + - " FROM plane ", Tuple.class) - .unwrap(org.hibernate.query.NativeQuery.class) - .addScalar( - "seat_grid", - new IntArrayType( - ReflectionUtils.getField(Plane.class, "seatGrid").getType() - ) - ) - .addScalar("name", StringType.INSTANCE) - .addScalar("id", LongType.INSTANCE) - .getResultList(); - - Tuple plane = tuples.get(0); - assertEquals("ATR-42", plane.get("name")); - }); - } - - @Entity(name = "Plane") - @Table(name = "plane") - @TypeDef(name = "int-array", typeClass = IntArrayType.class) - public static class Plane { - - @Id - private Long id; - - private String name; - - @Type(type = "int-array") - @Column(name = "seat_grid", columnDefinition = "int[][]") - private Integer[][] seatGrid; - - public Long getId() { - return id; - } - - public Plane setId(Long id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Plane setName(String name) { - this.name = name; - return this; - } - - public Integer[][] getSeatGrid() { - return seatGrid; - } - - public Plane setSeatGrid(Integer[][] seatGrid) { - this.seatGrid = seatGrid; - return this; - } - - public int getSeatStatus(int row, char letter) { - return seatGrid[row - 1][letter - 65]; - } - } - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalStringArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalStringArrayTypeTest.java deleted file mode 100644 index 32c48981c..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/MultiDimensionalStringArrayTypeTest.java +++ /dev/null @@ -1,148 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.ReflectionUtils; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.type.LongType; -import org.hibernate.type.StringType; -import org.junit.Test; - -import javax.persistence.*; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * @author Vlad Mihalcea - */ -public class MultiDimensionalStringArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[] { - Plane.class, - }; - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - entityManager.persist( - new Plane() - .setId(1L) - .setName("ATR-42") - .setSeatGrid( - new String[][] { - {"BLOCKED", "BLOCKED", "BLOCKED", "BLOCKED"}, - {"UNRESERVED", "UNRESERVED", "RESERVED", "UNRESERVED"}, - {"RESERVED", "RESERVED", "RESERVED", "RESERVED"}, - {"RESERVED", "RESERVED", "RESERVED", "RESERVED"}, - {"RESERVED", "RESERVED", "RESERVED", "RESERVED"}, - {"RESERVED", "RESERVED", "RESERVED", "RESERVED"}, - {"RESERVED", "RESERVED", "RESERVED", "RESERVED"}, - {"RESERVED", "RESERVED", "RESERVED", "RESERVED"}, - {"RESERVED", "RESERVED", "RESERVED", "RESERVED"}, - {"RESERVED", "RESERVED", "RESERVED", "RESERVED"}, - {"RESERVED", "RESERVED", "RESERVED", "RESERVED"}, - {"BLOCKED", "BLOCKED", "BLOCKED", "BLOCKED"} - } - ) - ); - }); - - doInJPA(entityManager -> { - Plane plane = entityManager.find(Plane.class, 1L); - - assertEquals("ATR-42", plane.getName()); - assertEquals("BLOCKED", plane.getSeatStatus(1, 'A')); - assertEquals("BLOCKED", plane.getSeatStatus(1, 'B')); - assertEquals("BLOCKED", plane.getSeatStatus(1, 'C')); - assertEquals("BLOCKED", plane.getSeatStatus(1, 'D')); - assertEquals("UNRESERVED", plane.getSeatStatus(2, 'A')); - assertEquals("UNRESERVED", plane.getSeatStatus(2, 'B')); - assertEquals("RESERVED", plane.getSeatStatus(2, 'C')); - assertEquals("UNRESERVED", plane.getSeatStatus(2, 'D')); - }); - - doInJPA(entityManager -> { - List tuples = entityManager - .createNativeQuery( - "SELECT * " + - " FROM plane ", Tuple.class) - .unwrap(org.hibernate.query.NativeQuery.class) - .addScalar( - "seat_grid", - new StringArrayType( - ReflectionUtils.getField(Plane.class, "seatGrid").getType() - ) - ) - .addScalar("name", StringType.INSTANCE) - .addScalar("id", LongType.INSTANCE) - .getResultList(); - - Tuple plane = tuples.get(0); - assertEquals("ATR-42", plane.get("name")); - }); - } - - @Entity(name = "Plane") - @Table(name = "plane") - @TypeDef(name = "string-array", typeClass = StringArrayType.class) - public static class Plane { - - @Id - private Long id; - - private String name; - - @Type(type = "string-array") - @Column(name = "seat_grid", columnDefinition = "text[][]") - private String[][] seatGrid; - - public Long getId() { - return id; - } - - public Plane setId(Long id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Plane setName(String name) { - this.name = name; - return this; - } - - public String[][] getSeatGrid() { - return seatGrid; - } - - public Plane setSeatGrid(String[][] seatGrid) { - this.seatGrid = seatGrid; - return this; - } - - public String getSeatStatus(int row, char letter) { - return seatGrid[row - 1][letter - 65]; - } - } - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQL95ArrayDialect.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQL95ArrayDialect.java deleted file mode 100644 index 2dfeb0bec..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQL95ArrayDialect.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import org.hibernate.dialect.PostgreSQL95Dialect; - -import java.sql.Types; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQL95ArrayDialect extends PostgreSQL95Dialect { - - public PostgreSQL95ArrayDialect() { - super(); - this.registerColumnType(Types.ARRAY, "array"); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQLEnumArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQLEnumArrayTypeTest.java deleted file mode 100644 index 0241dcd6a..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQLEnumArrayTypeTest.java +++ /dev/null @@ -1,177 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.annotations.TypeDefs; -import org.hibernate.jpa.TypedParameterValue; -import org.hibernate.query.Query; -import org.junit.Before; -import org.junit.Test; -import javax.persistence.*; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.fail; - -/** - * @author Nikita Konev - */ -public class PostgreSQLEnumArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - public static final EnumArrayType ROLE_TYPE = new EnumArrayType(UserRole.class, "user_role"); - - @Override - protected Class[] entities() { - return new Class[]{ - UserAccount.class - }; - } - - @Before - public void init() { - DataSource dataSource = newDataSource(); - try (Connection connection = dataSource.getConnection()) { - try (Statement statement = connection.createStatement()){ - statement.executeUpdate("DROP TYPE IF EXISTS user_role;"); - statement.executeUpdate("CREATE TYPE user_role AS ENUM ('ROLE_ADMIN', 'ROLE_USER');"); - } - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Test - public void test() { - UserRole[] userRoles = {UserRole.ROLE_ADMIN, UserRole.ROLE_USER}; - - doInJPA(entityManager -> { - UserAccount account = new UserAccount(); - account.setUsername("vladmihalcea.com"); - account.setRoles(userRoles); - entityManager.persist(account); - }); - - doInJPA(entityManager -> { - UserAccount singleResult = entityManager - .createQuery( - "select ua " + - "from UserAccountEntity ua " + - "where ua.username = :username", UserAccount.class) - .setParameter("username", "vladmihalcea.com") - .getSingleResult(); - - assertArrayEquals(userRoles, singleResult.getRoles()); - }); - } - - @Test - public void testSetParameterWithType() { - UserRole[] userRoles = {UserRole.ROLE_ADMIN, UserRole.ROLE_USER}; - UserRole[] requiredRoles = {UserRole.ROLE_USER}; - - doInJPA(entityManager -> { - UserAccount account = new UserAccount(); - account.setUsername("vladmihalcea.com"); - account.setRoles(userRoles); - entityManager.persist(account); - }); - - doInJPA(entityManager -> { - entityManager - .createQuery( - "select ua " + - "from UserAccountEntity ua " + - "where ua.roles = :roles", UserAccount.class) - .unwrap(Query.class) - .setParameter("roles", requiredRoles, new EnumArrayType(UserRole.class, "user_role")) - .getResultList(); - }); - } - - @Test - public void testTypedParameterValue() { - UserRole[] userRoles = {UserRole.ROLE_ADMIN, UserRole.ROLE_USER}; - UserRole[] requiredRoles = {UserRole.ROLE_USER}; - - doInJPA(entityManager -> { - UserAccount account = new UserAccount(); - account.setUsername("vladmihalcea.com"); - account.setRoles(userRoles); - entityManager.persist(account); - }); - - doInJPA(entityManager -> { - entityManager - .createQuery( - "select ua " + - "from UserAccountEntity ua " + - "where ua.roles = :roles", UserAccount.class) - .setParameter("roles", new TypedParameterValue(ROLE_TYPE, requiredRoles)) - .getResultList(); - }); - } - - public enum UserRole { - ROLE_ADMIN, - ROLE_USER, - } - - @TypeDefs({ - @TypeDef( - name = "pgsql_array", - typeClass = EnumArrayType.class - ) - }) - @Entity(name = "UserAccountEntity") - @Table(name = "users") - public static class UserAccount { - - @Id - @GeneratedValue - private Long id; - - private String username; - - @Type( - type = "pgsql_array", - parameters = @org.hibernate.annotations.Parameter( - name = "sql_array_type", - value = "user_role" - ) - ) - @Column( - name = "roles", - columnDefinition = "user_role[]" - ) - private UserRole roles[]; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public UserRole[] getRoles() { - return roles; - } - - public void setRoles(UserRole[] roles) { - this.roles = roles; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQLMultipleEnumArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQLMultipleEnumArrayTypeTest.java deleted file mode 100644 index aef32efd9..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/PostgreSQLMultipleEnumArrayTypeTest.java +++ /dev/null @@ -1,179 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.annotations.TypeDefs; -import org.junit.Before; -import org.junit.Test; - -import javax.persistence.*; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.fail; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLMultipleEnumArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - UserAccount.class - }; - } - - @Before - public void init() { - DataSource dataSource = newDataSource(); - - try (Connection connection = dataSource.getConnection()) { - try (Statement statement = connection.createStatement()){ - statement.executeUpdate("DROP TYPE IF EXISTS user_role;"); - statement.executeUpdate("CREATE TYPE user_role AS ENUM ('ROLE_ADMIN', 'ROLE_USER');"); - } - } catch (SQLException e) { - fail(e.getMessage()); - } - - try (Connection connection = dataSource.getConnection()) { - try (Statement statement = connection.createStatement()){ - statement.executeUpdate("DROP TYPE IF EXISTS user_role;"); - statement.executeUpdate("CREATE TYPE user_role AS ENUM ('ROLE_ADMIN', 'ROLE_USER');"); - } - - try (Statement statement = connection.createStatement()){ - statement.executeUpdate("DROP TYPE IF EXISTS user_type;"); - statement.executeUpdate("CREATE TYPE user_type AS ENUM ('SUPER_USER', 'REGULAR');"); - } - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Test - public void test() { - final UserRole[] userRoles = { - UserRole.ROLE_ADMIN, - UserRole.ROLE_USER - }; - - final UserType[] userTypes = { - UserType.SUPER_USER, - UserType.REGULAR - }; - - doInJPA(entityManager -> { - UserAccount account = new UserAccount(); - account.setUsername("vladmihalcea.com"); - account.setRoles(userRoles); - account.setTypes(userTypes); - entityManager.persist(account); - }); - - doInJPA(entityManager -> { - UserAccount singleResult = entityManager - .createQuery( - "select ua " + - "from UserAccountEntity ua " + - "where ua.username = :username", UserAccount.class) - .setParameter("username", "vladmihalcea.com") - .getSingleResult(); - - assertArrayEquals(userRoles, singleResult.getRoles()); - assertArrayEquals(userTypes, singleResult.getTypes()); - }); - } - - public enum UserRole { - ROLE_ADMIN, - ROLE_USER, - } - - public enum UserType { - SUPER_USER, - REGULAR, - } - - @TypeDefs({ - @TypeDef( - name = "pgsql_array", - typeClass = EnumArrayType.class - ) - - }) - @Entity(name = "UserAccountEntity") - @Table(name = "users") - public static class UserAccount { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - private String username; - - @Type( - type = "pgsql_array", - parameters = @org.hibernate.annotations.Parameter( - name = "sql_array_type", - value = "user_role" - ) - ) - @Column( - name = "roles", - columnDefinition = "user_role[]" - ) - private UserRole roles[]; - - @Type( - type = "pgsql_array", - parameters = @org.hibernate.annotations.Parameter( - name = "sql_array_type", - value = "user_type" - ) - ) - @Column( - name = "types", - columnDefinition = "user_type[]" - ) - private UserType types[]; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public UserRole[] getRoles() { - return roles; - } - - public void setRoles(UserRole[] roles) { - this.roles = roles; - } - - public UserType[] getTypes() { - return types; - } - - public void setTypes(UserType[] types) { - this.types = types; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/SimpleArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/SimpleArrayTypeTest.java deleted file mode 100644 index 7b3cdebb4..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/SimpleArrayTypeTest.java +++ /dev/null @@ -1,176 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.Parameter; -import org.hibernate.annotations.TypeDef; -import org.hibernate.annotations.TypeDefs; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.fail; - -/** - * @author Vlad Mihalcea - */ -public class SimpleArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - public void init() { - DataSource dataSource = newDataSource(); - try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { - try { - statement.executeUpdate( - "DROP TYPE sensor_state CASCADE" - ); - } catch (SQLException ignore) { - } - statement.executeUpdate( - "CREATE TYPE sensor_state AS ENUM ('ONLINE', 'OFFLINE', 'UNKNOWN')" - ); - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - entityManager.persist( - new Event() - .setId(1L) - .setSensorNames(new String[]{"Temperature", "Pressure"}) - .setSensorValues(new int[]{12, 756}) - .setSensorStates(new SensorState[]{SensorState.ONLINE, SensorState.OFFLINE, SensorState.ONLINE, SensorState.UNKNOWN}) - ); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new String[]{"Temperature", "Pressure"}, event.getSensorNames()); - assertArrayEquals(new int[]{12, 756}, event.getSensorValues()); - assertArrayEquals(new SensorState[]{SensorState.ONLINE, SensorState.OFFLINE, SensorState.ONLINE, SensorState.UNKNOWN}, event.getSensorStates()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - @TypeDefs({ - @TypeDef( - typeClass = StringArrayType.class, - defaultForType = String[].class - ), - @TypeDef( - typeClass = IntArrayType.class, - defaultForType = int[].class - ), - @TypeDef( - typeClass = EnumArrayType.class, - defaultForType = SensorState[].class, - parameters = { - @Parameter( - name = AbstractArrayType.SQL_ARRAY_TYPE, - value = "sensor_state" - ) - } - ) - }) - public static class Event { - - @Id - private Long id; - - @Column( - name = "sensor_names", - columnDefinition = "text[]" - ) - private String[] sensorNames; - - @Column( - name = "sensor_values", - columnDefinition = "integer[]" - ) - private int[] sensorValues; - - @Column( - name = "sensor_states", - columnDefinition = "sensor_state[]" - ) - private SensorState[] sensorStates; - - public Long getId() { - return id; - } - - public Event setId(Long id) { - this.id = id; - return this; - } - - public String[] getSensorNames() { - return sensorNames; - } - - public Event setSensorNames(String[] sensorNames) { - this.sensorNames = sensorNames; - return this; - } - - public int[] getSensorValues() { - return sensorValues; - } - - public Event setSensorValues(int[] sensorValues) { - this.sensorValues = sensorValues; - return this; - } - - public SensorState[] getSensorStates() { - return sensorStates; - } - - public Event setSensorStates(SensorState[] sensorStates) { - this.sensorStates = sensorStates; - return this; - } - } - - public enum SensorState { - ONLINE, OFFLINE, UNKNOWN; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/WrapperArrayTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/WrapperArrayTypeTest.java deleted file mode 100644 index 85318f044..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/array/WrapperArrayTypeTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package io.hypersistence.utils.hibernate.type.array; - -import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayType; -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import org.hibernate.annotations.Parameter; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Tuple; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; -import java.util.UUID; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class WrapperArrayTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - public void init() { - DataSource dataSource = newDataSource(); - try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { - statement.executeUpdate( - "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"" - ); - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider() { - @Override - public String hibernateDialect() { - return PostgreSQL95ArrayDialect.class.getName(); - } - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Event event = new Event(); - event.setId(1L); - event.setSensorIds(new UUID[]{UUID.fromString("c65a3bcb-8b36-46d4-bddb-ae96ad016eb1"), UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800")}); - event.setSensorValues(new Integer[]{12, 756}); - event.setSensorLongValues(new Long[]{42L, 9223372036854775800L}); - event.setSensorDoubleValues(new Double[]{0.123, 456.789}); - event.setSensorFloatValues(new Float[]{1.23f, 45.89f}); - - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - - assertArrayEquals(new UUID[]{UUID.fromString("c65a3bcb-8b36-46d4-bddb-ae96ad016eb1"), UUID.fromString("72e95717-5294-4c15-aa64-a3631cf9a800")}, event.getSensorIds()); - assertArrayEquals(new Integer[]{12, 756}, event.getSensorValues()); - assertArrayEquals(new Long[]{42L, 9223372036854775800L}, event.getSensorLongValues()); - assertArrayEquals(new Double[]{0.123, 456.789}, event.getSensorDoubleValues()); - assertArrayEquals(new Float[]{1.23f, 45.89f}, event.getSensorFloatValues()); - }); - - doInJPA(entityManager -> { - List events = entityManager.createNativeQuery( - "select " + - " id, " + - " sensor_ids, " + - " sensor_values, " + - " sensor_double_values " + - "from event ", Tuple.class) - .unwrap(org.hibernate.query.NativeQuery.class) - .addScalar("sensor_ids", UUIDArrayType.INSTANCE) - .addScalar("sensor_values", IntArrayType.INSTANCE) - .addScalar("sensor_double_values", DoubleArrayType.INSTANCE) - .getResultList(); - - assertEquals(2, events.size()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - @TypeDef(name = "sensor-state-array", typeClass = EnumArrayType.class, parameters = { - @Parameter(name = AbstractArrayType.SQL_ARRAY_TYPE, value = "sensor_state")} - ) - public static class Event extends BaseEntity { - @Type(type = "uuid-array") - @Column(name = "sensor_ids", columnDefinition = "uuid[]") - private UUID[] sensorIds; - - @Type(type = "int-array") - @Column(name = "sensor_values", columnDefinition = "integer[]") - private Integer[] sensorValues; - - @Type(type = "long-array") - @Column(name = "sensor_long_values", columnDefinition = "bigint[]") - private Long[] sensorLongValues; - - @Type(type = "double-array") - @Column(name = "sensor_double_values", columnDefinition = "float8[]") - private Double[] sensorDoubleValues; - - @Type(type = "float-array") - @Column(name = "sensor_float_values", columnDefinition = "float4[]") - private Float[] sensorFloatValues; - - public UUID[] getSensorIds() { - return sensorIds; - } - - public void setSensorIds(UUID[] sensorIds) { - this.sensorIds = sensorIds; - } - - public Integer[] getSensorValues() { - return sensorValues; - } - - public void setSensorValues(Integer[] sensorValues) { - this.sensorValues = sensorValues; - } - - public Long[] getSensorLongValues() { - return sensorLongValues; - } - - public void setSensorLongValues(Long[] sensorLongValues) { - this.sensorLongValues = sensorLongValues; - } - - public Double[] getSensorDoubleValues() { - return sensorDoubleValues; - } - - public void setSensorDoubleValues(Double[] sensorDoubleValues) { - this.sensorDoubleValues = sensorDoubleValues; - } - - public Float[] getSensorFloatValues() { - return sensorFloatValues; - } - - public void setSensorFloatValues(Float[] sensorFloatValues) { - this.sensorFloatValues = sensorFloatValues; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/Iso8601MonthTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/Iso8601MonthTest.java deleted file mode 100644 index 12682a320..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/Iso8601MonthTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.TypeDef; -import org.junit.Assert; -import org.junit.Test; - -import javax.persistence.*; -import java.time.Month; -import java.time.Year; - -import static org.junit.Assert.assertEquals; - -/** - * @author Martin Panzer - */ -public class Iso8601MonthTest extends AbstractTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Publisher.class - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Publisher publisher = new Publisher(); - publisher.setName("vladmihalcea.com"); - publisher.setEstYear(Year.of(2013)); - publisher.setSalesMonth(Month.NOVEMBER); - - entityManager.persist(publisher); - }); - - doInJPA(entityManager -> { - Publisher publisher = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Publisher.class) - .load("vladmihalcea.com"); - - assertEquals(Year.of(2013), publisher.getEstYear()); - assertEquals(Month.NOVEMBER, publisher.getSalesMonth()); - }); - - doInJPA(entityManager -> { - Publisher book = entityManager - .createQuery( - "select p " + - "from Publisher p " + - "where " + - " p.estYear = :estYear and " + - " p.salesMonth = :salesMonth", Publisher.class) - .setParameter("estYear", Year.of(2013)) - .setParameter("salesMonth", Month.NOVEMBER) - .getSingleResult(); - - assertEquals("vladmihalcea.com", book.getName()); - }); - - doInJPA(entityManager -> { - Query query = entityManager.createNativeQuery("Select p.sales_month from publisher p where p.name = :name"); - query.setParameter("name", "vladmihalcea.com"); - Short result = (Short)query.getSingleResult(); - - Assert.assertEquals(11L, result.longValue()); - }); - } - - - @Entity(name = "Publisher") - @Table(name = "publisher") - @TypeDef(typeClass = Iso8601MonthType.class, defaultForType = Month.class) - public static class Publisher { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String name; - - @Column(name = "est_year") - private Year estYear; - - @Column(name = "sales_month", columnDefinition = "smallint") - private Month salesMonth; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Year getEstYear() { - return estYear; - } - - public void setEstYear(Year estYear) { - this.estYear = estYear; - } - - public Month getSalesMonth() { - return salesMonth; - } - - public void setSalesMonth(Month salesMonth) { - this.salesMonth = salesMonth; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLMonthDayDateTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLMonthDayDateTest.java deleted file mode 100644 index 57bd4f063..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLMonthDayDateTest.java +++ /dev/null @@ -1,150 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.time.MonthDay; -import java.util.ArrayList; -import java.util.TimeZone; - -import static org.junit.Assert.assertEquals; - -/** - * @author Mladen Savic (mladensavic94@gmail.com) - */ -public class MySQLMonthDayDateTest extends AbstractMySQLIntegrationTest { - - public static final String COLUMN_TYPE = "date"; - - @Override - protected Class[] entities() { - return new Class[]{Season.class}; - } - - private TimeZone defaultTimeZone; - - @Override - protected void afterInit() { - defaultTimeZone = TimeZone.getDefault(); - TimeZone.setDefault(TimeZone.getTimeZone("Europe/Athens")); - } - - @Override - public void destroy() { - super.destroy(); - TimeZone.setDefault(defaultTimeZone); - } - - @Test - public void testCreationAndFetchById(){ - Season season = createEntity("Summer", MonthDay.of(6,21), MonthDay.of(9,22)); - - doInJPA(entityManager -> { - Season summer = entityManager.unwrap(Session.class).find(Season.class, season.getId()); - - assertEquals(summer.getBeginningOfSeason(), MonthDay.of(6,21)); - assertEquals(summer.getEndOfSeason(), MonthDay.of(9,22)); - }); - - assertEquals(COLUMN_TYPE, getColumnType("end_of_season") ); - assertEquals(COLUMN_TYPE, getColumnType("beginning_of_season") ); - - } - - @Test - public void testFetchWithQuery(){ - createEntity("Winter", MonthDay.of(12,21), MonthDay.of(3,20)); - - doInJPA(entityManager -> { - Season seasonQ = entityManager - .createQuery( - "select s " + - "from Season s " + - "where " + - "s.beginningOfSeason = :beginningOfSeason", Season.class) - .setParameter("beginningOfSeason", MonthDay.of(12,21)) - .getSingleResult(); - - assertEquals("Winter", seasonQ.getName()); - }); - - assertEquals(COLUMN_TYPE, getColumnType("end_of_season") ); - assertEquals(COLUMN_TYPE, getColumnType("beginning_of_season") ); - } - - public Season createEntity(String name, MonthDay beginning, MonthDay end){ - Season season = new Season(); - season.setName(name); - season.setBeginningOfSeason(beginning); - season.setEndOfSeason(end); - - doInJPA(entityManager -> { - entityManager.persist(season); - }); - - return season; - } - - public String getColumnType(String column){ - ArrayList results = new ArrayList<>(1); - doInJPA(entityManager -> { - Object result = entityManager.createNativeQuery("SELECT data_type FROM information_schema.columns WHERE \n" + - "table_name = 'season' AND column_name = :column_name") - .setParameter("column_name", column) - .getSingleResult(); - results.add((String) result); - }); - return results.get(0); - } - - - @Entity(name = "Season") - @Table(name = "season") - @TypeDef(typeClass = MonthDayDateType.class, defaultForType = MonthDay.class) - public static class Season { - - @Id - @GeneratedValue - private Long id; - private String name; - @Column(name = "beginning_of_season", columnDefinition = "date") - private MonthDay beginningOfSeason; - @Column(name = "end_of_season", columnDefinition = "date") - private MonthDay endOfSeason; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public MonthDay getBeginningOfSeason() { - return beginningOfSeason; - } - - public void setBeginningOfSeason(MonthDay beginningOfSeason) { - this.beginningOfSeason = beginningOfSeason; - } - - public MonthDay getEndOfSeason() { - return endOfSeason; - } - - public void setEndOfSeason(MonthDay endOfSeason) { - this.endOfSeason = endOfSeason; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLMonthDayIntegerTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLMonthDayIntegerTest.java deleted file mode 100644 index 0a5aac7a3..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLMonthDayIntegerTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.time.MonthDay; -import java.util.ArrayList; - -import static org.junit.Assert.assertEquals; - -/** - * @author Mladen Savic (mladensavic94@gmail.com) - */ -public class MySQLMonthDayIntegerTest extends AbstractMySQLIntegrationTest { - - public static final String COLUMN_TYPE = "int"; - - @Override - protected Class[] entities() { - return new Class[]{Season.class}; - } - - @Test - public void testCreationAndFetchById(){ - Season season = createEntity("Summer", MonthDay.of(6,21), MonthDay.of(9,22)); - - doInJPA(entityManager -> { - Season summer = entityManager.unwrap(Session.class).find(Season.class, season.getId()); - - assertEquals(summer.getBeginningOfSeason(), MonthDay.of(6,21)); - assertEquals(summer.getEndOfSeason(), MonthDay.of(9,22)); - }); - - assertEquals(COLUMN_TYPE, getColumnType("end_of_season") ); - assertEquals(COLUMN_TYPE, getColumnType("beginning_of_season") ); - - } - - @Test - public void testFetchWithQuery(){ - createEntity("Winter", MonthDay.of(12,21), MonthDay.of(3,20)); - - doInJPA(entityManager -> { - Season seasonQ = entityManager - .createQuery( - "select s " + - "from Season s " + - "where " + - "s.beginningOfSeason = :beginningOfSeason", Season.class) - .setParameter("beginningOfSeason", MonthDay.of(12,21)) - .getSingleResult(); - - assertEquals("Winter", seasonQ.getName()); - }); - - assertEquals(COLUMN_TYPE, getColumnType("end_of_season") ); - assertEquals(COLUMN_TYPE, getColumnType("beginning_of_season") ); - - } - - public Season createEntity(String name, MonthDay beginning, MonthDay end){ - Season season = new Season(); - season.setName(name); - season.setBeginningOfSeason(beginning); - season.setEndOfSeason(end); - - doInJPA(entityManager -> { - entityManager.persist(season); - }); - - return season; - } - - public String getColumnType(String column){ - ArrayList results = new ArrayList<>(1); - doInJPA(entityManager -> { - Object result = entityManager.createNativeQuery("SELECT data_type FROM information_schema.columns WHERE \n" + - "table_name = 'season' AND column_name = :column_name") - .setParameter("column_name", column) - .getSingleResult(); - results.add((String) result); - }); - return results.get(0); - } - - - @Entity(name = "Season") - @Table(name = "season") - @TypeDef(typeClass = MonthDayIntegerType.class, defaultForType = MonthDay.class) - public static class Season { - - @Id - @GeneratedValue - private Long id; - private String name; - @Column(name = "beginning_of_season", columnDefinition = "integer") - private MonthDay beginningOfSeason; - @Column(name = "end_of_season", columnDefinition = "integer") - private MonthDay endOfSeason; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public MonthDay getBeginningOfSeason() { - return beginningOfSeason; - } - - public void setBeginningOfSeason(MonthDay beginningOfSeason) { - this.beginningOfSeason = beginningOfSeason; - } - - public MonthDay getEndOfSeason() { - return endOfSeason; - } - - public void setEndOfSeason(MonthDay endOfSeason) { - this.endOfSeason = endOfSeason; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLYearMonthDateTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLYearMonthDateTest.java deleted file mode 100644 index 99c1d70a0..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLYearMonthDateTest.java +++ /dev/null @@ -1,147 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.time.YearMonth; -import java.util.TimeZone; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Vlad Mihalcea - */ -public class MySQLYearMonthDateTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - private TimeZone defaultTimeZone; - - @Override - protected void afterInit() { - defaultTimeZone = TimeZone.getDefault(); - TimeZone.setDefault(TimeZone.getTimeZone("Europe/Athens")); - } - - @Override - public void destroy() { - super.destroy(); - TimeZone.setDefault(defaultTimeZone); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.setTitle("High-Performance Java Persistence"); - book.setPublishedOn(YearMonth.of(2016, 10)); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals(YearMonth.of(2016, 10), book.getPublishedOn()); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .createQuery( - "select b " + - "from Book b " + - "where " + - " b.title = :title and " + - " b.publishedOn = :publishedOn", Book.class) - .setParameter("title", "High-Performance Java Persistence") - .setParameter("publishedOn", YearMonth.of(2016, 10)) - .getSingleResult(); - - assertEquals("978-9730228236", book.getIsbn()); - }); - } - - @Test - public void testNull() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("123-456"); - book.setPublishedOn(null); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("123-456"); - - assertNull(book.getPublishedOn()); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(typeClass = YearMonthDateType.class, defaultForType = YearMonth.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - private String title; - - @Column(name = "published_on", columnDefinition = "date") - private YearMonth publishedOn; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public YearMonth getPublishedOn() { - return publishedOn; - } - - public void setPublishedOn(YearMonth publishedOn) { - this.publishedOn = publishedOn; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLYearMonthIntegerTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLYearMonthIntegerTest.java deleted file mode 100644 index a800bc678..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/MySQLYearMonthIntegerTest.java +++ /dev/null @@ -1,132 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.time.YearMonth; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Vlad Mihalcea - */ -public class MySQLYearMonthIntegerTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.setTitle("High-Performance Java Persistence"); - book.setPublishedOn(YearMonth.of(2016, 10)); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals(YearMonth.of(2016, 10), book.getPublishedOn()); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .createQuery( - "select b " + - "from Book b " + - "where " + - " b.title = :title and " + - " b.publishedOn = :publishedOn", Book.class) - .setParameter("title", "High-Performance Java Persistence") - .setParameter("publishedOn", YearMonth.of(2016, 10)) - .getSingleResult(); - - assertEquals("978-9730228236", book.getIsbn()); - }); - } - - @Test - public void testNull() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("123-456"); - book.setPublishedOn(null); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("123-456"); - - assertNull(book.getPublishedOn()); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(typeClass = YearMonthIntegerType.class, defaultForType = YearMonth.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - private String title; - - @Column(name = "published_on", columnDefinition = "mediumint") - private YearMonth publishedOn; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public YearMonth getPublishedOn() { - return publishedOn; - } - - public void setPublishedOn(YearMonth publishedOn) { - this.publishedOn = publishedOn; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/NullableCharacterTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/NullableCharacterTypeTest.java deleted file mode 100644 index 67bd8ec08..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/NullableCharacterTypeTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractTest; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.*; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.fail; - -/** - * @author Vlad Mihalcea - */ -public class NullableCharacterTypeTest extends AbstractTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class - }; - } - - @Override - public void init() { - super.init(); - doInJDBC(connection -> { - try ( - Statement statement = connection.createStatement(); - ) { - statement.executeUpdate("INSERT INTO EVENT (ID, EVENT_TYPE) VALUES (1, 'abc')"); - statement.executeUpdate("INSERT INTO EVENT (ID, EVENT_TYPE) VALUES (2, '')"); - statement.executeUpdate("INSERT INTO EVENT (ID, EVENT_TYPE) VALUES (3, 'b')"); - } catch (SQLException e) { - fail(e.getMessage()); - } - }); - } - - @Test - public void test() { - final AtomicReference eventHolder = new AtomicReference<>(); - doInJPA(entityManager -> { - List events = entityManager.createQuery("select e from Event e", Event.class).getResultList(); - for (Event event : events) { - LOGGER.info("Event type: {}", event.getType()); - } - }); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event { - - @Id - @GeneratedValue - private Long id; - - @Type(type = "io.hypersistence.utils.hibernate.type.basic.NullableCharacterType") - @Column(name = "event_type") - private Character type; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Character getType() { - return type; - } - - public void setType(Character type) { - this.type = type; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/OracleBinaryDoubleTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/OracleBinaryDoubleTest.java deleted file mode 100644 index 45af332a7..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/OracleBinaryDoubleTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractOracleIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Vlad Mihalcea - */ -public class OracleBinaryDoubleTest extends AbstractOracleIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.setTitle("High-Performance Java Persistence"); - book.setRating(1.234d); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals(1.234d, book.getRating(), 0.001); - }); - } - - @Test - public void testNull() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("123-456"); - book.setRating(null); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("123-456"); - - assertNull(book.getRating()); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - private String title; - - @Column(columnDefinition = "binary_double") - private Double rating; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public Double getRating() { - return rating; - } - - public void setRating(Double rating) { - this.rating = rating; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/OracleBinaryFloatTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/OracleBinaryFloatTest.java deleted file mode 100644 index 99ac59bf6..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/OracleBinaryFloatTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractOracleIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Vlad Mihalcea - */ -public class OracleBinaryFloatTest extends AbstractOracleIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.setTitle("High-Performance Java Persistence"); - book.setRating(1.234f); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals(1.234f, book.getRating(), 0.001); - }); - } - - @Test - public void testNull() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("123-456"); - book.setRating(null); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("123-456"); - - assertNull(book.getRating()); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - private String title; - - @Column(columnDefinition = "binary_float") - private Float rating; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public Float getRating() { - return rating; - } - - public void setRating(Float rating) { - this.rating = rating; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLCITextTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLCITextTypeTest.java deleted file mode 100644 index cc09a1541..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLCITextTypeTest.java +++ /dev/null @@ -1,164 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.transaction.JPATransactionFunction; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * @author Sergei Portnov - */ -public class PostgreSQLCITextTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Country.class - }; - } - - @Override - public void init() { - DataSource dataSource = newDataSource(); - Connection connection = null; - Statement statement = null; - try { - connection = dataSource.getConnection(); - statement = connection.createStatement(); - - statement.executeUpdate("CREATE EXTENSION IF NOT EXISTS citext"); - } catch (SQLException e) { - fail(e.getMessage()); - } finally { - if(statement != null) { - try { - statement.close(); - } catch (SQLException e) { - fail(e.getMessage()); - } - } - if(connection != null) { - try { - connection.close(); - } catch (SQLException e) { - fail(e.getMessage()); - } - } - } - super.init(); - } - - @Test - public void test() { - Country countryWithNullName = new Country(); - countryWithNullName.setId(1L); - persist(countryWithNullName); - testFindById(countryWithNullName.getId(), countryWithNullName.getName()); - - Country countryWithName = new Country(); - countryWithName.setId(2L); - countryWithName.setName("Test"); - persist(countryWithName); - testFindById(countryWithName.getId(), countryWithName.getName()); - - testFindCountryByName(countryWithName.getName(), countryWithName); - testFindCountryByName(countryWithName.getName().toUpperCase(), countryWithName); - testFindCountryByName(countryWithName.getName().toLowerCase(), countryWithName); - } - - private void persist(final Country country) { - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - entityManager.persist(country); - - return null; - } - }); - } - - private void testFindById(final Long countryId, final String expectedName) { - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Country country = entityManager.find(Country.class, countryId); - - assertEquals(expectedName, country.getName()); - - return null; - } - }); - } - - private void testFindCountryByName(final String searchableName, final Country expectedCountry) { - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - - CriteriaQuery criteria = builder.createQuery(Country.class); - - Root root = criteria.from(Country.class); - - criteria.where( - builder.equal(root.get("name"), searchableName) - ); - - List countries = entityManager - .createQuery(criteria).getResultList(); - - assertEquals(1, countries.size()); - - Country country = countries.iterator().next(); - - assertEquals(expectedCountry.getId(), country.getId()); - assertEquals(expectedCountry.getName(), country.getName()); - - return null; - } - }); - } - - @Table(name = "country") - @Entity(name = "Country") - @TypeDef(name = "citext", typeClass = PostgreSQLCITextType.class) - public static class Country { - - @Id - private Long id; - - @Type(type = "citext") - @Column(columnDefinition = "citext") - private String name; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLEnumTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLEnumTest.java deleted file mode 100644 index 1f94909e9..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLEnumTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.jpa.TypedParameterValue; -import org.hibernate.type.CustomType; -import org.junit.Before; -import org.junit.Test; - -import javax.persistence.*; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLEnumTest extends AbstractPostgreSQLIntegrationTest { - - public static final CustomType POST_STATUS_TYPE = new CustomType(new PostgreSQLEnumType(PostStatus.class)); - - @Override - protected Class[] entities() { - return new Class[]{ - Post.class, - }; - } - - public void init() { - DataSource dataSource = newDataSource(); - try (Connection connection = dataSource.getConnection()) { - try (Statement statement = connection.createStatement()) { - try { - statement.executeUpdate( - "DROP TYPE post_status_info CASCADE" - ); - } catch (SQLException ignore) { - } - statement.executeUpdate( - "CREATE TYPE post_status_info AS ENUM ('PENDING', 'APPROVED', 'SPAM')" - ); - } - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Before - public void setUp() { - doInJPA(entityManager -> { - Post post = new Post(); - post.setId(1L); - post.setTitle("High-Performance Java Persistence"); - post.setStatus(PostStatus.PENDING); - entityManager.persist(post); - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Post post = entityManager.find(Post.class, 1L); - assertEquals(PostStatus.PENDING, post.getStatus()); - }); - } - - @Test - public void testTypedParameterValue() { - doInJPA(entityManager -> { - entityManager.createQuery("SELECT a FROM Post a WHERE a.status = :paramValue", Post.class) - .setParameter("paramValue", new TypedParameterValue(POST_STATUS_TYPE, PostStatus.APPROVED)) - .getResultList(); - }); - } - - @Test - public void testConstructorExpressionWithEnumWrapper() { - doInJPA(entityManager -> { - StatusWrapper statusWrapper = entityManager.createQuery( - "SELECT " + - " new io.hypersistence.utils.hibernate.type.basic.PostgreSQLEnumTest$StatusWrapper(p.status) " + - "FROM Post p " + - "WHERE p.id = :id" - , StatusWrapper.class) - .setParameter("id", 1L) - .getSingleResult(); - - assertEquals(PostStatus.PENDING, statusWrapper.getStatus()); - }); - } - - public enum PostStatus { - PENDING, - APPROVED, - SPAM; - - @Override - public String toString() { - return String.format("The %s enum is mapped to ordinal: %d", name(), ordinal()); - } - } - - @Entity(name = "Post") - @Table(name = "post") - @TypeDef(name = "pgsql_enum", typeClass = PostgreSQLEnumType.class) - public static class Post { - - @Id - private Long id; - - private String title; - - @Enumerated(EnumType.STRING) - @Column(columnDefinition = "post_status_info") - @Type(type = "pgsql_enum") - private PostStatus status; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public PostStatus getStatus() { - return status; - } - - public void setStatus(PostStatus status) { - this.status = status; - } - } - - public static class StatusWrapper { - private PostStatus status; - - public StatusWrapper(PostStatus status) { - this.status = status; - } - - public PostStatus getStatus() { - return status; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLHStoreTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLHStoreTypeTest.java deleted file mode 100644 index a984e961f..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLHStoreTypeTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.envers.Audited; -import org.junit.Test; - -import javax.persistence.*; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * @author Edgar Asatryan - * @author Vlad Mihalcea - */ -public class PostgreSQLHStoreTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - public void init() { - DataSource dataSource = newDataSource(); - try (Connection connection = dataSource.getConnection(); - Statement statement = connection.createStatement()) { - statement.executeUpdate("CREATE EXTENSION IF NOT EXISTS hstore"); - } catch (SQLException e) { - fail(e.getMessage()); - } - super.init(); - } - - @Test - public void test() { - - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.getProperties().put("title", "High-Performance Java Persistence"); - book.getProperties().put("author", "Vlad Mihalcea"); - book.getProperties().put("publisher", "Amazon"); - book.getProperties().put("price", "$44.95"); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals("High-Performance Java Persistence", book.getProperties().get("title")); - assertEquals("Vlad Mihalcea", book.getProperties().get("author")); - }); - } - - @Audited - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "hstore", typeClass = PostgreSQLHStoreType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - @Column(length = 15) - private String isbn; - - @Type(type = "hstore") - @Column(columnDefinition = "hstore") - private Map properties = new HashMap<>(); - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public Map getProperties() { - return properties; - } - - public void setProperties(Map properties) { - this.properties = properties; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLInetTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLInetTypeTest.java deleted file mode 100644 index 86f13ab19..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLInetTypeTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLInetTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[] { - Event.class - }; - } - - private Event _event; - - @Override - public void afterInit() { - doInJDBC(connection -> { - try (Statement statement = connection.createStatement()) { - statement.executeUpdate("CREATE INDEX ON event USING gist (ip inet_ops)"); - } catch (SQLException e) { - fail(e.getMessage()); - } - }); - - _event = doInJPA(entityManager -> { - entityManager.persist(new Event()); - - Event event = new Event(); - event.setIp("192.168.0.123/24"); - entityManager.persist(event); - - return event; - }); - } - - @Test - public void testFindById() { - Event updatedEvent = doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - - assertEquals("192.168.0.123/24", event.getIp().getAddress()); - assertEquals("192.168.0.123", event.getIp().toInetAddress().getHostAddress()); - - event.setIp("192.168.0.231/24"); - - return event; - }); - - assertEquals("192.168.0.231/24", updatedEvent.getIp().getAddress()); - } - - @Test - public void testJPQLQuery() { - doInJPA(entityManager -> { - Event event = entityManager.createQuery( - "select e " + - "from Event e " + - "where " + - " ip is not null", Event.class) - .getSingleResult(); - - assertEquals("192.168.0.123/24", event.getIp().getAddress()); - }); - } - - @Test - public void testNativeQuery() { - doInJPA(entityManager -> { - Event event = (Event) entityManager.createNativeQuery( - "SELECT e.* " + - "FROM event e " + - "WHERE " + - " e.ip && CAST(:network AS inet) = true", Event.class) - .setParameter("network", "192.168.0.1/24") - .getSingleResult(); - - assertEquals("192.168.0.123/24", event.getIp().getAddress()); - }); - } - - - @Test - public void testJDBCQuery() { - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - session.doWork(connection -> { - try(PreparedStatement ps = connection.prepareStatement( - "SELECT * " + - "FROM Event e " + - "WHERE " + - " e.ip && ?::inet = true" - )) { - ps.setObject(1, "192.168.0.1/24"); - ResultSet rs = ps.executeQuery(); - while(rs.next()) { - Long id = rs.getLong(1); - String ip = rs.getString(2); - assertEquals("192.168.0.123/24", ip); - } - } - }); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - @TypeDef(name = "ipv4", typeClass = PostgreSQLInetType.class, defaultForType = Inet.class) - public static class Event { - - @Id - @GeneratedValue - private Long id; - - @Column(name = "ip", columnDefinition = "inet") - private Inet ip; - - public Long getId() { - return id; - } - - public Inet getIp() { - return ip; - } - - public void setIp(String address) { - this.ip = new Inet(address); - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLLTreeTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLLTreeTypeTest.java deleted file mode 100644 index 6d2cdb63f..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLLTreeTypeTest.java +++ /dev/null @@ -1,159 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.transaction.JPATransactionFunction; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -public class PostgreSQLLTreeTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Tree.class - }; - } - - @Override - public void init() { - DataSource dataSource = newDataSource(); - Connection connection = null; - Statement statement = null; - try { - connection = dataSource.getConnection(); - statement = connection.createStatement(); - - statement.executeUpdate("CREATE EXTENSION IF NOT EXISTS ltree"); - } catch (SQLException e) { - fail(e.getMessage()); - } finally { - if (statement != null) { - try { - statement.close(); - } catch (SQLException e) { - fail(e.getMessage()); - } - } - if (connection != null) { - try { - connection.close(); - } catch (SQLException e) { - fail(e.getMessage()); - } - } - } - super.init(); - } - - @Test - public void test() { - Tree treeWithNullPath = new Tree(); - treeWithNullPath.setId(1L); - persist(treeWithNullPath); - testFindById(treeWithNullPath.getId(), treeWithNullPath.getPath()); - - Tree treeWithPath = new Tree(); - treeWithPath.setId(2L); - treeWithPath.setPath("Top.Collections.Pictures.Astronomy.Stars"); - persist(treeWithPath); - testFindById(treeWithPath.getId(), treeWithPath.getPath()); - - testFindTreeByPath(treeWithPath.getPath(), treeWithPath); - } - - private void persist(final Tree tree) { - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - entityManager.persist(tree); - - return null; - } - }); - } - - private void testFindById(final Long treeId, final String expectedPath) { - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Tree tree = entityManager.find(Tree.class, treeId); - - assertEquals(expectedPath, tree.getPath()); - - return null; - } - }); - } - - private void testFindTreeByPath(final String searchablePath, final Tree expectedTree) { - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - - CriteriaQuery criteria = builder.createQuery(Tree.class); - - Root root = criteria.from(Tree.class); - - criteria.where( - builder.equal(root.get("path"), searchablePath) - ); - - List trees = entityManager - .createQuery(criteria).getResultList(); - - assertEquals(1, trees.size()); - - Tree tree = trees.iterator().next(); - - assertEquals(expectedTree.getId(), tree.getId()); - assertEquals(expectedTree.getPath(), tree.getPath()); - - return null; - } - }); - } - - @Table(name = "tree") - @Entity(name = "Tree") - @TypeDef(name = "ltree", typeClass = PostgreSQLLTreeType.class) - public static class Tree { - - @Id - private Long id; - - @Type(type = "ltree") - @Column(columnDefinition = "ltree") - private String path; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLMonthDayDateTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLMonthDayDateTest.java deleted file mode 100644 index a1195ce54..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLMonthDayDateTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.time.MonthDay; -import java.util.ArrayList; - -import static org.junit.Assert.assertEquals; - -/** - * @author Mladen Savic (mladensavic94@gmail.com) - */ -public class PostgreSQLMonthDayDateTest extends AbstractPostgreSQLIntegrationTest { - - public static final String COLUMN_TYPE = "date"; - - @Override - protected Class[] entities() { - return new Class[]{Season.class}; - } - - @Test - public void testCreationAndFetchById(){ - Season season = createEntity("Summer", MonthDay.of(6,21), MonthDay.of(9,22)); - - doInJPA(entityManager -> { - Season summer = entityManager.unwrap(Session.class).find(Season.class, season.getId()); - - assertEquals(summer.getBeginningOfSeason(), MonthDay.of(6,21)); - assertEquals(summer.getEndOfSeason(), MonthDay.of(9,22)); - }); - - assertEquals(COLUMN_TYPE, getColumnType("end_of_season") ); - assertEquals(COLUMN_TYPE, getColumnType("beginning_of_season") ); - - } - - @Test - public void testFetchWithQuery(){ - createEntity("Winter", MonthDay.of(12,21), MonthDay.of(3,20)); - - doInJPA(entityManager -> { - Season seasonQ = entityManager - .createQuery( - "select s " + - "from Season s " + - "where " + - "s.beginningOfSeason = :beginningOfSeason", Season.class) - .setParameter("beginningOfSeason", MonthDay.of(12,21)) - .getSingleResult(); - - assertEquals("Winter", seasonQ.getName()); - }); - - assertEquals(COLUMN_TYPE, getColumnType("end_of_season") ); - assertEquals(COLUMN_TYPE, getColumnType("beginning_of_season") ); - } - - public Season createEntity(String name, MonthDay beginning, MonthDay end){ - Season season = new Season(); - season.setName(name); - season.setBeginningOfSeason(beginning); - season.setEndOfSeason(end); - - doInJPA(entityManager -> { - entityManager.persist(season); - }); - - return season; - } - - public String getColumnType(String column){ - ArrayList results = new ArrayList<>(1); - doInJPA(entityManager -> { - Object result = entityManager.createNativeQuery("SELECT data_type FROM information_schema.columns WHERE \n" + - "table_name = 'season' AND column_name = :column_name") - .setParameter("column_name", column) - .getSingleResult(); - results.add((String) result); - }); - return results.get(0); - } - - - @Entity(name = "Season") - @Table(name = "season") - @TypeDef(typeClass = MonthDayDateType.class, defaultForType = MonthDay.class) - public static class Season { - - @Id - @GeneratedValue - private Long id; - private String name; - @Column(name = "beginning_of_season", columnDefinition = "date") - private MonthDay beginningOfSeason; - @Column(name = "end_of_season", columnDefinition = "date") - private MonthDay endOfSeason; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public MonthDay getBeginningOfSeason() { - return beginningOfSeason; - } - - public void setBeginningOfSeason(MonthDay beginningOfSeason) { - this.beginningOfSeason = beginningOfSeason; - } - - public MonthDay getEndOfSeason() { - return endOfSeason; - } - - public void setEndOfSeason(MonthDay endOfSeason) { - this.endOfSeason = endOfSeason; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLMonthDayIntegerTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLMonthDayIntegerTest.java deleted file mode 100644 index 18d1099f1..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLMonthDayIntegerTest.java +++ /dev/null @@ -1,132 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.time.MonthDay; -import java.util.ArrayList; - -import static org.junit.Assert.assertEquals; - -/** - * @author Mladen Savic (mladensavic94@gmail.com) - */ -public class PostgreSQLMonthDayIntegerTest extends AbstractPostgreSQLIntegrationTest { - - public static final String COLUMN_TYPE = "integer"; - @Override - protected Class[] entities() { - return new Class[]{Season.class}; - } - - @Test - public void testCreationAndFetchById(){ - Season season = createEntity("Summer", MonthDay.of(6,21), MonthDay.of(9,22)); - - doInJPA(entityManager -> { - Season summer = entityManager.unwrap(Session.class).find(Season.class, season.getId()); - - assertEquals(summer.getBeginningOfSeason(), MonthDay.of(6,21)); - assertEquals(summer.getEndOfSeason(), MonthDay.of(9,22)); - }); - - assertEquals(COLUMN_TYPE, getColumnType("end_of_season") ); - assertEquals(COLUMN_TYPE, getColumnType("beginning_of_season") ); - } - - @Test - public void testFetchWithQuery(){ - createEntity("Winter", MonthDay.of(12,21), MonthDay.of(3,20)); - - doInJPA(entityManager -> { - Season seasonQ = entityManager - .createQuery( - "select s " + - "from Season s " + - "where " + - "s.beginningOfSeason = :beginningOfSeason", Season.class) - .setParameter("beginningOfSeason", MonthDay.of(12,21)) - .getSingleResult(); - - assertEquals("Winter", seasonQ.getName()); - }); - assertEquals(COLUMN_TYPE, getColumnType("end_of_season") ); - assertEquals(COLUMN_TYPE, getColumnType("beginning_of_season") ); - } - - public Season createEntity(String name, MonthDay beginning, MonthDay end){ - Season season = new Season(); - season.setName(name); - season.setBeginningOfSeason(beginning); - season.setEndOfSeason(end); - - doInJPA(entityManager -> { - entityManager.persist(season); - }); - - return season; - } - - public String getColumnType(String column){ - ArrayList results = new ArrayList<>(1); - doInJPA(entityManager -> { - Object result = entityManager.createNativeQuery("SELECT data_type FROM information_schema.columns WHERE \n" + - "table_name = 'season' AND column_name = :column_name") - .setParameter("column_name", column) - .getSingleResult(); - results.add((String) result); - }); - return results.get(0); - } - - - @Entity(name = "Season") - @Table(name = "season") - @TypeDef(typeClass = MonthDayIntegerType.class, defaultForType = MonthDay.class) - public static class Season { - - @Id - @GeneratedValue - private Long id; - private String name; - @Column(name = "beginning_of_season", columnDefinition = "integer") - private MonthDay beginningOfSeason; - @Column(name = "end_of_season", columnDefinition = "integer") - private MonthDay endOfSeason; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public MonthDay getBeginningOfSeason() { - return beginningOfSeason; - } - - public void setBeginningOfSeason(MonthDay beginningOfSeason) { - this.beginningOfSeason = beginningOfSeason; - } - - public MonthDay getEndOfSeason() { - return endOfSeason; - } - - public void setEndOfSeason(MonthDay endOfSeason) { - this.endOfSeason = endOfSeason; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthDateTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthDateTest.java deleted file mode 100644 index 279f8197a..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthDateTest.java +++ /dev/null @@ -1,132 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.time.YearMonth; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLYearMonthDateTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.setTitle("High-Performance Java Persistence"); - book.setPublishedOn(YearMonth.of(2016, 10)); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals(YearMonth.of(2016, 10), book.getPublishedOn()); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .createQuery( - "select b " + - "from Book b " + - "where " + - " b.title = :title and " + - " b.publishedOn = :publishedOn", Book.class) - .setParameter("title", "High-Performance Java Persistence") - .setParameter("publishedOn", YearMonth.of(2016, 10)) - .getSingleResult(); - - assertEquals("978-9730228236", book.getIsbn()); - }); - } - - @Test - public void testNull() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("123-456"); - book.setPublishedOn(null); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("123-456"); - - assertNull(book.getPublishedOn()); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(typeClass = YearMonthDateType.class, defaultForType = YearMonth.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - private String title; - - @Column(name = "published_on", columnDefinition = "date") - private YearMonth publishedOn; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public YearMonth getPublishedOn() { - return publishedOn; - } - - public void setPublishedOn(YearMonth publishedOn) { - this.publishedOn = publishedOn; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthEpochTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthEpochTest.java deleted file mode 100644 index c2ff5b8b5..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthEpochTest.java +++ /dev/null @@ -1,189 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.TypeDef; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.query.NativeQuery; -import org.junit.Ignore; -import org.junit.Test; - -import javax.persistence.*; -import java.time.YearMonth; -import java.util.List; -import java.util.Properties; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLYearMonthEpochTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void additionalProperties(Properties properties) { - properties.put(AvailableSettings.STATEMENT_BATCH_SIZE, 50); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.setTitle("High-Performance Java Persistence"); - book.setPublishedOn(YearMonth.of(2016, 10)); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals(YearMonth.of(2016, 10), book.getPublishedOn()); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .createQuery( - "select b " + - "from Book b " + - "where " + - " b.title = :title and " + - " b.publishedOn = :publishedOn", Book.class) - .setParameter("title", "High-Performance Java Persistence") - .setParameter("publishedOn", YearMonth.of(2016, 10)) - .getSingleResult(); - - assertEquals("978-9730228236", book.getIsbn()); - }); - } - - @Test - public void testNull() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("123-456"); - book.setPublishedOn(null); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("123-456"); - - assertNull(book.getPublishedOn()); - }); - } - - @Test - @Ignore - public void testIndexing() { - doInJPA(entityManager -> { - - YearMonth yearMonth = YearMonth.of(1970, 1); - - for (int i = 0; i < 5000; i++) { - yearMonth = yearMonth.plusMonths(1); - - Book book = new Book(); - book.setTitle( - String.format( - "IT industry newsletter - %s edition", yearMonth - ) - ); - book.setPublishedOn(yearMonth); - - entityManager.persist(book); - } - }); - - List executionPlanLines = doInJPA(entityManager -> { - return entityManager.createNativeQuery( - "EXPLAIN ANALYZE " + - "SELECT " + - " b.published_on " + - "FROM " + - " book b " + - "WHERE " + - " b.published_on BETWEEN :startYearMonth AND :endYearMonth ") - .unwrap(NativeQuery.class) - .setParameter("startYearMonth", YearMonth.of(2010, 12), YearMonthEpochType.INSTANCE) - .setParameter("endYearMonth", YearMonth.of(2018, 1), YearMonthEpochType.INSTANCE) - .getResultList(); - }); - - LOGGER.info("Execution plan: \n{}", executionPlanLines.stream().collect(Collectors.joining("\n"))); - } - - @Entity(name = "Book") - @Table( - name = "book", - indexes = @Index( - name = "idx_book_published_on", - columnList = "published_on" - ) - ) - @TypeDef(typeClass = YearMonthEpochType.class, defaultForType = YearMonth.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - private String title; - - @Column(name = "published_on", columnDefinition = "integer") - private YearMonth publishedOn; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public YearMonth getPublishedOn() { - return publishedOn; - } - - public void setPublishedOn(YearMonth publishedOn) { - this.publishedOn = publishedOn; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthIntegerTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthIntegerTest.java deleted file mode 100644 index d3d710266..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthIntegerTest.java +++ /dev/null @@ -1,190 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.TypeDef; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.query.NativeQuery; -import org.junit.Ignore; -import org.junit.Test; - -import javax.persistence.*; -import java.time.YearMonth; -import java.util.List; -import java.util.Properties; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLYearMonthIntegerTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void additionalProperties(Properties properties) { - properties.put(AvailableSettings.STATEMENT_BATCH_SIZE, 50); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.setTitle("High-Performance Java Persistence"); - book.setPublishedOn(YearMonth.of(2016, 10)); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals(YearMonth.of(2016, 10), book.getPublishedOn()); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .createQuery( - "select b " + - "from Book b " + - "where " + - " b.title = :title and " + - " b.publishedOn = :publishedOn", Book.class) - .setParameter("title", "High-Performance Java Persistence") - .setParameter("publishedOn", YearMonth.of(2016, 10)) - .getSingleResult(); - - assertEquals("978-9730228236", book.getIsbn()); - }); - } - - @Test - public void testNull() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("123-456"); - book.setPublishedOn(null); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("123-456"); - - assertNull(book.getPublishedOn()); - }); - } - - @Test - @Ignore - public void testIndexing() { - doInJPA(entityManager -> { - - YearMonth yearMonth = YearMonth.of(1970, 1); - - for (int i = 0; i < 5000; i++) { - yearMonth = yearMonth.plusMonths(1); - - Book book = new Book(); - book.setTitle( - String.format( - "IT industry newsletter - %s edition", yearMonth - ) - ); - book.setPublishedOn(yearMonth); - - entityManager.persist(book); - } - }); - - List executionPlanLines = doInJPA(entityManager -> { - return entityManager.createNativeQuery( - "EXPLAIN ANALYZE " + - "SELECT " + - " b.published_on " + - "FROM " + - " book b " + - "WHERE " + - " b.published_on BETWEEN :startYearMonth AND :endYearMonth ") - .unwrap(NativeQuery.class) - .setParameter("startYearMonth", YearMonth.of(2010, 12), YearMonthIntegerType.INSTANCE) - .setParameter("endYearMonth", YearMonth.of(2018, 1), YearMonthIntegerType.INSTANCE) - .getResultList(); - }); - - LOGGER.info("Execution plan: \n{}", executionPlanLines.stream().collect(Collectors.joining("\n"))); - } - - @Entity(name = "Book") - @Table( - name = "book", - indexes = @Index( - name = "idx_book_published_on", - columnList = "published_on" - ) - ) - @TypeDef(typeClass = YearMonthIntegerType.class, defaultForType = YearMonth.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - private String title; - - @Column(name = "published_on", columnDefinition = "integer") - private YearMonth publishedOn; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public YearMonth getPublishedOn() { - return publishedOn; - } - - public void setPublishedOn(YearMonth publishedOn) { - this.publishedOn = publishedOn; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthIntegerTypeContributorTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthIntegerTypeContributorTest.java deleted file mode 100644 index 6007b1989..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthIntegerTypeContributorTest.java +++ /dev/null @@ -1,122 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.jpa.boot.spi.TypeContributorList; -import org.junit.Test; - -import javax.persistence.*; -import java.time.YearMonth; -import java.util.Collections; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLYearMonthIntegerTypeContributorTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void additionalProperties(Properties properties) { - properties.put("hibernate.type_contributors", - (TypeContributorList) () -> Collections.singletonList( - (typeContributions, serviceRegistry) -> - typeContributions.contributeType(YearMonthIntegerType.INSTANCE) - )); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.setTitle("High-Performance Java Persistence"); - book.setPublishedOn(YearMonth.of(2016, 10)); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals(YearMonth.of(2016, 10), book.getPublishedOn()); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .createQuery( - "select b " + - "from Book b " + - "where " + - " b.title = :title and " + - " b.publishedOn = :publishedOn", Book.class) - .setParameter("title", "High-Performance Java Persistence") - .setParameter("publishedOn", YearMonth.of(2016, 10)) - .getSingleResult(); - - assertEquals("978-9730228236", book.getIsbn()); - }); - } - - - @Entity(name = "Book") - @Table(name = "book") - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - private String title; - - @Column(name = "published_on", columnDefinition = "integer") - private YearMonth publishedOn; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public YearMonth getPublishedOn() { - return publishedOn; - } - - public void setPublishedOn(YearMonth publishedOn) { - this.publishedOn = publishedOn; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthTimestampTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthTimestampTest.java deleted file mode 100644 index 61fa8e97a..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/PostgreSQLYearMonthTimestampTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import java.time.YearMonth; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLYearMonthTimestampTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.setTitle("High-Performance Java Persistence"); - book.setPublishedOn(YearMonth.of(2016, 10)); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals(YearMonth.of(2016, 10), book.getPublishedOn()); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .createQuery( - "select b " + - "from Book b " + - "where " + - " b.title = :title and " + - " b.publishedOn = :publishedOn", Book.class) - .setParameter("title", "High-Performance Java Persistence") - .setParameter("publishedOn", YearMonth.of(2016, 10)) - .getSingleResult(); - - assertEquals("978-9730228236", book.getIsbn()); - }); - } - - @Test - public void testNull() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setIsbn("123-456"); - book.setPublishedOn(null); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("123-456"); - - assertNull(book.getPublishedOn()); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(typeClass = YearMonthTimestampType.class, defaultForType = YearMonth.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - private String title; - - @Column(name = "published_on", columnDefinition = "date") - private YearMonth publishedOn; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public YearMonth getPublishedOn() { - return publishedOn; - } - - public void setPublishedOn(YearMonth publishedOn) { - this.publishedOn = publishedOn; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/YearAndMonthTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/YearAndMonthTest.java deleted file mode 100644 index 4cb4c8440..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/YearAndMonthTest.java +++ /dev/null @@ -1,115 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.time.Month; -import java.time.Year; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class YearAndMonthTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Publisher.class - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Publisher publisher = new Publisher(); - publisher.setName("vladmihalcea.com"); - publisher.setEstYear(Year.of(2013)); - publisher.setSalesMonth(Month.NOVEMBER); - - entityManager.persist(publisher); - }); - - doInJPA(entityManager -> { - Publisher publisher = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(Publisher.class) - .load("vladmihalcea.com"); - - assertEquals(Year.of(2013), publisher.getEstYear()); - assertEquals(Month.NOVEMBER, publisher.getSalesMonth()); - }); - - doInJPA(entityManager -> { - Publisher book = entityManager - .createQuery( - "select p " + - "from Publisher p " + - "where " + - " p.estYear = :estYear and " + - " p.salesMonth = :salesMonth", Publisher.class) - .setParameter("estYear", Year.of(2013)) - .setParameter("salesMonth", Month.NOVEMBER) - .getSingleResult(); - - assertEquals("vladmihalcea.com", book.getName()); - }); - } - - @Entity(name = "Publisher") - @Table(name = "publisher") - @TypeDef(typeClass = YearType.class, defaultForType = Year.class) - public static class Publisher { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String name; - - @Column(name = "est_year", columnDefinition = "smallint") - private Year estYear; - - @Column(name = "sales_month", columnDefinition = "smallint") - @Enumerated - private Month salesMonth; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Year getEstYear() { - return estYear; - } - - public void setEstYear(Year estYear) { - this.estYear = estYear; - } - - public Month getSalesMonth() { - return salesMonth; - } - - public void setSalesMonth(Month salesMonth) { - this.salesMonth = salesMonth; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/ZoneIdTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/ZoneIdTest.java deleted file mode 100644 index bf28b61c1..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/basic/ZoneIdTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package io.hypersistence.utils.hibernate.type.basic; - -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.time.ZoneId; - -import static org.junit.Assert.assertEquals; - -/** - * Tests for {@see ZoneId} Hibernate mapping. - * - * @author stonio - */ -public class ZoneIdTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{UserPreferences.class}; - } - - @Test - public void test() { - doInJPA(entityManager -> { - UserPreferences UserPreferences = new UserPreferences(); - UserPreferences.setName("vladmihalcea.com"); - UserPreferences.setZoneId(ZoneId.of("Europe/Bucharest")); - - entityManager.persist(UserPreferences); - }); - - doInJPA(entityManager -> { - UserPreferences userPreferences = entityManager - .unwrap(Session.class) - .bySimpleNaturalId(UserPreferences.class) - .load("vladmihalcea.com"); - - assertEquals(ZoneId.of("Europe/Bucharest"), userPreferences.getZoneId()); - }); - - doInJPA(entityManager -> { - UserPreferences prefs = entityManager - .createQuery( - "select p " + - "from UserPreferences p " + - "where " + - " p.zoneId = :zoneId", UserPreferences.class) - .setParameter("zoneId", ZoneId.of("Europe/Bucharest")) - .getSingleResult(); - - assertEquals("vladmihalcea.com", prefs.getName()); - }); - } - - @Entity(name = "UserPreferences") - @Table(name = "user_preferences") - @TypeDef(typeClass = ZoneIdType.class, defaultForType = ZoneId.class) - public static class UserPreferences { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String name; - - @Column(name = "zone_id", length= 40) - private ZoneId zoneId; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public ZoneId getZoneId() { - return zoneId; - } - - public void setZoneId(ZoneId zoneId) { - this.zoneId = zoneId; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/binary/MySQLBinaryTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/binary/MySQLBinaryTypeTest.java deleted file mode 100644 index 6f4d31c09..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/binary/MySQLBinaryTypeTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package io.hypersistence.utils.hibernate.type.binary; - -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.assertArrayEquals; - -/** - * @author Vlad Mihalcea - */ -public class MySQLBinaryTypeTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Post.class, - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - entityManager.persist( - new Post() - .setTitle("High-Performance Java Persistence") - .setImage(new byte[]{1, 2, 3}) - ); - }); - doInJPA(entityManager -> { - Post post = entityManager.find(Post.class, 1L); - - assertArrayEquals( - new byte[]{1, 2, 3}, - post.getImage() - ); - }); - } - - @Entity(name = "Post") - @Table(name = "post") - @TypeDef(typeClass = MySQLBinaryType.class, defaultForType = byte[].class) - public static class Post { - - @Id - @GeneratedValue - private Long id; - - private String title; - - @Column(columnDefinition = "BINARY(3)") - private byte[] image; - - public Long getId() { - return id; - } - - public Post setId(Long id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public Post setTitle(String title) { - this.title = title; - return this; - } - - public byte[] getImage() { - return image; - } - - public Post setImage(byte[] image) { - this.image = image; - return this; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/OracleIntervalDayToSecondTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/OracleIntervalDayToSecondTypeTest.java deleted file mode 100644 index b785b98ab..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/OracleIntervalDayToSecondTypeTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.hypersistence.utils.hibernate.type.interval; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractOracleIntegrationTest; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import java.time.Duration; - -import static org.junit.Assert.assertEquals; - -/** - * Tests for {@see OracleIntervalDayToSecondType} Hibernate type. - * - * @author Vlad Mihalcea - */ -public class OracleIntervalDayToSecondTypeTest extends AbstractOracleIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{WorkShift.class}; - } - - @Test - public void test() { - Duration duration = Duration.ofDays(1).plusHours(2).plusMinutes(3).plusSeconds(4); - - doInJPA(entityManager -> { - WorkShift intervalEntity = new WorkShift(); - intervalEntity.setId(1L); - intervalEntity.setDuration(duration); - - entityManager.persist(intervalEntity); - }); - - doInJPA(entityManager -> { - WorkShift result = entityManager.find(WorkShift.class, 1L); - assertEquals(duration, result.getDuration()); - }); - } - - @Entity(name = "WorkShift") - @TypeDef(typeClass = OracleIntervalDayToSecondType.class, defaultForType = Duration.class) - public static class WorkShift extends BaseEntity { - - @Column(columnDefinition = "INTERVAL DAY TO SECOND") - private Duration duration; - - public Duration getDuration() { - return duration; - } - - public void setDuration(Duration duration) { - this.duration = duration; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLIntervalTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLIntervalTypeTest.java deleted file mode 100644 index cd6790cfd..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLIntervalTypeTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package io.hypersistence.utils.hibernate.type.interval; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import java.time.Duration; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; - -/** - * Tests for {@see PostgreSQLIntervalType} Hibernate type. - * - * @author Jan-Willem Gmelig Meyling - */ -public class PostgreSQLIntervalTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{WorkShift.class}; - } - - @Test - public void test() { - Duration duration = Duration.ofDays(1).plusHours(2).plusMinutes(3).plusSeconds(4).plusNanos(5000); - - doInJPA(entityManager -> { - WorkShift intervalEntity = new WorkShift(); - intervalEntity.setId(1L); - intervalEntity.setDuration(duration); - - entityManager.persist(intervalEntity); - }); - - doInJPA(entityManager -> { - WorkShift result = entityManager.find(WorkShift.class, 1L); - assertEquals(duration, result.getDuration()); - }); - } - - @Entity(name = "WorkShift") - @TypeDef(typeClass = PostgreSQLIntervalType.class, defaultForType = Duration.class) - public static class WorkShift extends BaseEntity { - - @Column(columnDefinition = "interval") - private Duration duration; - - public Duration getDuration() { - return duration; - } - - public void setDuration(Duration duration) { - this.duration = duration; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLPeriodTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLPeriodTypeTest.java deleted file mode 100644 index de2005a5e..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/interval/PostgreSQLPeriodTypeTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.hypersistence.utils.hibernate.type.interval; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import java.time.Period; - -import static org.junit.Assert.assertEquals; - -/** - * Tests for {@see PostgreSQLIntervalType} Hibernate type. - * - * @author Jan-Willem Gmelig Meyling - */ -public class PostgreSQLPeriodTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{WorkShift.class}; - } - - @Test - public void test() { - Period duration = Period.of(1, 2, 3); - - doInJPA(entityManager -> { - WorkShift intervalEntity = new WorkShift(); - intervalEntity.setId(1L); - intervalEntity.setDuration(duration); - - entityManager.persist(intervalEntity); - }); - - doInJPA(entityManager -> { - WorkShift result = entityManager.find(WorkShift.class, 1L); - assertEquals(duration, result.getDuration()); - }); - } - - @Entity(name = "WorkShift") - @TypeDef(typeClass = PostgreSQLPeriodType.class, defaultForType = Period.class) - public static class WorkShift extends BaseEntity { - - @Column(columnDefinition = "interval") - private Period duration; - - public Period getDuration() { - return duration; - } - - public void setDuration(Period duration) { - this.duration = duration; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/EhcacheMySQLJsonBinaryTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/EhcacheMySQLJsonBinaryTypeTest.java deleted file mode 100644 index c90e65bfd..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/EhcacheMySQLJsonBinaryTypeTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.type.json.internal.JacksonUtil; -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.type.model.Location; -import io.hypersistence.utils.hibernate.type.model.Ticket; -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.Cacheable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import java.util.List; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * @author Vlad Mihalcea - */ -public class EhcacheMySQLJsonBinaryTypeTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - protected String[] packages() { - return new String[]{ - Event.class.getPackage().getName() - }; - } - - protected void additionalProperties(Properties properties) { - properties.setProperty("hibernate.cache.use_second_level_cache", "true"); - properties.setProperty("hibernate.cache.use_query_cache", "true"); - properties.setProperty("hibernate.cache.region.factory_class", "ehcache"); - } - - private Event _event; - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - - Event event = new Event(); - event.setId(1L); - - event.setProperties( - JacksonUtil.toJsonNode( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - entityManager.persist(event); - - Ticket ticket = new Ticket(); - ticket.setPrice(12.34d); - ticket.setRegistrationCode("ABC123"); - - _event = event; - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - SQLStatementCountValidator.reset(); - - Event event = entityManager.find(Event.class, _event.getId()); - assertNotNull(event.getProperties()); - - SQLStatementCountValidator.assertTotalCount(0); - - List properties = entityManager.createNativeQuery( - "select CAST(e.properties AS CHAR(1000)) " + - "from event e " + - "where JSON_EXTRACT(e.properties, \"$.price\") > 1 ") - .getResultList(); - - assertEquals(1, properties.size()); - JsonNode jsonNode = JacksonUtil.toJsonNode(properties.get(0)); - assertEquals("High-Performance Java Persistence", jsonNode.get("title").asText()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - @Cacheable(true) - @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - public static class Event extends BaseEntity { - - @Type(type = "json-node") - @Column(columnDefinition = "json") - private JsonNode properties; - - public JsonNode getProperties() { - return properties; - } - - public void setProperties(JsonNode properties) { - this.properties = properties; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/HbmJsonTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/HbmJsonTypeTest.java deleted file mode 100644 index dfc32616c..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/HbmJsonTypeTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.type.model.Location; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class HbmJsonTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - }; - } - - protected String[] resources() { - return new String[]{ - "hbm/type/json/HbmJsonTypeTest.hbm.xml" - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - assertEquals("Romania", event.getLocation().getCountry()); - assertEquals("Cluj-Napoca", event.getLocation().getCity()); - }); - } - - public static class Event { - - private Long id; - - private Location location; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonNodePropertyTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonNodePropertyTest.java deleted file mode 100644 index 72753d956..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonNodePropertyTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; - -import static org.junit.Assert.assertEquals; - -/** - * @author Victor Noël - */ -public class MySQLJsonNodePropertyTest extends AbstractMySQLIntegrationTest { - - private final ObjectMapper mapper = newMapper(); - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - try { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .setProperties(mapper.readTree("{\"field\": 0.05}")) - ); - } catch (JsonProcessingException e) { - throw new IllegalStateException(e); - } - }); - } - - @Test - public void test() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - assertEquals(0.05, book.getProperties().get("field").asDouble(), 0.0); - }); - - SQLStatementCountValidator.assertUpdateCount(0); - } - - public static class MyJsonType extends JsonType { - public MyJsonType() { - super(newMapper()); - } - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = MyJsonType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "json") - private JsonNode properties; - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public JsonNode getProperties() { - return properties; - } - - public Book setProperties(JsonNode properties) { - this.properties = properties; - return this; - } - } - - private static ObjectMapper newMapper() { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true); - return mapper; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonStringPropertyTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonStringPropertyTest.java deleted file mode 100644 index 48fb0e008..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonStringPropertyTest.java +++ /dev/null @@ -1,143 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** - * @author Vlad Mihalcea - */ -public class MySQLJsonStringPropertyTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - Book book = session - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertTrue(book.getProperties().contains("\"price\": 44.99")); - }); - - SQLStatementCountValidator.assertTotalCount(2); - SQLStatementCountValidator.assertSelectCount(2); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Test - public void testNullValue() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties(null); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertNull(book.getProperties()); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonStringType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "json") - private String properties; - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public String getProperties() { - return properties; - } - - public Book setProperties(String properties) { - this.properties = properties; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonTypeSetTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonTypeSetTest.java deleted file mode 100644 index 8ca547a5d..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonTypeSetTest.java +++ /dev/null @@ -1,194 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.annotations.DynamicUpdate; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import java.beans.ConstructorProperties; -import java.io.Serializable; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - -import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; - -/** - * @author Sergei Poznanski - */ -public class MySQLJsonTypeSetTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - User.class - }; - } - - private User _user; - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - User user = new User(); - - user.setId(1L); - user.setPhones(new HashSet<>(asList("7654321", "1234567"))); - user.setRoles(EnumSet.of(Role.ADMIN, Role.USER)); - user.setChildren(new HashSet<>(asList( - new Child("Jane", 2, new HashSet<>(asList("toy1", "toy2"))), - new Child("John", 1, new HashSet<>(asList("toy3", "toy4"))) - ))); - - entityManager.persist(user); - _user = user; - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - User user = entityManager.find(User.class, _user.getId()); - - SQLStatementCountValidator.reset(); - - user.setPhones(new HashSet<>(asList("1592637", "9518473"))); - user.setRoles(EnumSet.of(Role.USER, Role.DEV)); - user.setChildren(new HashSet<>(asList( - new Child("Jinny", 1, new HashSet<>(asList("toy5", "toy6"))), - new Child("Jenny", 2, new HashSet<>(asList("toy7", "toy8"))) - ))); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - doInJPA(entityManager -> { - User user = entityManager.find(User.class, _user.getId()); - assertEquals(new HashSet<>(asList("9518473", "1592637")), user.getPhones()); - assertEquals(EnumSet.of(Role.DEV, Role.USER), user.getRoles()); - assertEquals(new HashSet<>(asList( - new Child("Jenny", 2, new HashSet<>(asList("toy8", "toy7"))), - new Child("Jinny", 1, new HashSet<>(asList("toy6", "toy5"))) - )), user.getChildren()); - assertEquals(Integer.valueOf(1), user.getVersion()); - }); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - User user = entityManager.find(User.class, _user.getId()); - assertEquals(new HashSet<>(asList("1234567", "7654321")), user.getPhones()); - assertEquals(EnumSet.of(Role.USER, Role.ADMIN), user.getRoles()); - assertEquals(new HashSet<>(asList( - new Child("John", 1, new HashSet<>(asList("toy4", "toy3"))), - new Child("Jane", 2, new HashSet<>(asList("toy2", "toy1"))) - )), user.getChildren()); - assertEquals(Integer.valueOf(0), user.getVersion()); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertSelectCount(1); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Entity - @Table(name = "users") - @DynamicUpdate - public static class User extends BaseEntity { - - @Type(type = "json") - @Column(nullable = false, columnDefinition = "json") - private Set phones; - - @Type(type = "json") - @Column(nullable = false, columnDefinition = "json") - private EnumSet roles; - - @Type(type = "json") - @Column(nullable = false, columnDefinition = "json") - private Set children; - - public Set getPhones() { - return phones; - } - - public void setPhones(Set phones) { - this.phones = phones; - } - - public EnumSet getRoles() { - return roles; - } - - public void setRoles(EnumSet roles) { - this.roles = roles; - } - - public Set getChildren() { - return children; - } - - public void setChildren(final Set children) { - this.children = children; - } - } - - public enum Role { - USER, ADMIN, DEV - } - - public static class Child implements Serializable { - - private final String name; - private final Integer age; - private final Set toys; - - @ConstructorProperties({"name", "age", "toys"}) - public Child(String name, Integer age, final Set toys) { - this.name = Objects.requireNonNull(name); - this.age = Objects.requireNonNull(age); - this.toys = Objects.requireNonNull(toys); - } - - public String getName() { - return name; - } - - public Integer getAge() { - return age; - } - - public Set getToys() { - return toys; - } - - @Override - public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final Child child = (Child) o; - if (!name.equals(child.name)) return false; - if (!age.equals(child.age)) return false; - return toys.equals(child.toys); - } - - @Override - public int hashCode() { - int result = name.hashCode(); - result = 31 * result + age.hashCode(); - result = 31 * result + toys.hashCode(); - return result; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonTypeTest.java deleted file mode 100644 index 85f837267..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLJsonTypeTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.type.model.Location; -import io.hypersistence.utils.hibernate.type.model.Ticket; -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class MySQLJsonTypeTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - Participant.class - }; - } - - @Override - protected String[] packages() { - return new String[]{ - Location.class.getPackage().getName() - }; - } - - private Event _event; - - private Participant _participant; - - @Override - protected void afterInit() { - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - - Ticket ticket = new Ticket(); - ticket.setPrice(12.34d); - ticket.setRegistrationCode("ABC123"); - - Participant participant = new Participant(); - participant.setId(1L); - participant.setTicket(ticket); - participant.setEvent(event); - - entityManager.persist(participant); - - _event = event; - _participant = participant; - }); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - assertEquals("Romania", event.getLocation().getCountry()); - assertEquals("Cluj-Napoca", event.getLocation().getCity()); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertSelectCount(1); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Test - public void test() { - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - assertEquals("Cluj-Napoca", event.getLocation().getCity()); - - Participant participant = entityManager.find(Participant.class, _participant.getId()); - assertEquals("ABC123", participant.getTicket().getRegistrationCode()); - - List participants = entityManager.createNativeQuery( - "select p.ticket -> \"$.registrationCode\" " + - "from participant p " + - "where JSON_EXTRACT(p.ticket, \"$.price\") > 1 ") - .getResultList(); - - event.getLocation().setCity("Constanța"); - entityManager.flush(); - - assertEquals(1, participants.size()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event extends BaseEntity { - - @Type(type = "json") - @Column(columnDefinition = "json") - private Location location; - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - } - - @Entity(name = "Participant") - @Table(name = "participant") - public static class Participant extends BaseEntity { - - @Type(type = "json") - @Column(columnDefinition = "json") - private Ticket ticket; - - @ManyToOne - private Event event; - - public Ticket getTicket() { - return ticket; - } - - public void setTicket(Ticket ticket) { - this.ticket = ticket; - } - - public Event getEvent() { - return event; - } - - public void setEvent(Event event) { - this.event = event; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLParametrizedJsonTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLParametrizedJsonTypeTest.java deleted file mode 100644 index 56c8160f0..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/MySQLParametrizedJsonTypeTest.java +++ /dev/null @@ -1,248 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.ObjectMapper; -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import org.junit.Test; - -import javax.persistence.*; -import java.io.Serializable; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.*; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class MySQLParametrizedJsonTypeTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - PropertyHolder.class, - }; - } - - @Override - protected String[] packages() { - return new String[]{ - PropertyHolder.class.getPackage().getName() - }; - } - - @Override - protected List additionalTypes() { - - ParametrizedJsonStringType jsonType = new ParametrizedJsonStringType("json-hashmap", HashMap.class, new Class[]{String.class, Object.class}); - return Collections.singletonList(jsonType); - } - - @Override - protected boolean nativeHibernateSessionFactoryBootstrap() { - return true; - } - - @Test - public void test() { - final AtomicReference eventHolder = new AtomicReference<>(); - - doInJPA(entityManager -> { - PropertyHolder propertyHolder = new PropertyHolder(); - propertyHolder.setId(1L); - propertyHolder.addProperty("key1", "value"); - propertyHolder.addProperty("key2", 123456789); - propertyHolder.addProperty("key3", new POJO("one", "two")); - entityManager.persist(propertyHolder); - - eventHolder.set(propertyHolder); - }); - - doInJPA(entityManager -> { - PropertyHolder propertyHolder = entityManager.find(PropertyHolder.class, eventHolder.get().getId()); - assertEquals("value", propertyHolder.getProperty("key1")); - assertEquals(123456789, propertyHolder.getProperty("key2")); - assertEquals(new POJO("one", "two"), propertyHolder.getProperty("key3")); - - }); - } - - public static class ParametrizedJsonStringType extends JsonStringType { - - private String name; - - public ParametrizedJsonStringType(String name, final Type rawType, final Type[] actualTypeArguments) { - super(createObjectMapper(), createParameterizedType(rawType, actualTypeArguments, null)); - this.name = name; - } - - @Override - public String getName() { - return name; - } - - private static ObjectMapper createObjectMapper() { - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.enableDefaultTyping(); - return objectMapper; - } - - private static ParameterizedType createParameterizedType(final Type rawType, final Type[] actualTypeArguments, final Type ownerType) { - return new ParameterizedType() { - - @Override - public Type[] getActualTypeArguments() { - return actualTypeArguments; - } - - @Override - public Type getRawType() { - return rawType; - } - - @Override - public Type getOwnerType() { - return ownerType; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof ParameterizedType)) { - return false; - } - ParameterizedType other = (ParameterizedType) obj; - return Arrays.equals(getActualTypeArguments(), other.getActualTypeArguments()) && safeEquals(getRawType(), other.getRawType()) && safeEquals(getOwnerType(), other.getOwnerType()); - } - - @Override - public int hashCode() { - return safeHashCode(getActualTypeArguments()) ^ safeHashCode(getRawType()) ^ safeHashCode(getOwnerType()); - } - }; - } - - private static boolean safeEquals(Type t1, Type t2) { - if (t1 == null) { - return t2 == null; - } - return t1.equals(t2); - } - - private static int safeHashCode(Object o) { - if (o == null) { - return 1; - } - return o.hashCode(); - } - - } - - @Entity(name = "PropertyHolder") - @Table(name = "propertyholder") - public static class PropertyHolder { - - @Id - private Long id; - - @Version - private Integer version; - - @org.hibernate.annotations.Type(type = "json-hashmap") - @Column(columnDefinition = "json") - private Map props = new HashMap<>(); - - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Integer getVersion() { - return version; - } - - public Map getProps() { - return props; - } - - public void setProps(Map props) { - this.props = props; - } - - public void addProperty(String key, Object value) { - props.put(key, value); - } - - public Object getProperty(String key) { - return props.get(key); - } - } - - public static class POJO implements Serializable { - - private static final long serialVersionUID = -5009179810689351758L; - - private String first; - private String second; - - public POJO() { - } - - public POJO(String first, String second) { - this.first = first; - this.second = second; - } - - public String getFirst() { - return first; - } - - public void setFirst(String first) { - this.first = first; - } - - public String getSecond() { - return second; - } - - public void setSecond(String second) { - this.second = second; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((first == null) ? 0 : first.hashCode()); - result = prime * result + ((second == null) ? 0 : second.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - POJO other = (POJO) obj; - if (first == null) { - if (other.first != null) - return false; - } else if (!first.equals(other.first)) - return false; - if (second == null) { - if (other.second != null) - return false; - } else if (!second.equals(other.second)) - return false; - return true; - } - } - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/OracleJsonBinaryTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/OracleJsonBinaryTypeTest.java deleted file mode 100644 index 90a4a9481..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/OracleJsonBinaryTypeTest.java +++ /dev/null @@ -1,188 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.type.json.internal.JacksonUtil; -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.type.model.Location; -import io.hypersistence.utils.hibernate.type.model.Ticket; -import io.hypersistence.utils.hibernate.util.AbstractOracleIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.Session; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import java.sql.Statement; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class OracleJsonBinaryTypeTest extends AbstractOracleIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - Participant.class - }; - } - - private Event _event; - - private Participant _participant; - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - entityManager.unwrap(Session.class).doWork(connection -> { - try(Statement statement = connection.createStatement()) { - statement.executeUpdate( - "ALTER TABLE event MOVE LOB (location) STORE AS (CACHE)" - ); - - statement.executeUpdate( - "ALTER TABLE participant MOVE LOB (ticket, metadata) STORE AS (CACHE)" - ); - } - }); - }); - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - - Ticket ticket = new Ticket(); - ticket.setPrice(12.34d); - ticket.setRegistrationCode("ABC123"); - - Participant participant = new Participant(); - participant.setId(1L); - participant.setTicket(ticket); - participant.setEvent(event); - participant.setMetadata(JacksonUtil.toString(location)); - - entityManager.persist(participant); - - _event = event; - _participant = participant; - }); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - assertEquals("Romania", event.getLocation().getCountry()); - assertEquals("Cluj-Napoca", event.getLocation().getCity()); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertSelectCount(1); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - assertEquals("Cluj-Napoca", event.getLocation().getCity()); - - Participant participant = entityManager.find(Participant.class, _participant.getId()); - assertEquals("ABC123", participant.getTicket().getRegistrationCode()); - - event.getLocation().setCity("Constanța"); - assertEquals(Integer.valueOf(0), event.getVersion()); - entityManager.flush(); - assertEquals(Integer.valueOf(1), event.getVersion()); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - event.getLocation().setCity(null); - assertEquals(Integer.valueOf(1), event.getVersion()); - entityManager.flush(); - assertEquals(Integer.valueOf(2), event.getVersion()); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - event.setLocation(null); - assertEquals(Integer.valueOf(2), event.getVersion()); - entityManager.flush(); - assertEquals(Integer.valueOf(3), event.getVersion()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event extends BaseEntity { - - @Type(type = "jsonb-lob") - @Column(columnDefinition = "BLOB") - private Location location; - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - } - - @Entity(name = "Participant") - @Table(name = "participant") - public static class Participant extends BaseEntity { - - @Type(type = "jsonb-lob") - @Column(columnDefinition = "BLOB") - private Ticket ticket; - - @ManyToOne - private Event event; - - @Type(type = "jsonb-lob") - @Column(name = "metadata", columnDefinition = "BLOB") - private String metadata; - - public Ticket getTicket() { - return ticket; - } - - public void setTicket(Ticket ticket) { - this.ticket = ticket; - } - - public Event getEvent() { - return event; - } - - public void setEvent(Event event) { - this.event = event; - } - - public String getMetadata() { - return metadata; - } - - public void setMetadata(String metadata) { - this.metadata = metadata; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/OracleJsonStringPropertyTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/OracleJsonStringPropertyTest.java deleted file mode 100644 index 2b6e928a1..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/OracleJsonStringPropertyTest.java +++ /dev/null @@ -1,165 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.util.AbstractOracleIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.Session; -import org.hibernate.annotations.Check; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.query.NativeQuery; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class OracleJsonStringPropertyTest extends AbstractOracleIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - doInJPA(entityManager -> { - JsonNode properties = (JsonNode) entityManager - .createNativeQuery( - "SELECT " + - " properties AS properties " + - "FROM book " + - "WHERE " + - " isbn = :isbn") - .setParameter("isbn", "978-9730228236") - .unwrap(NativeQuery.class) - .addScalar("properties", new JsonStringType(JsonNode.class)) - .getSingleResult(); - - assertEquals("High-Performance Java Persistence", properties.get("title").asText()); - }); - } - - @Test - public void testNullValue() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties(null); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertNull(book.getProperties()); - }); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - Book book = session - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertTrue(book.getProperties().contains("\"price\": 44.99")); - }); - - SQLStatementCountValidator.assertTotalCount(2); - SQLStatementCountValidator.assertSelectCount(2); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonStringType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "VARCHAR2(1000)") - @Check(constraints = "properties IS JSON") - private String properties; - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public String getProperties() { - return properties; - } - - public Book setProperties(String properties) { - this.properties = properties; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLGenericJsonBinaryTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLGenericJsonBinaryTypeTest.java deleted file mode 100644 index ac402ebfe..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLGenericJsonBinaryTypeTest.java +++ /dev/null @@ -1,138 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.type.model.Location; -import io.hypersistence.utils.hibernate.type.model.Ticket; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLGenericJsonBinaryTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - Participant.class - }; - } - - private Event _event; - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - Location cluj = new Location(); - cluj.setCountry("Romania"); - cluj.setCity("Cluj-Napoca"); - - Location newYork = new Location(); - newYork.setCountry("US"); - newYork.setCity("New-York"); - - Location london = new Location(); - london.setCountry("UK"); - london.setCity("London"); - - Event event = new Event(); - event.setId(1L); - event.setLocation(cluj); - event.setAlternativeLocations(Arrays.asList(newYork, london)); - - entityManager.persist(event); - - _event = event; - }); - } - - @Test - public void test() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - - assertEquals("Cluj-Napoca", event.getLocation().getCity()); - - assertEquals(2, event.getAlternativeLocations().size()); - assertEquals("New-York", event.getAlternativeLocations().get(0).getCity()); - assertEquals("London", event.getAlternativeLocations().get(1).getCity()); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertSelectCount(1); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event extends BaseEntity { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private Location location; - - @Type( - type = "jsonb" - ) - @Column(columnDefinition = "jsonb") - private List alternativeLocations; - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - - public List getAlternativeLocations() { - return alternativeLocations; - } - - public void setAlternativeLocations(List alternativeLocations) { - this.alternativeLocations = alternativeLocations; - } - } - - @Entity(name = "Participant") - @Table(name = "participant") - public static class Participant extends BaseEntity { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private Ticket ticket; - - @ManyToOne - private Event event; - - public Ticket getTicket() { - return ticket; - } - - public void setTicket(Ticket ticket) { - this.ticket = ticket; - } - - public Event getEvent() { - return event; - } - - public void setEvent(Event event) { - this.event = event; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeLazyGroupTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeLazyGroupTest.java deleted file mode 100644 index 3b414d074..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeLazyGroupTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.type.model.Event; -import io.hypersistence.utils.hibernate.type.model.Location; -import io.hypersistence.utils.hibernate.type.model.Participant; -import io.hypersistence.utils.hibernate.type.model.Ticket; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.junit.Test; - -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonBinaryTypeLazyGroupTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - Participant.class - }; - } - - @Test - public void test() { - final AtomicReference eventHolder = new AtomicReference<>(); - final AtomicReference participantHolder = new AtomicReference<>(); - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - - Ticket ticket = new Ticket(); - ticket.setPrice(12.34d); - ticket.setRegistrationCode("ABC123"); - - Participant participant = new Participant(); - participant.setId(1L); - participant.setTicket(ticket); - participant.setEvent(event); - - entityManager.persist(participant); - - eventHolder.set(event); - participantHolder.set(participant); - }); - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, eventHolder.get().getId()); - LOGGER.debug("Fetched event"); - assertEquals("Cluj-Napoca", event.getLocation().getCity()); - - Participant participant = entityManager.find(Participant.class, participantHolder.get().getId()); - LOGGER.debug("Fetched participant"); - assertEquals("ABC123", participant.getTicket().getRegistrationCode()); - }); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeNestedCollectionExplicitEqualsTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeNestedCollectionExplicitEqualsTest.java deleted file mode 100644 index 23d537af2..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeNestedCollectionExplicitEqualsTest.java +++ /dev/null @@ -1,129 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.annotations.TypeDefs; -import org.junit.Test; - -import javax.persistence.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonBinaryTypeNestedCollectionExplicitEqualsTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Post.class, - }; - } - - private Post _post; - - @Override - protected void afterInit() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - List attributes = new ArrayList<>(); - attributes.add("JPA"); - attributes.add("Hibernate"); - - PostAttributes customAttributes = new PostAttributes(); - customAttributes.setAttributes(attributes); - - Post post = new Post(); - post.setCustomAttributes(customAttributes); - - entityManager.persist(post); - - _post = post; - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertInsertCount(1); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Post post = entityManager.find(Post.class, _post.getId()); - List attributes = post.getCustomAttributes().getAttributes(); - - assertTrue(attributes.contains("JPA")); - assertTrue(attributes.contains("Hibernate")); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertSelectCount(1); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @TypeDefs({@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)}) - @Entity(name = "Post") - @Table(name = "post") - public static class Post { - - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Id - private Long id; - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private PostAttributes customAttributes; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public PostAttributes getCustomAttributes() { - return customAttributes; - } - - public void setCustomAttributes(PostAttributes customAttributes) { - this.customAttributes = customAttributes; - } - } - - public static class PostAttributes { - - private List attributes; - - public List getAttributes() { - return attributes; - } - - public void setAttributes(List attributes) { - this.attributes = attributes; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PostAttributes)) return false; - PostAttributes that = (PostAttributes) o; - return Objects.equals(attributes, that.attributes); - } - - @Override - public int hashCode() { - return Objects.hash(attributes); - } - } - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeNestedCollectionNoEqualsTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeNestedCollectionNoEqualsTest.java deleted file mode 100644 index 80f15816c..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeNestedCollectionNoEqualsTest.java +++ /dev/null @@ -1,115 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.annotations.TypeDefs; -import org.junit.Test; - -import javax.persistence.*; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonBinaryTypeNestedCollectionNoEqualsTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Post.class, - }; - } - - private Post _post; - - @Override - protected void afterInit() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - List attributes = new ArrayList<>(); - attributes.add("JPA"); - attributes.add("Hibernate"); - - PostAttributes customAttributes = new PostAttributes(); - customAttributes.setAttributes(attributes); - - Post post = new Post(); - post.setCustomAttributes(customAttributes); - - entityManager.persist(post); - - _post = post; - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertInsertCount(1); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Post post = entityManager.find(Post.class, _post.getId()); - List attributes = post.getCustomAttributes().getAttributes(); - - assertTrue(attributes.contains("JPA")); - assertTrue(attributes.contains("Hibernate")); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertSelectCount(1); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @TypeDefs({@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)}) - @Entity(name = "Post") - @Table(name = "post") - public static class Post { - - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Id - private Long id; - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private PostAttributes customAttributes; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public PostAttributes getCustomAttributes() { - return customAttributes; - } - - public void setCustomAttributes(PostAttributes customAttributes) { - this.customAttributes = customAttributes; - } - } - - public static class PostAttributes { - - private List attributes; - - public List getAttributes() { - return attributes; - } - - public void setAttributes(List attributes) { - this.attributes = attributes; - } - } - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeSetTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeSetTest.java deleted file mode 100644 index cbff8640f..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeSetTest.java +++ /dev/null @@ -1,194 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.annotations.DynamicUpdate; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import java.beans.ConstructorProperties; -import java.io.Serializable; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - -import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; - -/** - * @author Sergei Poznanski - */ -public class PostgreSQLJsonBinaryTypeSetTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - User.class - }; - } - - private User _user; - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - User user = new User(); - - user.setId(1L); - user.setPhones(new HashSet<>(asList("7654321", "1234567"))); - user.setRoles(EnumSet.of(Role.ADMIN, Role.USER)); - user.setChildren(new HashSet<>(asList( - new Child("Jane", 2, new HashSet<>(asList("toy1", "toy2"))), - new Child("John", 1, new HashSet<>(asList("toy3", "toy4"))) - ))); - - entityManager.persist(user); - _user = user; - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - User user = entityManager.find(User.class, _user.getId()); - - SQLStatementCountValidator.reset(); - - user.setPhones(new HashSet<>(asList("1592637", "9518473"))); - user.setRoles(EnumSet.of(Role.USER, Role.DEV)); - user.setChildren(new HashSet<>(asList( - new Child("Jinny", 1, new HashSet<>(asList("toy5", "toy6"))), - new Child("Jenny", 2, new HashSet<>(asList("toy7", "toy8"))) - ))); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - doInJPA(entityManager -> { - User user = entityManager.find(User.class, _user.getId()); - assertEquals(new HashSet<>(asList("9518473", "1592637")), user.getPhones()); - assertEquals(EnumSet.of(Role.DEV, Role.USER), user.getRoles()); - assertEquals(new HashSet<>(asList( - new Child("Jenny", 2, new HashSet<>(asList("toy8", "toy7"))), - new Child("Jinny", 1, new HashSet<>(asList("toy6", "toy5"))) - )), user.getChildren()); - assertEquals(Integer.valueOf(1), user.getVersion()); - }); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - User user = entityManager.find(User.class, _user.getId()); - assertEquals(new HashSet<>(asList("1234567", "7654321")), user.getPhones()); - assertEquals(EnumSet.of(Role.USER, Role.ADMIN), user.getRoles()); - assertEquals(new HashSet<>(asList( - new Child("John", 1, new HashSet<>(asList("toy4", "toy3"))), - new Child("Jane", 2, new HashSet<>(asList("toy2", "toy1"))) - )), user.getChildren()); - assertEquals(Integer.valueOf(0), user.getVersion()); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertSelectCount(1); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Entity - @Table(name = "users") - @DynamicUpdate - public static class User extends BaseEntity { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private Set phones; - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private EnumSet roles; - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private Set children; - - public Set getPhones() { - return phones; - } - - public void setPhones(Set phones) { - this.phones = phones; - } - - public EnumSet getRoles() { - return roles; - } - - public void setRoles(EnumSet roles) { - this.roles = roles; - } - - public Set getChildren() { - return children; - } - - public void setChildren(final Set children) { - this.children = children; - } - } - - public enum Role { - USER, ADMIN, DEV - } - - public static class Child implements Serializable { - - private final String name; - private final Integer age; - private final Set toys; - - @ConstructorProperties({"name", "age", "toys"}) - public Child(String name, Integer age, final Set toys) { - this.name = Objects.requireNonNull(name); - this.age = Objects.requireNonNull(age); - this.toys = Objects.requireNonNull(toys); - } - - public String getName() { - return name; - } - - public Integer getAge() { - return age; - } - - public Set getToys() { - return toys; - } - - @Override - public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final Child child = (Child) o; - if (!name.equals(child.name)) return false; - if (!age.equals(child.age)) return false; - return toys.equals(child.toys); - } - - @Override - public int hashCode() { - int result = name.hashCode(); - result = 31 * result + age.hashCode(); - result = 31 * result + toys.hashCode(); - return result; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeTest.java deleted file mode 100644 index f66632eb9..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonBinaryTypeTest.java +++ /dev/null @@ -1,191 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.type.json.internal.JacksonUtil; -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.type.model.Location; -import io.hypersistence.utils.hibernate.type.model.Ticket; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonBinaryTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - Participant.class - }; - } - - private Event _event; - - private Participant _participant; - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - - Ticket ticket = new Ticket(); - ticket.setPrice(12.34d); - ticket.setRegistrationCode("ABC123"); - - Participant participant = new Participant(); - participant.setId(1L); - participant.setTicket(ticket); - participant.setEvent(event); - participant.setMetaData(JacksonUtil.toString(location)); - - entityManager.persist(participant); - - _event = event; - _participant = participant; - }); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - assertEquals("Romania", event.getLocation().getCountry()); - assertEquals("Cluj-Napoca", event.getLocation().getCity()); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertSelectCount(1); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Test - public void test() { - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - assertEquals("Cluj-Napoca", event.getLocation().getCity()); - - Participant participant = entityManager.find(Participant.class, _participant.getId()); - assertEquals("ABC123", participant.getTicket().getRegistrationCode()); - - List participants = entityManager.createNativeQuery( - "select jsonb_pretty(p.ticket) " + - "from participant p " + - "where p.ticket ->> 'price' > :price") - .setParameter("price", "10") - .getResultList(); - - List countries = entityManager.createNativeQuery( - "select p.metadata ->> 'country' " + - "from participant p ") - .getResultList(); - - event.getLocation().setCity("Constanța"); - assertEquals(Integer.valueOf(0), event.getVersion()); - entityManager.flush(); - assertEquals(Integer.valueOf(1), event.getVersion()); - - assertEquals(1, participants.size()); - assertEquals(1, countries.size()); - assertNotNull(countries.get(0)); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - event.getLocation().setCity(null); - assertEquals(Integer.valueOf(1), event.getVersion()); - entityManager.flush(); - assertEquals(Integer.valueOf(2), event.getVersion()); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - event.setLocation(null); - assertEquals(Integer.valueOf(2), event.getVersion()); - entityManager.flush(); - assertEquals(Integer.valueOf(3), event.getVersion()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event extends BaseEntity { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private Location location; - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - } - - @Entity(name = "Participant") - @Table(name = "participant") - public static class Participant extends BaseEntity { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private Ticket ticket; - - @ManyToOne - private Event event; - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private String metaData; - - public Ticket getTicket() { - return ticket; - } - - public void setTicket(Ticket ticket) { - this.ticket = ticket; - } - - public Event getEvent() { - return event; - } - - public void setEvent(Event event) { - this.event = event; - } - - public String getMetaData() { - return metaData; - } - - public void setMetaData(String metaData) { - this.metaData = metaData; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonListEnumTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonListEnumTest.java deleted file mode 100644 index bb115f1df..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonListEnumTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonListEnumTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .addProperty(PropertyType.BEST_SELLER) - .addProperty(PropertyType.FREE_CHAPTER) - ); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - List bookProperties = book.getProperties(); - assertEquals(2, bookProperties.size()); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - @Column(length = 15) - private String isbn; - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private List propertyTypes = new ArrayList<>(); - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public List getProperties() { - return propertyTypes; - } - - public Book setProperties(List properties) { - this.propertyTypes = properties; - return this; - } - - public Book addProperty(PropertyType propertyType) { - propertyTypes.add(propertyType); - return this; - } - } - - public enum PropertyType { - BEST_SELLER, - FREE_CHAPTER - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonListPojoTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonListPojoTest.java deleted file mode 100644 index a25b021fb..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonListPojoTest.java +++ /dev/null @@ -1,122 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonListPojoTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .addProperty("title", "High-Performance Java Persistence") - .addProperty("author", "Vlad Mihalcea") - .addProperty("publisher", "Amazon") - .addProperty("price", "$44.95") - ); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - List bookProperties = book.getProperties(); - assertEquals(4, bookProperties.size()); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - @Column(length = 15) - private String isbn; - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private List properties = new ArrayList<>(); - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public List getProperties() { - return properties; - } - - public Book setProperties(List properties) { - this.properties = properties; - return this; - } - - public Book addProperty(String key, String value) { - properties.add(new Property(key, value)); - return this; - } - } - - public static class Property { - - private String key; - private String value; - - public Property() { - } - - public Property(String key, String value) { - this.key = key; - this.value = value; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonMapTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonMapTest.java deleted file mode 100644 index e99969fa6..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonMapTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonMapTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .addProperty("title", "High-Performance Java Persistence") - .addProperty("author", "Vlad Mihalcea") - .addProperty("publisher", "Amazon") - .addProperty("price", "$44.95") - ); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - Map bookProperties = book.getProperties(); - - assertEquals( - "High-Performance Java Persistence", - bookProperties.get("title") - ); - - assertEquals( - "Vlad Mihalcea", - bookProperties.get("author") - ); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - @Column(length = 15) - private String isbn; - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private Map properties = new HashMap<>(); - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public Map getProperties() { - return properties; - } - - public Book setProperties(Map properties) { - this.properties = properties; - return this; - } - - public Book addProperty(String key, String value) { - properties.put(key, value); - return this; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonNodeBinaryTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonNodeBinaryTypeTest.java deleted file mode 100644 index 8983b557c..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonNodeBinaryTypeTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.type.json.internal.JacksonUtil; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonNodeBinaryTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.setProperties( - JacksonUtil.toJsonNode( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - - entityManager.persist(book); - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - Book book = session - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties( - JacksonUtil.toJsonNode( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ) - ); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - Book book = session - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals(expectedPrice(), book.getProperties().get("price").asText()); - }); - - SQLStatementCountValidator.assertTotalCount(2); - SQLStatementCountValidator.assertSelectCount(2); - SQLStatementCountValidator.assertUpdateCount(0); - } - - protected String initialPrice() { - return "44.99"; - } - - protected String expectedPrice() { - return "44.99"; - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "jsonb-node", typeClass = JsonNodeBinaryType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "jsonb-node") - @Column(columnDefinition = "jsonb") - private JsonNode properties; - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public JsonNode getProperties() { - return properties; - } - - public void setProperties(JsonNode properties) { - this.properties = properties; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonNodeTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonNodeTypeTest.java deleted file mode 100644 index bd02139e7..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonNodeTypeTest.java +++ /dev/null @@ -1,252 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.type.json.internal.JacksonUtil; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.TypeDef; -import org.hibernate.boot.spi.MetadataBuilderContributor; -import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; -import org.hibernate.query.NativeQuery; -import org.hibernate.transform.AliasToBeanResultTransformer; -import org.junit.Test; - -import javax.persistence.*; -import java.util.List; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonNodeTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void additionalProperties(Properties properties) { - properties.put( - EntityManagerFactoryBuilderImpl.METADATA_BUILDER_CONTRIBUTOR, - (MetadataBuilderContributor) metadataBuilder -> metadataBuilder.applyBasicType( - JsonNodeBinaryType.INSTANCE - ) - ); - } - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - - Book book = new Book(); - book.setIsbn("978-9730228236"); - book.setProperties( - JacksonUtil.toJsonNode( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - - entityManager.persist(book); - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - Book book = session - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties( - JacksonUtil.toJsonNode( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ) - ); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - Book book = session - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertEquals(expectedPrice(), book.getProperties().get("price").asText()); - }); - - SQLStatementCountValidator.assertTotalCount(2); - SQLStatementCountValidator.assertSelectCount(2); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Test - public void testQueryByJsonNode() { - Book book = doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - return session - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - }); - - Book _book = doInJPA(entityManager -> { - return entityManager - .createQuery( - "select b " + - "from Book b " + - "where b.properties = :properties", Book.class) - .setParameter("properties", book.getProperties()) - .getSingleResult(); - }); - - assertEquals(book.getIsbn(), _book.getIsbn()); - } - - @Test - public void testNativeQueryResultTransformer() { - doInJPA(entityManager -> { - List books = entityManager.createNativeQuery( - "SELECT " + - " b.id as id, " + - " b.properties as properties " + - "FROM book b") - .unwrap(NativeQuery.class) - .setResultTransformer(new AliasToBeanResultTransformer(BookDTO.class)) - .getResultList(); - - assertEquals(1, books.size()); - BookDTO book = books.get(0); - - assertEquals(expectedPrice(), book.getProperties().get("price").asText()); - }); - } - - @Test - public void testNativeQueryResultMapping() { - doInJPA(entityManager -> { - List books = entityManager.createNativeQuery( - "SELECT " + - " b.id as id, " + - " b.properties as properties " + - "FROM book b") - .unwrap(NativeQuery.class) - .setResultSetMapping("BookDTO") - .getResultList(); - - assertEquals(1, books.size()); - BookDTO book = books.get(0); - - assertEquals(expectedPrice(), book.getProperties().get("price").asText()); - }); - } - - protected String initialPrice() { - return "44.99"; - } - - protected String expectedPrice() { - return "44.99"; - } - - public static class BookDTO { - - private long id; - - private JsonNode properties; - - public BookDTO() { - } - - public BookDTO(Number id, JsonNode properties) { - this.id = id.longValue(); - this.properties = properties; - } - - public Long getId() { - return id; - } - - public void setId(Number id) { - this.id = id.longValue(); - } - - public JsonNode getProperties() { - return properties; - } - - public void setProperties(JsonNode properties) { - this.properties = properties; - } - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(typeClass = JsonBinaryType.class, defaultForType = JsonNode.class) - @SqlResultSetMapping( - name = "BookDTO", - classes = { - @ConstructorResult( - targetClass = BookDTO.class, - columns = { - @ColumnResult(name = "id"), - @ColumnResult(name = "properties", type = JsonNode.class), - } - ) - } - ) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Column(columnDefinition = "jsonb") - private JsonNode properties; - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public JsonNode getProperties() { - return properties; - } - - public void setProperties(JsonNode properties) { - this.properties = properties; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonParameterizedPropertyTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonParameterizedPropertyTest.java deleted file mode 100644 index 47dae8065..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonParameterizedPropertyTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.query.NativeQuery; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonParameterizedPropertyTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - doInJPA(entityManager -> { - JsonNode properties = (JsonNode) entityManager - .createNativeQuery( - "SELECT " + - " properties AS properties " + - "FROM book " + - "WHERE " + - " isbn = :isbn") - .setParameter("isbn", "978-9730228236") - .unwrap(NativeQuery.class) - .addScalar("properties", new JsonBinaryType(JsonNode.class)) - .getSingleResult(); - - assertEquals("High-Performance Java Persistence", properties.get("title").asText()); - }); - } - - @Test - public void testNullValue() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties(null); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertNull(book.getProperties()); - }); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - Book book = session - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertTrue(book.getProperties().contains("\"price\": 44.99")); - }); - - SQLStatementCountValidator.assertTotalCount(2); - SQLStatementCountValidator.assertSelectCount(2); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @MappedSuperclass - @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) - public static class AbstractBook { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private T properties; - - public T getProperties() { - return properties; - } - - public AbstractBook setProperties(T properties) { - this.properties = properties; - return this; - } - } - - @Entity(name = "Book") - @Table(name = "book") - public static class Book extends AbstractBook { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonStringPropertyTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonStringPropertyTest.java deleted file mode 100644 index 5d27bc049..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonStringPropertyTest.java +++ /dev/null @@ -1,189 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.util.ExceptionUtil; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.query.NativeQuery; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonStringPropertyTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - doInJPA(entityManager -> { - JsonNode properties = (JsonNode) entityManager - .createNativeQuery( - "SELECT " + - " properties AS properties " + - "FROM book " + - "WHERE " + - " isbn = :isbn") - .setParameter("isbn", "978-9730228236") - .unwrap(NativeQuery.class) - .addScalar("properties", new JsonBinaryType(JsonNode.class)) - .getSingleResult(); - - assertEquals("High-Performance Java Persistence", properties.get("title").asText()); - }); - } - - @Test - public void testNullValue() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties(null); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertNull(book.getProperties()); - }); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - Book book = session - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertTrue(book.getProperties().contains("\"price\": 44.99")); - }); - - SQLStatementCountValidator.assertTotalCount(2); - SQLStatementCountValidator.assertSelectCount(2); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Test - public void testInvalidJson() { - try { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": " + - " \"extras \": [" + - "}" - ); - }); - fail("An invalid JSON should throw an exception!"); - } catch (Exception e) { - Exception rootCause = ExceptionUtil.rootCause(e); - assertTrue(rootCause.getMessage().contains("invalid input syntax for type json")); - } - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private String properties; - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public String getProperties() { - return properties; - } - - public Book setProperties(String properties) { - this.properties = properties; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonStringTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonStringTypeTest.java deleted file mode 100644 index ac94bff37..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/PostgreSQLJsonStringTypeTest.java +++ /dev/null @@ -1,141 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.type.model.Location; -import io.hypersistence.utils.hibernate.type.model.Ticket; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonStringTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - Participant.class - }; - } - - private Event _event; - - private Participant _participant; - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - - Ticket ticket = new Ticket(); - ticket.setPrice(12.34d); - ticket.setRegistrationCode("ABC123"); - - Participant participant = new Participant(); - participant.setId(1L); - participant.setTicket(ticket); - participant.setEvent(event); - - entityManager.persist(participant); - - _event = event; - _participant = participant; - }); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - assertEquals("Cluj-Napoca", event.getLocation().getCity()); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertSelectCount(1); - SQLStatementCountValidator.assertUpdateCount(0); - - Participant participant = entityManager.find(Participant.class, _participant.getId()); - assertEquals("ABC123", participant.getTicket().getRegistrationCode()); - - List participants = entityManager.createNativeQuery( - "select p.ticket ->>'registrationCode' " + - "from participant p " + - "where p.ticket ->> 'price' > '10'") - .getResultList(); - - event.getLocation().setCity("Constanța"); - entityManager.flush(); - - assertEquals(1, participants.size()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event extends BaseEntity { - - @Type(type = "jsonb") - @Column(columnDefinition = "json") - private Location location; - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - } - - @Entity(name = "Participant") - @Table(name = "participant") - public static class Participant extends BaseEntity { - - @Type(type = "jsonb") - @Column(columnDefinition = "json") - private Ticket ticket; - - @ManyToOne - private Event event; - - public Ticket getTicket() { - return ticket; - } - - public void setTicket(Ticket ticket) { - this.ticket = ticket; - } - - public Event getEvent() { - return event; - } - - public void setEvent(Event event) { - this.event = event; - } - } - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/SQLServerJsonStringPropertyTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/SQLServerJsonStringPropertyTest.java deleted file mode 100644 index 7d6b850a9..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/SQLServerJsonStringPropertyTest.java +++ /dev/null @@ -1,163 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.util.AbstractSQLServerIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.query.NativeQuery; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class SQLServerJsonStringPropertyTest extends AbstractSQLServerIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - doInJPA(entityManager -> { - JsonNode properties = (JsonNode) entityManager - .createNativeQuery( - "SELECT " + - " properties AS properties " + - "FROM book " + - "WHERE " + - " isbn = :isbn") - .setParameter("isbn", "978-9730228236") - .unwrap(NativeQuery.class) - .addScalar("properties", new JsonStringType(JsonNode.class)) - .getSingleResult(); - - assertEquals("High-Performance Java Persistence", properties.get("title").asText()); - }); - } - - @Test - public void testNullValue() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - SQLStatementCountValidator.reset(); - - book.setProperties(null); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertUpdateCount(1); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertNull(book.getProperties()); - }); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - Book book = session - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertTrue(book.getProperties().contains("\"price\": 44.99")); - }); - - SQLStatementCountValidator.assertTotalCount(2); - SQLStatementCountValidator.assertSelectCount(2); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonStringType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "NVARCHAR(1000) CHECK(ISJSON(properties) = 1)") - private String properties; - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public String getProperties() { - return properties; - } - - public Book setProperties(String properties) { - this.properties = properties; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomJsonSerializer.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomJsonSerializer.java deleted file mode 100644 index fcd6d488e..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomJsonSerializer.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.configuration; - -import io.hypersistence.utils.hibernate.type.json.internal.JacksonUtil; -import io.hypersistence.utils.hibernate.type.util.JsonSerializer; - -/** - * @author Vlad Mihalcea - */ -public class CustomJsonSerializer implements JsonSerializer { - - private static boolean called; - - public static boolean isCalled() { - return called; - } - - public static void reset() { - called = false; - } - - @Override - public T clone(T value) { - called = true; - return JacksonUtil.clone(value); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomJsonSerializerSupplier.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomJsonSerializerSupplier.java deleted file mode 100644 index c69837ece..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomJsonSerializerSupplier.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.configuration; - -import io.hypersistence.utils.hibernate.type.util.JsonSerializer; -import io.hypersistence.utils.hibernate.type.util.JsonSerializerSupplier; - -/** - * @author Vlad Mihalcea - */ -public class CustomJsonSerializerSupplier implements JsonSerializerSupplier { - - @Override - public JsonSerializer get() { - return new CustomJsonSerializer(); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomObjectMapperSupplier.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomObjectMapperSupplier.java deleted file mode 100644 index d9e1d4566..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/CustomObjectMapperSupplier.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.configuration; - -import com.fasterxml.jackson.core.Version; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; -import io.hypersistence.utils.hibernate.type.util.ObjectMapperSupplier; - -import java.util.TimeZone; - -/** - * @author Vlad Mihalcea - */ -public class CustomObjectMapperSupplier implements ObjectMapperSupplier { - - @Override - public ObjectMapper get() { - ObjectMapper objectMapper = new ObjectMapper().findAndRegisterModules(); - objectMapper.setTimeZone(TimeZone.getTimeZone("GMT")); - SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1, 0, 0, null, null, null)); - simpleModule.addSerializer(new MoneySerializer()); - objectMapper.registerModule(simpleModule); - return objectMapper; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/MoneySerializer.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/MoneySerializer.java deleted file mode 100644 index 57b9e4ce5..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/MoneySerializer.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.configuration; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import java.io.IOException; -import java.math.BigDecimal; - -/** - * @author Vlad Mihalcea - */ -public class MoneySerializer extends JsonSerializer { - - @Override - public void serialize(BigDecimal value, JsonGenerator jsonGenerator, SerializerProvider provider) - throws IOException { - jsonGenerator.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString()); - } - - @Override - public Class handledType() { - return BigDecimal.class; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeConfigurationJvmForkTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeConfigurationJvmForkTest.java deleted file mode 100644 index d5cda6832..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeConfigurationJvmForkTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.configuration; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import java.io.Serializable; -import java.math.BigDecimal; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonBinaryTypeConfigurationJvmForkTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - public void init() { - System.setProperty( - Configuration.PROPERTIES_FILE_PATH, - "PostgreSQLJsonBinaryTypeConfigurationTest.properties" - ); - super.init(); - } - - @Override - public void destroy() { - super.destroy(); - System.getProperties().remove(Configuration.PROPERTIES_FILE_PATH); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - location.setReference(BigDecimal.valueOf(2.25262562526626D)); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - assertEquals("2.25", event.getLocation().getReference().toString()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event extends BaseEntity { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private Location location; - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - } - - public static class Location implements Serializable { - - private String country; - - private String city; - - private BigDecimal reference; - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public BigDecimal getReference() { - return reference; - } - - public void setReference(BigDecimal reference) { - this.reference = reference; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeCustomJsonSerializerConfigurationJvmForkTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeCustomJsonSerializerConfigurationJvmForkTest.java deleted file mode 100644 index f65900998..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeCustomJsonSerializerConfigurationJvmForkTest.java +++ /dev/null @@ -1,123 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.configuration; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.hibernate.type.util.Configuration; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Table; -import java.io.Serializable; -import java.math.BigDecimal; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonBinaryTypeCustomJsonSerializerConfigurationJvmForkTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - public void init() { - System.setProperty( - Configuration.PROPERTIES_FILE_PATH, - "PostgreSQLJsonBinaryTypeCustomJsonSerializerConfigurationTest.properties" - ); - super.init(); - } - - @Override - public void destroy() { - super.destroy(); - System.getProperties().remove(Configuration.PROPERTIES_FILE_PATH); - } - - @Test - public void test() { - assertFalse(CustomJsonSerializer.isCalled()); - - doInJPA(entityManager -> { - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - location.setReference(BigDecimal.valueOf(2.25262562526626D)); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - }); - - assertTrue(CustomJsonSerializer.isCalled()); - CustomJsonSerializer.reset(); - assertFalse(CustomJsonSerializer.isCalled()); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - assertEquals("2.25262562526626", event.getLocation().getReference().toString()); - }); - - assertTrue(CustomJsonSerializer.isCalled()); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event extends BaseEntity { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private Location location; - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - } - - public static class Location implements Serializable { - - private String country; - - private String city; - - private BigDecimal reference; - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public BigDecimal getReference() { - return reference; - } - - public void setReference(BigDecimal reference) { - this.reference = reference; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeProgrammaticConfigurationSupplierTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeProgrammaticConfigurationSupplierTest.java deleted file mode 100644 index 3620b9fb9..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeProgrammaticConfigurationSupplierTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.configuration; - -import com.fasterxml.jackson.core.Version; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; -import io.hypersistence.utils.hibernate.type.json.JsonBinaryType; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.Type; -import org.hibernate.jpa.boot.spi.TypeContributorList; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.Collections; -import java.util.Properties; -import java.util.TimeZone; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonBinaryTypeProgrammaticConfigurationSupplierTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - protected void additionalProperties(Properties properties) { - ObjectMapper objectMapper = new ObjectMapper().findAndRegisterModules(); - objectMapper.setTimeZone(TimeZone.getTimeZone("GMT")); - SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1, 0, 0, null, null, null)); - simpleModule.addSerializer(new MoneySerializer()); - objectMapper.registerModule(simpleModule); - - JsonBinaryType jsonBinaryType = new JsonBinaryType(objectMapper, Location.class); - - properties.put("hibernate.type_contributors", - (TypeContributorList) () -> Collections.singletonList( - (typeContributions, serviceRegistry) -> - typeContributions.contributeType( - jsonBinaryType, "location" - ) - ) - ); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - location.setReference(BigDecimal.valueOf(2.25262562526626D)); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - assertEquals("2.25", event.getLocation().getReference().toString()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event { - - @Id - private Long id; - - @Type(type = "location") - @Column(columnDefinition = "jsonb") - private Location location; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - } - - public static class Location implements Serializable { - - private String country; - - private String city; - - private BigDecimal reference; - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public BigDecimal getReference() { - return reference; - } - - public void setReference(BigDecimal reference) { - this.reference = reference; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeProgrammaticConfigurationTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeProgrammaticConfigurationTest.java deleted file mode 100644 index 1e563a64f..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/configuration/PostgreSQLJsonBinaryTypeProgrammaticConfigurationTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.configuration; - -import io.hypersistence.utils.hibernate.type.json.JsonBinaryType; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.Type; -import org.hibernate.jpa.boot.spi.TypeContributorList; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.Collections; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonBinaryTypeProgrammaticConfigurationTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Override - protected void additionalProperties(Properties properties) { - CustomObjectMapperSupplier customObjectMapperSupplier = new CustomObjectMapperSupplier(); - JsonBinaryType jsonBinaryType = new JsonBinaryType(customObjectMapperSupplier.get(), Location.class); - - properties.put("hibernate.type_contributors", - (TypeContributorList) () -> Collections.singletonList( - (typeContributions, serviceRegistry) -> - typeContributions.contributeType( - jsonBinaryType, "location" - ) - ) - ); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - location.setReference(BigDecimal.valueOf(2.25262562526626D)); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - assertEquals("2.25", event.getLocation().getReference().toString()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event { - - @Id - private Long id; - - @Type(type = "location") - @Column(columnDefinition = "jsonb") - private Location location; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - } - - public static class Location implements Serializable { - - private String country; - - private String city; - - private BigDecimal reference; - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public BigDecimal getReference() { - return reference; - } - - public void setReference(BigDecimal reference) { - this.reference = reference; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericH2JsonMapTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericH2JsonMapTest.java deleted file mode 100644 index c1044dd43..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericH2JsonMapTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.util.AbstractTest; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.H2DataSourceProvider; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class GenericH2JsonMapTest extends AbstractTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected DataSourceProvider dataSourceProvider() { - return new H2DataSourceProvider(); - } - - @Test - public void test() { - - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .addProperty("title", "High-Performance Java Persistence") - .addProperty("author", "Vlad Mihalcea") - .addProperty("publisher", "Amazon") - .addProperty("price", "$44.95") - ); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - Map bookProperties = book.getProperties(); - - assertEquals( - "High-Performance Java Persistence", - bookProperties.get("title") - ); - - assertEquals( - "Vlad Mihalcea", - bookProperties.get("author") - ); - }); - } - - @Entity(name = "Book") - @TypeDef(name = "json", typeClass = JsonType.class) - public static class Book { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @NaturalId - @Column(length = 15) - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "json") - private Map properties = new HashMap<>(); - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public Map getProperties() { - return properties; - } - - public Book setProperties(Map properties) { - this.properties = properties; - return this; - } - - public Book addProperty(String key, String value) { - properties.put(key, value); - return this; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericMySQLJsonMapTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericMySQLJsonMapTest.java deleted file mode 100644 index 5d9dd7cae..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericMySQLJsonMapTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class GenericMySQLJsonMapTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .addProperty("title", "High-Performance Java Persistence") - .addProperty("author", "Vlad Mihalcea") - .addProperty("publisher", "Amazon") - .addProperty("price", "$44.95") - ); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - Map bookProperties = book.getProperties(); - - assertEquals( - "High-Performance Java Persistence", - bookProperties.get("title") - ); - - assertEquals( - "Vlad Mihalcea", - bookProperties.get("author") - ); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - @Column(length = 15) - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "json") - private Map properties = new HashMap<>(); - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public Map getProperties() { - return properties; - } - - public Book setProperties(Map properties) { - this.properties = properties; - return this; - } - - public Book addProperty(String key, String value) { - properties.put(key, value); - return this; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericMySQLJsonTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericMySQLJsonTypeTest.java deleted file mode 100644 index e5d6b92c3..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericMySQLJsonTypeTest.java +++ /dev/null @@ -1,155 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.type.model.Location; -import io.hypersistence.utils.hibernate.type.model.Ticket; -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.annotations.Type; -import org.hibernate.query.NativeQuery; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class GenericMySQLJsonTypeTest extends AbstractMySQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - Participant.class - }; - } - - @Override - protected String[] packages() { - return new String[]{ - Location.class.getPackage().getName() - }; - } - - private Event _event; - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - - Event event = new Event(); - event.setId(1L); - event.setAlternativeLocations(Arrays.asList(location)); - entityManager.persist(event); - - _event = event; - }); - } - - @Test - public void test() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - assertEquals(1, event.getAlternativeLocations().size()); - assertEquals("Cluj-Napoca", event.getAlternativeLocations().get(0).getCity()); - assertEquals("Romania", event.getAlternativeLocations().get(0).getCountry()); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertSelectCount(1); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Test - public void testBulkUpdate() { - doInJPA(entityManager -> { - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Sibiu"); - - entityManager.createNativeQuery( - "update Event " + - "set location = :location " + - "where id = :id") - .setParameter("id", _event.getId()) - .unwrap(NativeQuery.class) - .setParameter("location", location, new JsonType(Location.class)) - .executeUpdate(); - - Event event = entityManager.find(Event.class, _event.getId()); - assertEquals("Sibiu", event.getLocation().getCity()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event extends BaseEntity { - - @Type(type = "json") - @Column(columnDefinition = "json") - private Location location; - - @Type( - type = "json" - ) - @Column(columnDefinition = "json") - private List alternativeLocations; - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - - public List getAlternativeLocations() { - return alternativeLocations; - } - - public void setAlternativeLocations(List alternativeLocations) { - this.alternativeLocations = alternativeLocations; - } - } - - @Entity(name = "Participant") - @Table(name = "participant") - public static class Participant extends BaseEntity { - - @Type(type = "json") - @Column(columnDefinition = "json") - private Ticket ticket; - - @ManyToOne - private Event event; - - public Ticket getTicket() { - return ticket; - } - - public void setTicket(Ticket ticket) { - this.ticket = ticket; - } - - public Event getEvent() { - return event; - } - - public void setEvent(Event event) { - this.event = event; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOffsetDateTimeJsonTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOffsetDateTimeJsonTest.java deleted file mode 100644 index 5fc3de7bf..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOffsetDateTimeJsonTest.java +++ /dev/null @@ -1,156 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import java.io.Serializable; -import java.math.BigDecimal; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * @author Vlad Mihalcea - */ -public class GenericOffsetDateTimeJsonTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - }; - } - - @Test - public void test() { - OffsetDateTime dateTime = OffsetDateTime.of(2015, 10, 1, 9, 0, 0, 0, ZoneOffset.ofHours(2)); - - doInJPA(entityManager -> { - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - location.setRentedAt(dateTime); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - assertEquals(dateTime, event.getLocation().getRentedAt()); - }); - } - - @Test - public void testWithDouble() { - OffsetDateTime dateTime = OffsetDateTime.of(2022, 7, 14, 11, 37, 0, 0, ZoneOffset.ofHours(0)); - - //2022-07-14T11:37Z - String dateAsDouble = "1657798620.121624"; - String json = String.format("{\n" + - "\"country\":\"Romania\",\n" + - "\"city\":\"Cluj-Napoca\",\n" + - "\"rentedAt\": %s\n" + - "}", dateAsDouble); - - doInJDBC(connection -> { - String sql = "INSERT INTO EVENT (ID, LOCATION) VALUES (1, ?::JSON)"; - try ( - PreparedStatement statement = connection.prepareStatement(sql); - ) { - statement.setObject(1, json); - statement.executeUpdate(); - } catch (SQLException e) { - fail(e.getMessage()); - } - }); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, 1L); - assertEquals(dateTime, event.getLocation().getRentedAt()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - @TypeDef(defaultForType = Location.class, typeClass = JsonType.class) - public static class Event { - - @Id - private Long id; - - @Column(columnDefinition = "jsonb") - private Location location; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - } - - public static class Location implements Serializable { - - private String country; - - private String city; - - private BigDecimal reference; - - private OffsetDateTime rentedAt; - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public BigDecimal getReference() { - return reference; - } - - public void setReference(BigDecimal reference) { - this.reference = reference; - } - - public OffsetDateTime getRentedAt() { - return rentedAt; - } - - public void setRentedAt(OffsetDateTime rentedAt) { - this.rentedAt = rentedAt; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonMapTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonMapTest.java deleted file mode 100644 index ecf282f97..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonMapTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.util.AbstractOracleIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.Check; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class GenericOracleJsonMapTest extends AbstractOracleIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .addProperty("title", "High-Performance Java Persistence") - .addProperty("author", "Vlad Mihalcea") - .addProperty("publisher", "Amazon") - .addProperty("price", "$44.95") - ); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - Map bookProperties = book.getProperties(); - - assertEquals( - "High-Performance Java Persistence", - bookProperties.get("title") - ); - - assertEquals( - "Vlad Mihalcea", - bookProperties.get("author") - ); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - @Column(length = 15) - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "VARCHAR2(1000)") - @Check(constraints = "properties IS JSON") - private Map properties = new HashMap<>(); - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public Map getProperties() { - return properties; - } - - public Book setProperties(Map properties) { - this.properties = properties; - return this; - } - - public Book addProperty(String key, String value) { - properties.put(key, value); - return this; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeBlobPropertyParameterSettingTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeBlobPropertyParameterSettingTest.java deleted file mode 100644 index ddbcbb4d6..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeBlobPropertyParameterSettingTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.type.json.JsonBlobType; -import io.hypersistence.utils.hibernate.util.AbstractOracleIntegrationTest; -import io.hypersistence.utils.hibernate.util.transaction.JPATransactionFunction; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.query.NativeQuery; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class GenericOracleJsonTypeBlobPropertyParameterSettingTest extends AbstractOracleIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = entityManager - .createQuery( - "select b " + - "from Book b " + - "where b.isbn = :isbn", Book.class) - .setParameter("isbn", "978-9730228236") - .getSingleResult(); - - LOGGER.info("Book details: {}", book.getProperties()); - - assertTrue(book.getProperties().replaceAll(" ", "").contains("\"price\":44.99")); - - book.setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - JsonNode properties = (JsonNode) entityManager - .createNativeQuery( - "SELECT " + - " properties AS properties " + - "FROM book " + - "WHERE " + - " isbn = :isbn") - .setParameter("isbn", "978-9730228236") - .unwrap(NativeQuery.class) - .addScalar("properties", new JsonBlobType(JsonNode.class)) - .uniqueResult(); - - assertEquals("High-Performance Java Persistence", properties.get("title").asText()); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = (Book) entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - book.setProperties(null); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertNull(book.getProperties()); - - return null; - } - }); - } - - @Entity(name = "Book") - @Table(name = "book") - - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "io.hypersistence.utils.hibernate.type.json.JsonType") - @Column(columnDefinition = "BLOB") - private String properties; - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public String getProperties() { - return properties; - } - - public Book setProperties(String properties) { - this.properties = properties; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeBlobPropertyTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeBlobPropertyTest.java deleted file mode 100644 index 3b81e433a..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeBlobPropertyTest.java +++ /dev/null @@ -1,164 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.type.json.JsonBlobType; -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.util.AbstractOracleIntegrationTest; -import io.hypersistence.utils.hibernate.util.transaction.JPATransactionFunction; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.query.NativeQuery; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class GenericOracleJsonTypeBlobPropertyTest extends AbstractOracleIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = entityManager - .createQuery( - "select b " + - "from Book b " + - "where b.isbn = :isbn", Book.class) - .setParameter("isbn", "978-9730228236") - .getSingleResult(); - - LOGGER.info("Book details: {}", book.getProperties()); - - assertTrue(book.getProperties().replaceAll(" ", "").contains("\"price\":44.99")); - - book.setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - JsonNode properties = (JsonNode) entityManager - .createNativeQuery( - "SELECT " + - " properties AS properties " + - "FROM book " + - "WHERE " + - " isbn = :isbn") - .setParameter("isbn", "978-9730228236") - .unwrap(NativeQuery.class) - .addScalar("properties", new JsonBlobType(JsonNode.class)) - .uniqueResult(); - - assertEquals("High-Performance Java Persistence", properties.get("title").asText()); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = (Book) entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - book.setProperties(null); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertNull(book.getProperties()); - - return null; - } - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "BLOB") - private String properties; - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public String getProperties() { - return properties; - } - - public Book setProperties(String properties) { - this.properties = properties; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypePropertyTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypePropertyTest.java deleted file mode 100644 index e28afa51c..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypePropertyTest.java +++ /dev/null @@ -1,164 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.type.json.JsonStringType; -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.util.AbstractOracleIntegrationTest; -import io.hypersistence.utils.hibernate.util.transaction.JPATransactionFunction; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.query.NativeQuery; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class GenericOracleJsonTypePropertyTest extends AbstractOracleIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = entityManager - .createQuery( - "select b " + - "from Book b " + - "where b.isbn = :isbn", Book.class) - .setParameter("isbn", "978-9730228236") - .getSingleResult(); - - LOGGER.info("Book details: {}", book.getProperties()); - - assertTrue(book.getProperties().contains("\"price\":44.99")); - - book.setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - JsonNode properties = (JsonNode) entityManager - .createNativeQuery( - "SELECT " + - " properties AS properties " + - "FROM book " + - "WHERE " + - " isbn = :isbn") - .setParameter("isbn", "978-9730228236") - .unwrap(NativeQuery.class) - .addScalar("properties", new JsonStringType(JsonNode.class)) - .uniqueResult(); - - assertEquals("High-Performance Java Persistence", properties.get("title").asText()); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = (Book) entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - book.setProperties(null); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertNull(book.getProperties()); - - return null; - } - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "json") - private String properties; - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public String getProperties() { - return properties; - } - - public Book setProperties(String properties) { - this.properties = properties; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeVarcharPropertyTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeVarcharPropertyTest.java deleted file mode 100644 index ceffe5ef3..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericOracleJsonTypeVarcharPropertyTest.java +++ /dev/null @@ -1,166 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.type.json.JsonStringType; -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.util.AbstractOracleIntegrationTest; -import io.hypersistence.utils.hibernate.util.transaction.JPATransactionFunction; -import org.hibernate.Session; -import org.hibernate.annotations.Check; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.query.NativeQuery; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class GenericOracleJsonTypeVarcharPropertyTest extends AbstractOracleIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = entityManager - .createQuery( - "select b " + - "from Book b " + - "where b.isbn = :isbn", Book.class) - .setParameter("isbn", "978-9730228236") - .getSingleResult(); - - LOGGER.info("Book details: {}", book.getProperties()); - - assertTrue(book.getProperties().replaceAll(" ", "").contains("\"price\":44.99")); - - book.setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - JsonNode properties = (JsonNode) entityManager - .createNativeQuery( - "SELECT " + - " properties AS properties " + - "FROM book " + - "WHERE " + - " isbn = :isbn") - .setParameter("isbn", "978-9730228236") - .unwrap(NativeQuery.class) - .addScalar("properties", new JsonStringType(JsonNode.class)) - .uniqueResult(); - - assertEquals("High-Performance Java Persistence", properties.get("title").asText()); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = (Book) entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - book.setProperties(null); - - return null; - } - }); - - doInJPA(new JPATransactionFunction() { - @Override - public Void apply(EntityManager entityManager) { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertNull(book.getProperties()); - - return null; - } - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "VARCHAR2(1000)") - @Check(constraints = "properties IS JSON") - private String properties; - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public String getProperties() { - return properties; - } - - public Book setProperties(String properties) { - this.properties = properties; - return this; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonMapTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonMapTest.java deleted file mode 100644 index d43499399..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonMapTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class GenericPostgreSQLJsonMapTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .addProperty("title", "High-Performance Java Persistence") - .addProperty("author", "Vlad Mihalcea") - .addProperty("publisher", "Amazon") - .addProperty("price", "$44.95") - ); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - Map bookProperties = book.getProperties(); - - assertEquals( - "High-Performance Java Persistence", - bookProperties.get("title") - ); - - assertEquals( - "Vlad Mihalcea", - bookProperties.get("author") - ); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - @Column(length = 15) - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "jsonb") - private Map properties = new HashMap<>(); - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public Map getProperties() { - return properties; - } - - public Book setProperties(Map properties) { - this.properties = properties; - return this; - } - - public Book addProperty(String key, String value) { - properties.put(key, value); - return this; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonStringTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonStringTest.java deleted file mode 100644 index 0c52feee3..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonStringTest.java +++ /dev/null @@ -1,147 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import com.fasterxml.jackson.databind.JsonNode; -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.query.NativeQuery; -import org.junit.Test; - -import javax.persistence.*; - -import static org.junit.Assert.*; - -/** - * @author Vlad Mihalcea - */ -public class GenericPostgreSQLJsonStringTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void afterInit() { - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99" + - "}" - ) - ); - }); - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - book.setProperties( - "{" + - " \"title\": \"High-Performance Java Persistence\"," + - " \"author\": \"Vlad Mihalcea\"," + - " \"publisher\": \"Amazon\"," + - " \"price\": 44.99," + - " \"url\": \"https://www.amazon.com/High-Performance-Java-Persistence-Vlad-Mihalcea/dp/973022823X/\"" + - "}" - ); - }); - - doInJPA(entityManager -> { - JsonNode properties = (JsonNode) entityManager - .createNativeQuery( - "SELECT " + - " properties AS properties " + - "FROM book " + - "WHERE " + - " isbn = :isbn") - .setParameter("isbn", "978-9730228236") - .unwrap(NativeQuery.class) - .addScalar("properties", new JsonType(JsonNode.class)) - .getSingleResult(); - - assertEquals("High-Performance Java Persistence", properties.get("title").asText()); - }); - } - - @Test - public void testNullValue() { - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - book.setProperties(null); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertNull(book.getProperties()); - }); - } - - @Test - public void testLoad() { - doInJPA(entityManager -> { - Session session = entityManager.unwrap(Session.class); - Book book = session - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - assertTrue(book.getProperties().contains("\"price\": 44.99")); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "jsonb") - private String properties; - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public String getProperties() { - return properties; - } - - public Book setProperties(String properties) { - this.properties = properties; - return this; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonTypeTest.java deleted file mode 100644 index 2df0690dd..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericPostgreSQLJsonTypeTest.java +++ /dev/null @@ -1,157 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import io.hypersistence.utils.hibernate.type.model.Location; -import io.hypersistence.utils.hibernate.type.model.Ticket; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import io.hypersistence.utils.jdbc.validator.SQLStatementCountValidator; -import org.hibernate.annotations.Type; -import org.hibernate.query.NativeQuery; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class GenericPostgreSQLJsonTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Event.class, - Participant.class - }; - } - - @Override - protected String[] packages() { - return new String[]{ - Location.class.getPackage().getName() - }; - } - - private Event _event; - - private Participant _participant; - - @Override - protected void afterInit() { - - doInJPA(entityManager -> { - Event nullEvent = new Event(); - nullEvent.setId(0L); - entityManager.persist(nullEvent); - - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Cluj-Napoca"); - - Event event = new Event(); - event.setId(1L); - event.setLocation(location); - entityManager.persist(event); - - Ticket ticket = new Ticket(); - ticket.setPrice(12.34d); - ticket.setRegistrationCode("ABC123"); - - Participant participant = new Participant(); - participant.setId(1L); - participant.setTicket(ticket); - participant.setEvent(event); - - entityManager.persist(participant); - - _event = event; - _participant = participant; - }); - } - - @Test - public void testLoad() { - SQLStatementCountValidator.reset(); - - doInJPA(entityManager -> { - Event event = entityManager.find(Event.class, _event.getId()); - assertEquals("Romania", event.getLocation().getCountry()); - assertEquals("Cluj-Napoca", event.getLocation().getCity()); - }); - - SQLStatementCountValidator.assertTotalCount(1); - SQLStatementCountValidator.assertSelectCount(1); - SQLStatementCountValidator.assertUpdateCount(0); - } - - @Test - public void testBulkUpdate() { - doInJPA(entityManager -> { - Location location = new Location(); - location.setCountry("Romania"); - location.setCity("Sibiu"); - - entityManager.createNativeQuery( - "update Event " + - "set location = :location " + - "where id = :id") - .setParameter("id", _event.getId()) - .unwrap(NativeQuery.class) - .setParameter("location", location, new JsonType(Location.class)) - .executeUpdate(); - - Event event = entityManager.find(Event.class, _event.getId()); - assertEquals("Sibiu", event.getLocation().getCity()); - }); - } - - @Entity(name = "Event") - @Table(name = "event") - public static class Event extends BaseEntity { - - @Type(type = "io.hypersistence.utils.hibernate.type.json.JsonType") - @Column(columnDefinition = "jsonb") - private Location location; - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - } - - @Entity(name = "Participant") - @Table(name = "participant") - public static class Participant extends BaseEntity { - - @Type(type = "io.hypersistence.utils.hibernate.type.json.JsonType") - @Column(columnDefinition = "jsonb") - private Ticket ticket; - - @ManyToOne - private Event event; - - public Ticket getTicket() { - return ticket; - } - - public void setTicket(Ticket ticket) { - this.ticket = ticket; - } - - public Event getEvent() { - return event; - } - - public void setEvent(Event event) { - this.event = event; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericSQLServerJsonMapTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericSQLServerJsonMapTest.java deleted file mode 100644 index d32a1a754..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/generic/GenericSQLServerJsonMapTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.generic; - -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.util.AbstractSQLServerIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class GenericSQLServerJsonMapTest extends AbstractSQLServerIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .addProperty("title", "High-Performance Java Persistence") - .addProperty("author", "Vlad Mihalcea") - .addProperty("publisher", "Amazon") - .addProperty("price", "$44.95") - ); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - Map bookProperties = book.getProperties(); - - assertEquals( - "High-Performance Java Persistence", - bookProperties.get("title") - ); - - assertEquals( - "Vlad Mihalcea", - bookProperties.get("author") - ); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - @Column(length = 15) - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "NVARCHAR(1000) CHECK(ISJSON(properties) = 1)") - private Map properties = new HashMap<>(); - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public Map getProperties() { - return properties; - } - - public Book setProperties(Map properties) { - this.properties = properties; - return this; - } - - public Book addProperty(String key, String value) { - properties.put(key, value); - return this; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/internal/JacksonUtilTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/internal/JacksonUtilTest.java deleted file mode 100644 index 540710e65..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/internal/JacksonUtilTest.java +++ /dev/null @@ -1,168 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.internal; - -import org.junit.Test; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.Arrays; -import java.util.Currency; -import java.util.List; -import java.util.Objects; - -import static org.junit.Assert.assertEquals; - -public class JacksonUtilTest { - - @Test - public void cloneDeserializeStepErrorTest() { - MyEntity entity = new MyEntity(); - - entity.setValue("some value"); - entity.setPojos(Arrays.asList( - createMyPojo("first value", MyType.A, "1.1", createOtherPojo("USD")), - createMyPojo("second value", MyType.B, "1.2", createOtherPojo("BRL")) - )); - - MyEntity clone = JacksonUtil.clone(entity); - assertEquals(clone, entity); - - List clonePojos = JacksonUtil.clone(entity.getPojos()); - assertEquals(clonePojos, entity.getPojos()); - } - - private MyPojo createMyPojo(String value, MyType myType, String number, OtherPojo otherPojo) { - MyPojo myPojo = new MyPojo(); - myPojo.setValue(value); - myPojo.setType(myType); - myPojo.setNumber(new BigDecimal(number)); - myPojo.setOtherPojo(otherPojo); - return myPojo; - } - - private OtherPojo createOtherPojo(String currency) { - OtherPojo otherPojo = new OtherPojo(); - otherPojo.setCurrency(Currency.getInstance(currency)); - return otherPojo; - } - - public static class MyEntity { - private String value; - private List pojos; - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public List getPojos() { - return pojos; - } - - public void setPojos(List pojos) { - this.pojos = pojos; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - MyEntity myEntity = (MyEntity) o; - return Objects.equals(value, myEntity.value) && - Objects.equals(pojos, myEntity.pojos); - } - - @Override - public int hashCode() { - return Objects.hash(value, pojos); - } - } - - public static class MyPojo implements Serializable { - private String value; - private MyType type; - private BigDecimal number; - private OtherPojo otherPojo; - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public MyType getType() { - return type; - } - - public void setType(MyType type) { - this.type = type; - } - - public BigDecimal getNumber() { - return number; - } - - public void setNumber(BigDecimal number) { - this.number = number; - } - - public OtherPojo getOtherPojo() { - return otherPojo; - } - - public void setOtherPojo(OtherPojo otherPojo) { - this.otherPojo = otherPojo; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - MyPojo myPojo = (MyPojo) o; - return Objects.equals(value, myPojo.value) && - type == myPojo.type && - Objects.equals(number, myPojo.number) && - Objects.equals(otherPojo, myPojo.otherPojo); - } - - @Override - public int hashCode() { - return Objects.hash(value, type, number, otherPojo); - } - } - - public enum MyType { - A, B, C - } - - public static class OtherPojo implements Serializable { - private Currency currency; - - public Currency getCurrency() { - return currency; - } - - public void setCurrency(Currency currency) { - this.currency = currency; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - OtherPojo otherPojo = (OtherPojo) o; - return Objects.equals(currency, otherPojo.currency); - } - - @Override - public int hashCode() { - return Objects.hash(currency); - } - } - -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/internal/JsonTypeDescriptorTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/internal/JsonTypeDescriptorTest.java deleted file mode 100644 index 556da3917..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/internal/JsonTypeDescriptorTest.java +++ /dev/null @@ -1,192 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.internal; - -import io.hypersistence.utils.hibernate.type.model.BaseEntity; -import org.hibernate.HibernateException; -import org.junit.Test; - -import java.util.Arrays; -import java.util.LinkedHashSet; -import java.util.Objects; -import java.util.Set; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class JsonTypeDescriptorTest { - - /** - * If JSON serialization is used, - * the {@link JsonTypeDescriptor#areEqual(Object, Object)} depends on the order of the elements. - *

- * If the first collection contains the all element of another collection, - * then the two collection are equaled. - *

- * If the JSON object of the `theFirst` form would be : - * { - * "formFields":[1, 2, 3] - * } - *

- * And, the JSON object of the `theSecond` form would be: - * { - * "formFields":[3, 2, 1] - * } - *

- * The two JSON objects should be equal. - */ - @Test - public void testSetsAreEqual() { - JsonTypeDescriptor descriptor = new JsonTypeDescriptor(); - - Form theFirst = createForm(1, 2, 3); - Form theSecond = createForm(3, 2, 1); - assertTrue(descriptor.areEqual(theFirst, theSecond)); - } - - /** - * When the JSON object contains an explicit equals method, even when defined on the abstract super class {@link AbstractForm}, - * that equals method should be used. - * If JSON serialization is used, - * the {@link JsonTypeDescriptor#areEqual(Object, Object)} depends on the values of the fields. - * - * The equals method of the {@link FormImpl} always returns true, so the two objects should be equal, - * even when having a different value. - */ - @Test - public void testAbstractClassImplementationsAreEqual() { - JsonTypeDescriptor descriptor = new JsonTypeDescriptor(); - - FormImpl firstEntity = new FormImpl("value1"); - FormImpl secondEntity = new FormImpl("value2"); - - assertTrue(descriptor.areEqual(firstEntity, secondEntity)); - } - - /** - * When the JSON object does not contain an explicit equals method, it should not use the equals method {@link Object}, - * but should use the ObjectWrapperMapper to equal the objects as JsonNodes - */ - @Test - public void testClassesWithoutEqualsMethodShouldEqualAsJsonNodes() { - JsonTypeDescriptor descriptor = new JsonTypeDescriptor(); - - FormWithoutEqualsMethod firstEntity = new FormWithoutEqualsMethod("value1"); - FormWithoutEqualsMethod secondEntity = new FormWithoutEqualsMethod("value1"); - - assertTrue(descriptor.areEqual(firstEntity, secondEntity)); - } - - @Test - public void testNullPropertyType() { - JsonTypeDescriptor descriptor = new JsonTypeDescriptor(); - - try { - descriptor.wrap("a", null); - fail("Should fail because the propertyType is null!"); - } catch (HibernateException expected) { - } - } - - private Form createForm(Integer... numbers) { - Form form = new Form(); - - Set formFields = new LinkedHashSet<>(); - - Arrays.asList(numbers).forEach(o -> { - FormField formField = new FormField(); - formField.setNumber(o); - formFields.add(formField); - }); - - form.setFormFields(formFields); - - return form; - } - - public static class FormField { - - private Integer number; - - public Integer getNumber() { - return number; - } - - public void setNumber(Integer number) { - this.number = number; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - FormField formField = (FormField) o; - return Objects.equals(number, formField.number); - } - - @Override - public int hashCode() { - return Objects.hash(number); - } - } - - public static class Form extends BaseEntity { - - private Set formFields; - - public Set getFormFields() { - return formFields; - } - - public void setFormFields(Set formFields) { - this.formFields = formFields; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Form)) return false; - Form form = (Form) o; - return Objects.equals(formFields, form.formFields); - } - - @Override - public int hashCode() { - return Objects.hash(formFields); - } - } - - private static class FormImpl extends AbstractForm { - private FormImpl(String value) { - super(value); - } - } - - private static abstract class AbstractForm { - private String value; - - private AbstractForm(String value) { - this.value = value; - } - - @Override - public boolean equals(Object o) { - return true; - } - - @Override - public int hashCode() { - return Objects.hashCode(value); - } - } - - private static class FormWithoutEqualsMethod { - private String value; - - public String getValue() { - return value; - } - - private FormWithoutEqualsMethod(String value) { - this.value = value; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/polymorphic/PostgreSQLJsonPolymorphicListCustomTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/polymorphic/PostgreSQLJsonPolymorphicListCustomTypeTest.java deleted file mode 100644 index 0db66d35a..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/polymorphic/PostgreSQLJsonPolymorphicListCustomTypeTest.java +++ /dev/null @@ -1,229 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.polymorphic; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.type.util.ObjectMapperWrapper; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.jpa.boot.spi.TypeContributorList; -import org.junit.Test; - -import javax.persistence.*; -import java.io.Serializable; -import java.math.BigDecimal; -import java.time.OffsetDateTime; -import java.util.*; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonPolymorphicListCustomTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Override - protected void additionalProperties(Properties properties) { - ObjectMapper objectMapper = new ObjectMapper() - .findAndRegisterModules() - .registerModule( - new SimpleModule() - .addSerializer(OffsetDateTime.class, ObjectMapperWrapper.OffsetDateTimeSerializer.INSTANCE) - .addDeserializer(OffsetDateTime.class, ObjectMapperWrapper.OffsetDateTimeDeserializer.INSTANCE) - ); - - properties.put("hibernate.type_contributors", - (TypeContributorList) () -> Collections.singletonList( - (typeContributions, serviceRegistry) -> - typeContributions.contributeType( - new JsonType( - objectMapper.activateDefaultTypingAsProperty( - objectMapper.getPolymorphicTypeValidator(), - ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE, - "type" - ), - ArrayList.class - ) { - @Override - public String getName() { - return "json-polymorphic-list"; - } - } - ) - ) - ); - } - - @Test - public void test() { - - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .addCoupon(new AmountDiscountCoupon("PPP") - .setAmount(new BigDecimal("4.99")) - ) - .addCoupon(new PercentageDiscountCoupon("Black Friday") - .setPercentage(BigDecimal.valueOf(0.02)) - ) - ); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - Map topics = book.getCoupons() - .stream() - .collect( - Collectors.toMap( - DiscountCoupon::getName, - Function.identity() - ) - ); - - assertEquals(2, topics.size()); - AmountDiscountCoupon amountDiscountCoupon = (AmountDiscountCoupon) - topics.get("PPP"); - assertEquals( - new BigDecimal("4.99"), - amountDiscountCoupon.getAmount() - ); - - PercentageDiscountCoupon percentageDiscountCoupon = (PercentageDiscountCoupon) - topics.get("Black Friday"); - assertEquals( - BigDecimal.valueOf(0.02), - percentageDiscountCoupon.getPercentage() - ); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - @Column(length = 15) - private String isbn; - - @Type(type = "json-polymorphic-list") - @Column(columnDefinition = "jsonb") - private List coupons = new ArrayList<>(); - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public List getCoupons() { - return coupons; - } - - public Book setCoupons(List coupons) { - this.coupons = coupons; - return this; - } - - public Book addCoupon(DiscountCoupon topic) { - coupons.add(topic); - return this; - } - } - - public abstract static class DiscountCoupon implements Serializable { - - private String name; - - public DiscountCoupon() { - } - - public DiscountCoupon(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DiscountCoupon)) return false; - DiscountCoupon that = (DiscountCoupon) o; - return Objects.equals(getName(), that.getName()); - } - - @Override - public int hashCode() { - return Objects.hash(getName()); - } - } - - public static class AmountDiscountCoupon extends DiscountCoupon { - - private BigDecimal amount; - - public AmountDiscountCoupon() { - } - - public AmountDiscountCoupon(String name) { - super(name); - } - - public BigDecimal getAmount() { - return amount; - } - - public AmountDiscountCoupon setAmount(BigDecimal amount) { - this.amount = amount; - return this; - } - } - - public static class PercentageDiscountCoupon extends DiscountCoupon { - - private BigDecimal percentage; - - public PercentageDiscountCoupon() { - } - - public PercentageDiscountCoupon(String name) { - super(name); - } - - public BigDecimal getPercentage() { - return percentage; - } - - public PercentageDiscountCoupon setPercentage(BigDecimal amount) { - this.percentage = amount; - return this; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/polymorphic/PostgreSQLJsonPolymorphicListJacksonTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/polymorphic/PostgreSQLJsonPolymorphicListJacksonTypeTest.java deleted file mode 100644 index c445e07bf..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/json/polymorphic/PostgreSQLJsonPolymorphicListJacksonTypeTest.java +++ /dev/null @@ -1,229 +0,0 @@ -package io.hypersistence.utils.hibernate.type.json.polymorphic; - -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import io.hypersistence.utils.hibernate.type.json.JsonType; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.Session; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLJsonPolymorphicListJacksonTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - - doInJPA(entityManager -> { - entityManager.persist( - new Book() - .setIsbn("978-9730228236") - .addCoupon(new AmountDiscountCoupon("PPP") - .setAmount(new BigDecimal("4.99")) - ) - .addCoupon(new PercentageDiscountCoupon("Black Friday") - .setPercentage(BigDecimal.valueOf(0.02)) - ) - ); - }); - - doInJPA(entityManager -> { - Book book = entityManager.unwrap(Session.class) - .bySimpleNaturalId(Book.class) - .load("978-9730228236"); - - Map topics = book.getCoupons() - .stream() - .collect( - Collectors.toMap( - DiscountCoupon::getName, - Function.identity() - ) - ); - - assertEquals(2, topics.size()); - AmountDiscountCoupon amountDiscountCoupon = (AmountDiscountCoupon) topics.get("PPP"); - assertEquals( - new BigDecimal("4.99"), - amountDiscountCoupon.getAmount() - ); - - PercentageDiscountCoupon percentageDiscountCoupon = (PercentageDiscountCoupon) topics.get("Black Friday"); - assertEquals( - BigDecimal.valueOf(0.02), - percentageDiscountCoupon.getPercentage() - ); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "json", typeClass = JsonType.class) - public static class Book { - - @Id - @GeneratedValue - private Long id; - - @NaturalId - @Column(length = 15) - private String isbn; - - @Type(type = "json") - @Column(columnDefinition = "jsonb") - private List coupons = new ArrayList<>(); - - public String getIsbn() { - return isbn; - } - - public Book setIsbn(String isbn) { - this.isbn = isbn; - return this; - } - - public List getCoupons() { - return coupons; - } - - public Book setCoupons(List coupons) { - this.coupons = coupons; - return this; - } - - public Book addCoupon(DiscountCoupon topic) { - coupons.add(topic); - return this; - } - } - - @JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - include = JsonTypeInfo.As.PROPERTY, - property = "type" - ) - @JsonSubTypes({ - @JsonSubTypes.Type( - name = "discount.coupon.amount", - value = AmountDiscountCoupon.class - ), - @JsonSubTypes.Type( - name = "discount.coupon.percentage", - value = PercentageDiscountCoupon.class - ), - }) - public abstract static class DiscountCoupon implements Serializable { - - private String name; - - public DiscountCoupon() { - } - - public DiscountCoupon(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME) - public abstract String getType(); - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DiscountCoupon)) return false; - DiscountCoupon that = (DiscountCoupon) o; - return Objects.equals(getName(), that.getName()); - } - - @Override - public int hashCode() { - return Objects.hash(getName()); - } - } - - public static class AmountDiscountCoupon extends DiscountCoupon { - - public static final String DISCRIMINATOR = "discount.coupon.amount"; - - private BigDecimal amount; - - public AmountDiscountCoupon() { - } - - public AmountDiscountCoupon(String name) { - super(name); - } - - public BigDecimal getAmount() { - return amount; - } - - public AmountDiscountCoupon setAmount(BigDecimal amount) { - this.amount = amount; - return this; - } - - @Override - public String getType() { - return DISCRIMINATOR; - } - } - - public static class PercentageDiscountCoupon extends DiscountCoupon { - - public static final String DISCRIMINATOR = "discount.coupon.percentage"; - - private BigDecimal percentage; - - public PercentageDiscountCoupon() { - } - - public PercentageDiscountCoupon(String name) { - super(name); - } - - public BigDecimal getPercentage() { - return percentage; - } - - public PercentageDiscountCoupon setPercentage(BigDecimal amount) { - this.percentage = amount; - return this; - } - - @Override - public String getType() { - return DISCRIMINATOR; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/BaseEntity.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/BaseEntity.java deleted file mode 100644 index 379d8dc87..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/BaseEntity.java +++ /dev/null @@ -1,54 +0,0 @@ -package io.hypersistence.utils.hibernate.type.model; - -import io.hypersistence.utils.hibernate.type.array.*; -import io.hypersistence.utils.hibernate.type.json.*; -import org.hibernate.annotations.TypeDef; -import org.hibernate.annotations.TypeDefs; - -import javax.persistence.Id; -import javax.persistence.MappedSuperclass; -import javax.persistence.Version; - -/** - * @author Vlad Mihalcea - */ -@TypeDefs({ - @TypeDef(name = "uuid-array", typeClass = UUIDArrayType.class), - @TypeDef(name = "string-array", typeClass = StringArrayType.class), - @TypeDef(name = "int-array", typeClass = IntArrayType.class), - @TypeDef(name = "long-array", typeClass = LongArrayType.class), - @TypeDef(name = "double-array", typeClass = DoubleArrayType.class), - @TypeDef(name = "float-array", typeClass = FloatArrayType.class), - @TypeDef(name = "boolean-array", typeClass = BooleanArrayType.class), - @TypeDef(name = "date-array", typeClass = DateArrayType.class), - @TypeDef(name = "timestamp-array", typeClass = TimestampArrayType.class), - @TypeDef(name = "decimal-array", typeClass = DecimalArrayType.class), - @TypeDef(name = "localdate-array", typeClass = LocalDateArrayType.class), - @TypeDef(name = "localdatetime-array", typeClass = LocalDateTimeArrayType.class), - @TypeDef(name = "json", typeClass = JsonStringType.class), - @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class), - @TypeDef(name = "jsonb-node", typeClass = JsonNodeBinaryType.class), - @TypeDef(name = "json-node", typeClass = JsonNodeStringType.class), - @TypeDef(name = "jsonb-lob", typeClass = JsonBlobType.class), -}) -@MappedSuperclass -public class BaseEntity { - - @Id - private Long id; - - @Version - private Integer version; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Integer getVersion() { - return version; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Event.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Event.java deleted file mode 100644 index 81ec88d19..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Event.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.hypersistence.utils.hibernate.type.model; - -import org.hibernate.annotations.Type; - -import javax.persistence.*; - -/** - * @author Vlad Mihalcea - */ -@Entity(name = "Event") -@Table(name = "event") -public class Event extends BaseEntity { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - @Basic(fetch = FetchType.LAZY) - private Location location; - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Location.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Location.java deleted file mode 100644 index 54d7aacda..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Location.java +++ /dev/null @@ -1,52 +0,0 @@ -package io.hypersistence.utils.hibernate.type.model; - -import java.io.Serializable; -import java.util.Objects; - -/** - * @author Vlad Mihalcea - */ -public class Location implements Serializable { - - private String country; - - private String city; - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - @Override - public String toString() { - return "Location{" + - "country='" + country + '\'' + - ", city='" + city + '\'' + - '}'; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Location location = (Location) o; - return Objects.equals(country, location.country) && - Objects.equals(city, location.city); - } - - @Override - public int hashCode() { - return Objects.hash(country, city); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Participant.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Participant.java deleted file mode 100644 index 104ca9389..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Participant.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.hypersistence.utils.hibernate.type.model; - -import org.hibernate.annotations.Type; - -import javax.persistence.*; - -/** - * @author Vlad Mihalcea - */ -@Entity(name = "Participant") -@Table(name = "participant") -public class Participant extends BaseEntity { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - @Basic(fetch = FetchType.LAZY) - private Ticket ticket; - - @ManyToOne(fetch = FetchType.LAZY) - private Event event; - - public Ticket getTicket() { - return ticket; - } - - public void setTicket(Ticket ticket) { - this.ticket = ticket; - } - - public Event getEvent() { - return event; - } - - public void setEvent(Event event) { - this.event = event; - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Ticket.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Ticket.java deleted file mode 100644 index b51c3f5e9..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/model/Ticket.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.hypersistence.utils.hibernate.type.model; - -import java.io.Serializable; -import java.util.Objects; - -/** - * @author Vlad Mihalcea - */ -public class Ticket implements Serializable { - - private String registrationCode; - - private double price; - - public String getRegistrationCode() { - return registrationCode; - } - - public void setRegistrationCode(String registrationCode) { - this.registrationCode = registrationCode; - } - - public double getPrice() { - return price; - } - - public void setPrice(double price) { - this.price = price; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Ticket ticket = (Ticket) o; - return Double.compare(ticket.price, price) == 0 && - Objects.equals(registrationCode, ticket.registrationCode); - } - - @Override - public int hashCode() { - return Objects.hash(registrationCode, price); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLCurrencyUnitTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLCurrencyUnitTypeTest.java deleted file mode 100644 index ee01c04f8..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLCurrencyUnitTypeTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package io.hypersistence.utils.hibernate.type.money; - -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.money.CurrencyUnit; -import javax.persistence.*; - -import static javax.money.Monetary.getCurrency; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Piotr Olaszewski - */ -public class MySQLCurrencyUnitTypeTest extends AbstractMySQLIntegrationTest { - @Override - protected Class[] entities() { - return new Class[]{ - Order.class - }; - } - - @Test - public void testPersistAndReadCurrency() { - Order _order = doInJPA(entityManager -> { - Order order = new Order(); - order.setCurrency(getCurrency("EUR")); - - entityManager.persist(order); - - return order; - }); - - doInJPA(entityManager -> { - Order order = entityManager.find(Order.class, _order.getId()); - - assertEquals(order.getCurrency(), getCurrency("EUR")); - }); - } - - @Test - public void testSearchByCurrency() { - doInJPA(entityManager -> { - Order order1 = new Order(); - order1.setCurrency(getCurrency("EUR")); - entityManager.persist(order1); - - Order order2 = new Order(); - order2.setCurrency(getCurrency("PLN")); - entityManager.persist(order2); - }); - - doInJPA(entityManager -> { - CurrencyUnit currency = getCurrency("PLN"); - Order order = entityManager.createQuery("select o from Order o where o.currency = :currency", Order.class) - .setParameter("currency", currency) - .getSingleResult(); - - assertEquals(Long.valueOf(2), order.getId()); - }); - } - - @Test - public void testReturnNullCurrency() { - Long _id = doInJPA(entityManager -> { - Order order = new Order(); - entityManager.persist(order); - - return order.getId(); - }); - - doInJPA(entityManager -> { - Order order = entityManager.createQuery("select o from Order o where o.id = :id", Order.class) - .setParameter("id", _id) - .getSingleResult(); - - assertNull(order.getCurrency()); - }); - - doInJPA(entityManager -> { - CurrencyUnit currency = entityManager.createQuery("select o.currency from Order o where o.id = :id", CurrencyUnit.class) - .setParameter("id", _id) - .getSingleResult(); - - assertNull(currency); - }); - } - - @Entity(name = "Order") - @Table(name = "orders") - @TypeDef(typeClass = CurrencyUnitType.class, defaultForType = CurrencyUnit.class) - public static class Order { - @Id - @GeneratedValue - private Long id; - - @Column(name = "currency", columnDefinition = "char(3)") - private CurrencyUnit currency; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public CurrencyUnit getCurrency() { - return currency; - } - - public void setCurrency(CurrencyUnit currency) { - this.currency = currency; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeElementCollectionTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeElementCollectionTest.java deleted file mode 100644 index e2f1eb383..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeElementCollectionTest.java +++ /dev/null @@ -1,129 +0,0 @@ -package io.hypersistence.utils.hibernate.type.money; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.Columns; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.javamoney.moneta.Money; -import org.junit.Test; - -import javax.money.MonetaryAmount; -import javax.persistence.*; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Nikola Malenic - */ -public class MySQLMonetaryAmountTypeElementCollectionTest extends AbstractPostgreSQLIntegrationTest { - @Override - protected Class[] entities() { - return new Class[]{ - Salary.class - }; - } - - @Test - public void testPersistAndReadMoney() { - Salary _salary = doInJPA(entityManager -> { - Salary salary = new Salary(); - salary.getComponents().add(new SalaryComponent(Money.of(new BigDecimal("10.23"), "USD"))); - - entityManager.persist(salary); - - return salary; - }); - - doInJPA(entityManager -> { - Salary salary = entityManager.find(Salary.class, _salary.getId()); - - assertEquals(salary.getComponents().get(0).getValue(), Money.of(new BigDecimal("10.23"), "USD")); - }); - } - - @Test - public void testSearchByMoneyInElementCollection() { - doInJPA(entityManager -> { - Salary salary1 = new Salary(); - salary1.getComponents().add(new SalaryComponent(Money.of(new BigDecimal("10.23"), "USD"))); - salary1.getComponents().add(new SalaryComponent(Money.of(new BigDecimal("20.23"), "USD"))); - entityManager.persist(salary1); - - Salary salary2 = new Salary(); - salary2.getComponents().add(new SalaryComponent(Money.of(new BigDecimal("30.23"), "EUR"))); - entityManager.persist(salary2); - }); - - doInJPA(entityManager -> { - Money money = Money.of(new BigDecimal("10.23"), "USD"); - Salary salary = entityManager.createQuery("select s from Salary s join s.components sc where sc.value = :salary", Salary.class) - .setParameter("salary", money) - .getSingleResult(); - - assertEquals(1, salary.getId()); - }); - } - - @Entity(name = "Salary") - @Table(name = "salary") - public static class Salary { - @Id - @GeneratedValue - private long id; - - private String other; - - @ElementCollection - private List components = new ArrayList<>(); - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public List getComponents() { - return components; - } - - public String getOther() { - return other; - } - - public void setOther(String other) { - this.other = other; - } - } - - @Embeddable - @TypeDef(name = "monetary-amount-currency", typeClass = MonetaryAmountType.class, defaultForType = MonetaryAmount.class) - public static class SalaryComponent { - @Columns(columns = { - @Column(name = "salary_amount"), - @Column(name = "salary_currency") - }) - @Type(type = "monetary-amount-currency") - private MonetaryAmount value; - - public SalaryComponent(MonetaryAmount value) { - this.value = value; - } - - public SalaryComponent() { - - } - - public MonetaryAmount getValue() { - return value; - } - - public void setValue(MonetaryAmount value) { - this.value = value; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeEmbeddedTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeEmbeddedTest.java deleted file mode 100644 index f7f02d650..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeEmbeddedTest.java +++ /dev/null @@ -1,176 +0,0 @@ -package io.hypersistence.utils.hibernate.type.money; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.Columns; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.javamoney.moneta.Money; -import org.junit.Test; - -import javax.money.MonetaryAmount; -import javax.persistence.*; -import java.math.BigDecimal; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Nikola Malenic - */ -public class MySQLMonetaryAmountTypeEmbeddedTest extends AbstractPostgreSQLIntegrationTest { - @Override - protected Class[] entities() { - return new Class[]{ - Salary.class - }; - } - - @Test - public void testReadAndWrite() { - Salary _salary = doInJPA(entityManager -> { - Salary salary = new Salary(); - salary.setEmbeddedSalary(new EmbeddableMonetaryAmount(Money.of(new BigDecimal("10.23"), "USD"))); - - entityManager.persist(salary); - - return salary; - }); - - doInJPA(entityManager -> { - Salary salary = entityManager.find(Salary.class, _salary.getId()); - - assertEquals(salary.getEmbeddedSalary().amount, Money.of(new BigDecimal("10.23"), "USD")); - }); - - Salary salary = doInJPA(entityManager -> { - return entityManager.find(Salary.class, _salary.getId()); - }); - - salary.setEmbeddedSalary(new EmbeddableMonetaryAmount(Money.of(new BigDecimal("10.49"), "USD"))); - - doInJPA(entityManager -> { - entityManager.merge(salary); - }); - } - - @Test - public void testSearchByMoney() { - doInJPA(entityManager -> { - Salary salary1 = new Salary(); - salary1.setEmbeddedSalary(new EmbeddableMonetaryAmount(Money.of(new BigDecimal("10.23"), "USD"))); - entityManager.persist(salary1); - - Salary salary2 = new Salary(); - salary2.setEmbeddedSalary(new EmbeddableMonetaryAmount((Money.of(new BigDecimal("20.23"), "EUR")))); - entityManager.persist(salary2); - }); - - doInJPA(entityManager -> { - Money money = Money.of(new BigDecimal("10.23"), "USD"); - Salary salary = entityManager.createQuery("select s from Salary s where s" + - ".embeddedSalary.amount = :amount", Salary.class) - .setParameter("amount", money) - .getSingleResult(); - - assertEquals(1, salary.getId()); - }); - } - - @Test - public void testSearchByComponents() { - doInJPA(entityManager -> { - Salary salary1 = new Salary(); - salary1.setEmbeddedSalary(new EmbeddableMonetaryAmount((Money.of(new BigDecimal("10.23"), "USD")))); - entityManager.persist(salary1); - - Salary salary2 = new Salary(); - salary2.setEmbeddedSalary(new EmbeddableMonetaryAmount((Money.of(new BigDecimal("20.23"), "EUR")))); - entityManager.persist(salary2); - }); - - doInJPA(entityManager -> { - BigDecimal amount = BigDecimal.TEN; - List salaries = entityManager.createQuery("select s from Salary s where s.embeddedSalary.amount.amount >= :amount", Salary.class) - .setParameter("amount", amount) - .getResultList(); - - - assertEquals(1L, salaries.get(0).getId()); - assertEquals(2L, salaries.get(1).getId()); - }); - - doInJPA(entityManager -> { - String currency = "USD"; - Salary salary = entityManager.createQuery("select s from Salary s where s.embeddedSalary.amount.currency = :currency", Salary.class) - .setParameter("currency", currency) - .getSingleResult(); - - assertEquals(1L, salary.getId()); - }); - } - - @Entity(name = "Salary") - @Table(name = "salary") - public static class Salary { - @Id - @GeneratedValue - private long id; - - private String other; - - @Embedded - private EmbeddableMonetaryAmount embeddedSalary; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public EmbeddableMonetaryAmount getEmbeddedSalary() { - return embeddedSalary; - } - - public void setEmbeddedSalary(EmbeddableMonetaryAmount embeddedSalary) { - this.embeddedSalary = embeddedSalary; - } - - public String getOther() { - return other; - } - - public void setOther(String other) { - this.other = other; - } - } - - @Embeddable - @TypeDef(name = "monetary-amount-currency", typeClass = MonetaryAmountType.class, defaultForType = MonetaryAmount.class) - public static class EmbeddableMonetaryAmount { - @Columns(columns = { - @Column(name = "salary_amount"), - @Column(name = "salary_currency") - }) - @Type(type = "monetary-amount-currency") - private MonetaryAmount amount; - - public EmbeddableMonetaryAmount(MonetaryAmount amount) { - this.amount = amount; - } - - public EmbeddableMonetaryAmount() { - - } - - - public MonetaryAmount getAmount() { - return amount; - } - - public void setAmount(MonetaryAmount amount) { - this.amount = amount; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeTest.java deleted file mode 100644 index cf2654106..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/MySQLMonetaryAmountTypeTest.java +++ /dev/null @@ -1,204 +0,0 @@ -package io.hypersistence.utils.hibernate.type.money; - -import io.hypersistence.utils.hibernate.util.AbstractMySQLIntegrationTest; -import org.hibernate.annotations.Columns; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.hibernate.envers.Audited; -import org.javamoney.moneta.Money; -import org.junit.Test; - -import javax.money.MonetaryAmount; -import javax.persistence.*; -import java.math.BigDecimal; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Piotr Olaszewski - */ -public class MySQLMonetaryAmountTypeTest extends AbstractMySQLIntegrationTest { - @Override - protected Class[] entities() { - return new Class[]{ - Salary.class, - Bonus.class, - }; - } - - @Test - public void testReadAndWrite() { - Salary _salary = doInJPA(entityManager -> { - Salary salary = new Salary(); - salary.setSalary(Money.of(new BigDecimal("10.23"), "USD")); - - entityManager.persist(salary); - - return salary; - }); - - doInJPA(entityManager -> { - Salary salary = entityManager.find(Salary.class, _salary.getId()); - - assertEquals(salary.getSalary(), Money.of(new BigDecimal("10.23"), "USD")); - }); - - Salary salary = doInJPA(entityManager -> { - return entityManager.find(Salary.class, _salary.getId()); - }); - - salary.setSalary(Money.of(new BigDecimal("10.49"), "USD")); - - doInJPA(entityManager -> { - entityManager.merge(salary); - }); - } - - @Test - public void testSaveUsingMerge() { - Salary _salary = doInJPA(entityManager -> { - Salary salary = new Salary(); - salary.setSalary(Money.of(new BigDecimal("10.23"), "USD")); - - return entityManager.merge(salary); - }); - - Bonus _bonus = doInJPA(entityManager -> { - Bonus bonus = new Bonus(); - bonus.setId(1L); - bonus.setBonus(Money.of(new BigDecimal("1.23"), "EUR")); - - return entityManager.merge(bonus); - }); - - doInJPA(entityManager -> { - Salary salary = entityManager.find(Salary.class, _salary.getId()); - assertEquals(salary.getSalary(), Money.of(new BigDecimal("10.23"), "USD")); - - Bonus bonus = entityManager.find(Bonus.class, 1L); - assertEquals(bonus.getBonus(), Money.of(new BigDecimal("1.23"), "EUR")); - }); - } - - @Test - public void testSearchByMoney() { - doInJPA(entityManager -> { - Salary salary1 = new Salary(); - salary1.setSalary(Money.of(new BigDecimal("10.23"), "USD")); - entityManager.persist(salary1); - - Salary salary2 = new Salary(); - salary2.setSalary(Money.of(new BigDecimal("20.23"), "EUR")); - entityManager.persist(salary2); - }); - - doInJPA(entityManager -> { - Money money = Money.of(new BigDecimal("10.23"), "USD"); - Salary salary = entityManager.createQuery("select s from Salary s where s.salary = :salary", Salary.class) - .setParameter("salary", money) - .getSingleResult(); - - assertEquals(Long.valueOf(1), salary.getId()); - }); - } - - @Test - public void testReturnNullMoney() { - Long _id = doInJPA(entityManager -> { - Salary salary = new Salary(); - entityManager.persist(salary); - return salary.getId(); - }); - - doInJPA(entityManager -> { - Salary salary = entityManager.createQuery("select s from Salary s where s.id = :id", Salary.class) - .setParameter("id", _id) - .getSingleResult(); - - assertNull(salary.getSalary()); - }); - - doInJPA(entityManager -> { - MonetaryAmount money = entityManager.createQuery("select s.salary from Salary s where s.id = :id", MonetaryAmount.class) - .setParameter("id", _id) - .getSingleResult(); - - assertNull(money); - }); - } - - @Entity(name = "Salary") - @Table(name = "salary") - @TypeDef(name = "monetary-amount-currency", typeClass = MonetaryAmountType.class, defaultForType = MonetaryAmount.class) - public static class Salary { - @Id - @GeneratedValue - private Long id; - - private String other; - - @Columns(columns = { - @Column(name = "salary_amount"), - @Column(name = "salary_currency") - }) - @Type(type = "monetary-amount-currency") - private MonetaryAmount salary; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public MonetaryAmount getSalary() { - return salary; - } - - public void setSalary(MonetaryAmount salary) { - this.salary = salary; - } - - public String getOther() { - return other; - } - - public void setOther(String other) { - this.other = other; - } - } - - @Audited - @Entity(name = "Bonus") - @Table(name = "bonus") - @TypeDef(name = "monetary-amount-currency", typeClass = MonetaryAmountType.class, defaultForType = MonetaryAmount.class) - public static class Bonus { - @Id - private Long id; - - @Columns(columns = { - @Column(name = "salary_amount"), - @Column(name = "salary_currency") - }) - @Type(type = "monetary-amount-currency") - private MonetaryAmount bonus; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public MonetaryAmount getBonus() { - return bonus; - } - - public void setBonus(MonetaryAmount bonus) { - this.bonus = bonus; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLCurrencyUnitTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLCurrencyUnitTypeTest.java deleted file mode 100644 index 1a87c45b5..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLCurrencyUnitTypeTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package io.hypersistence.utils.hibernate.type.money; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.money.CurrencyUnit; -import javax.persistence.*; - -import static javax.money.Monetary.getCurrency; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Piotr Olaszewski - */ -public class PostgreSQLCurrencyUnitTypeTest extends AbstractPostgreSQLIntegrationTest { - @Override - protected Class[] entities() { - return new Class[]{ - Order.class - }; - } - - @Test - public void testPersistAndReadCurrency() { - Order _order = doInJPA(entityManager -> { - Order order = new Order(); - order.setCurrency(getCurrency("EUR")); - - entityManager.persist(order); - - return order; - }); - - doInJPA(entityManager -> { - Order order = entityManager.find(Order.class, _order.getId()); - - assertEquals(order.getCurrency(), getCurrency("EUR")); - }); - } - - @Test - public void testSearchByCurrency() { - doInJPA(entityManager -> { - Order order1 = new Order(); - order1.setCurrency(getCurrency("EUR")); - entityManager.persist(order1); - - Order order2 = new Order(); - order2.setCurrency(getCurrency("PLN")); - entityManager.persist(order2); - }); - - doInJPA(entityManager -> { - CurrencyUnit currency = getCurrency("PLN"); - Order order = entityManager.createQuery("select o from Order o where o.currency = :currency", Order.class) - .setParameter("currency", currency) - .getSingleResult(); - - assertEquals(Long.valueOf(2), order.getId()); - }); - } - - @Test - public void testReturnNullCurrency() { - Long _id = doInJPA(entityManager -> { - Order order = new Order(); - entityManager.persist(order); - - return order.getId(); - }); - - doInJPA(entityManager -> { - Order order = entityManager.createQuery("select o from Order o where o.id = :id", Order.class) - .setParameter("id", _id) - .getSingleResult(); - - assertNull(order.getCurrency()); - }); - - doInJPA(entityManager -> { - CurrencyUnit currency = entityManager.createQuery("select o.currency from Order o where o.id = :id", CurrencyUnit.class) - .setParameter("id", _id) - .getSingleResult(); - - assertNull(currency); - }); - } - - @Entity(name = "Order") - @Table(name = "orders") - @TypeDef(typeClass = CurrencyUnitType.class, defaultForType = CurrencyUnit.class) - public static class Order { - @Id - @GeneratedValue - private Long id; - - @Column(name = "currency", columnDefinition = "char(3)") - private CurrencyUnit currency; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public CurrencyUnit getCurrency() { - return currency; - } - - public void setCurrency(CurrencyUnit currency) { - this.currency = currency; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeElementCollectionTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeElementCollectionTest.java deleted file mode 100644 index 6fc6dd7b6..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeElementCollectionTest.java +++ /dev/null @@ -1,129 +0,0 @@ -package io.hypersistence.utils.hibernate.type.money; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.Columns; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.javamoney.moneta.Money; -import org.junit.Test; - -import javax.money.MonetaryAmount; -import javax.persistence.*; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Nikola Malenic - */ -public class PostgreSQLMonetaryAmountTypeElementCollectionTest extends AbstractPostgreSQLIntegrationTest { - @Override - protected Class[] entities() { - return new Class[]{ - Salary.class - }; - } - - @Test - public void testPersistAndReadMoney() { - Salary _salary = doInJPA(entityManager -> { - Salary salary = new Salary(); - salary.getComponents().add(new SalaryComponent(Money.of(new BigDecimal("10.23"), "USD"))); - - entityManager.persist(salary); - - return salary; - }); - - doInJPA(entityManager -> { - Salary salary = entityManager.find(Salary.class, _salary.getId()); - - assertEquals(salary.getComponents().get(0).getValue(), Money.of(new BigDecimal("10.23"), "USD")); - }); - } - - @Test - public void testSearchByMoneyInElementCollection() { - doInJPA(entityManager -> { - Salary salary1 = new Salary(); - salary1.getComponents().add(new SalaryComponent(Money.of(new BigDecimal("10.23"), "USD"))); - salary1.getComponents().add(new SalaryComponent(Money.of(new BigDecimal("20.23"), "USD"))); - entityManager.persist(salary1); - - Salary salary2 = new Salary(); - salary2.getComponents().add(new SalaryComponent(Money.of(new BigDecimal("30.23"), "EUR"))); - entityManager.persist(salary2); - }); - - doInJPA(entityManager -> { - Money money = Money.of(new BigDecimal("10.23"), "USD"); - Salary salary = entityManager.createQuery("select s from Salary s join s.components sc where sc.value = :salary", Salary.class) - .setParameter("salary", money) - .getSingleResult(); - - assertEquals(1, salary.getId()); - }); - } - - @Entity(name = "Salary") - @Table(name = "salary") - public static class Salary { - @Id - @GeneratedValue - private long id; - - private String other; - - @ElementCollection - private List components = new ArrayList<>(); - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public List getComponents() { - return components; - } - - public String getOther() { - return other; - } - - public void setOther(String other) { - this.other = other; - } - } - - @Embeddable - @TypeDef(name = "monetary-amount-currency", typeClass = MonetaryAmountType.class, defaultForType = MonetaryAmount.class) - public static class SalaryComponent { - @Columns(columns = { - @Column(name = "salary_amount"), - @Column(name = "salary_currency") - }) - @Type(type = "monetary-amount-currency") - private MonetaryAmount value; - - public SalaryComponent(MonetaryAmount value) { - this.value = value; - } - - public SalaryComponent() { - - } - - public MonetaryAmount getValue() { - return value; - } - - public void setValue(MonetaryAmount value) { - this.value = value; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeEmbeddedTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeEmbeddedTest.java deleted file mode 100644 index d91eaddc1..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeEmbeddedTest.java +++ /dev/null @@ -1,166 +0,0 @@ -package io.hypersistence.utils.hibernate.type.money; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.Columns; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.javamoney.moneta.Money; -import org.junit.Test; - -import javax.money.MonetaryAmount; -import javax.persistence.*; -import java.math.BigDecimal; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Nikola Malenic - */ -public class PostgreSQLMonetaryAmountTypeEmbeddedTest extends AbstractPostgreSQLIntegrationTest { - @Override - protected Class[] entities() { - return new Class[]{ - Salary.class - }; - } - - @Test - public void testPersistAndReadMoney() { - Salary _salary = doInJPA(entityManager -> { - Salary salary = new Salary(); - salary.setEmbeddedSalary(new EmbeddableMonetaryAmount(Money.of(new BigDecimal("10.23"), "USD"))); - - entityManager.persist(salary); - - return salary; - }); - - doInJPA(entityManager -> { - Salary salary = entityManager.find(Salary.class, _salary.getId()); - - assertEquals(salary.getEmbeddedSalary().amount, Money.of(new BigDecimal("10.23"), "USD")); - }); - } - - @Test - public void testSearchByMoney() { - doInJPA(entityManager -> { - Salary salary1 = new Salary(); - salary1.setEmbeddedSalary(new EmbeddableMonetaryAmount(Money.of(new BigDecimal("10.23"), "USD"))); - entityManager.persist(salary1); - - Salary salary2 = new Salary(); - salary2.setEmbeddedSalary(new EmbeddableMonetaryAmount((Money.of(new BigDecimal("20.23"), "EUR")))); - entityManager.persist(salary2); - }); - - doInJPA(entityManager -> { - Money money = Money.of(new BigDecimal("10.23"), "USD"); - Salary salary = entityManager.createQuery("select s from Salary s where s" + - ".embeddedSalary.amount = :amount", Salary.class) - .setParameter("amount", money) - .getSingleResult(); - - assertEquals(1, salary.getId()); - }); - } - - @Test - public void testSearchByComponents() { - doInJPA(entityManager -> { - Salary salary1 = new Salary(); - salary1.setEmbeddedSalary(new EmbeddableMonetaryAmount((Money.of(new BigDecimal("10.23"), "USD")))); - entityManager.persist(salary1); - - Salary salary2 = new Salary(); - salary2.setEmbeddedSalary(new EmbeddableMonetaryAmount((Money.of(new BigDecimal("20.23"), "EUR")))); - entityManager.persist(salary2); - }); - - doInJPA(entityManager -> { - BigDecimal amount = BigDecimal.TEN; - List salaries = entityManager.createQuery("select s from Salary s where s.embeddedSalary.amount.amount >= :amount", Salary.class) - .setParameter("amount", amount) - .getResultList(); - - - assertEquals(1L, salaries.get(0).getId()); - assertEquals(2L, salaries.get(1).getId()); - }); - - doInJPA(entityManager -> { - String currency = "USD"; - Salary salary = entityManager.createQuery("select s from Salary s where s.embeddedSalary.amount.currency = :currency", Salary.class) - .setParameter("currency", currency) - .getSingleResult(); - - assertEquals(1L, salary.getId()); - }); - } - - @Entity(name = "Salary") - @Table(name = "salary") - public static class Salary { - @Id - @GeneratedValue - private long id; - - private String other; - - @Embedded - private EmbeddableMonetaryAmount embeddedSalary; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public EmbeddableMonetaryAmount getEmbeddedSalary() { - return embeddedSalary; - } - - public void setEmbeddedSalary(EmbeddableMonetaryAmount embeddedSalary) { - this.embeddedSalary = embeddedSalary; - } - - public String getOther() { - return other; - } - - public void setOther(String other) { - this.other = other; - } - } - - @Embeddable - @TypeDef(name = "monetary-amount-currency", typeClass = MonetaryAmountType.class, defaultForType = MonetaryAmount.class) - public static class EmbeddableMonetaryAmount { - @Columns(columns = { - @Column(name = "salary_amount"), - @Column(name = "salary_currency") - }) - @Type(type = "monetary-amount-currency") - private MonetaryAmount amount; - - public EmbeddableMonetaryAmount(MonetaryAmount amount) { - this.amount = amount; - } - - public EmbeddableMonetaryAmount() { - - } - - - public MonetaryAmount getAmount() { - return amount; - } - - public void setAmount(MonetaryAmount amount) { - this.amount = amount; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeTest.java deleted file mode 100644 index 7660713d2..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/money/PostgreSQLMonetaryAmountTypeTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package io.hypersistence.utils.hibernate.type.money; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.Columns; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.javamoney.moneta.Money; -import org.junit.Test; - -import javax.money.MonetaryAmount; -import javax.persistence.*; -import java.math.BigDecimal; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Piotr Olaszewski - */ -public class PostgreSQLMonetaryAmountTypeTest extends AbstractPostgreSQLIntegrationTest { - @Override - protected Class[] entities() { - return new Class[]{ - Salary.class - }; - } - - @Test - public void testPersistAndReadMoney() { - Salary _salary = doInJPA(entityManager -> { - Salary salary = new Salary(); - salary.setSalary(Money.of(new BigDecimal("10.23"), "USD")); - - entityManager.persist(salary); - - return salary; - }); - - doInJPA(entityManager -> { - Salary salary = entityManager.find(Salary.class, _salary.getId()); - - assertEquals(salary.getSalary(), Money.of(new BigDecimal("10.23"), "USD")); - }); - } - - @Test - public void testSearchByMoney() { - doInJPA(entityManager -> { - Salary salary1 = new Salary(); - salary1.setSalary(Money.of(new BigDecimal("10.23"), "USD")); - entityManager.persist(salary1); - - Salary salary2 = new Salary(); - salary2.setSalary(Money.of(new BigDecimal("20.23"), "EUR")); - entityManager.persist(salary2); - }); - - doInJPA(entityManager -> { - Money money = Money.of(new BigDecimal("10.23"), "USD"); - Salary salary = entityManager.createQuery("select s from Salary s where s.salary = :salary", Salary.class) - .setParameter("salary", money) - .getSingleResult(); - - assertEquals(1L, salary.getId()); - }); - } - - @Test - public void testReturnNullMoney() { - Long _id = doInJPA(entityManager -> { - Salary salary = new Salary(); - entityManager.persist(salary); - return salary.getId(); - }); - - doInJPA(entityManager -> { - Salary salary = entityManager.createQuery("select s from Salary s where s.id = :id", Salary.class) - .setParameter("id", _id) - .getSingleResult(); - - assertNull(salary.getSalary()); - }); - - doInJPA(entityManager -> { - MonetaryAmount money = entityManager.createQuery("select s.salary from Salary s where s.id = :id", MonetaryAmount.class) - .setParameter("id", _id) - .getSingleResult(); - - assertNull(money); - }); - } - - @Test - public void testSearchByComponents() { - doInJPA(entityManager -> { - Salary salary1 = new Salary(); - salary1.setSalary(Money.of(new BigDecimal("10.23"), "USD")); - entityManager.persist(salary1); - - Salary salary2 = new Salary(); - salary2.setSalary(Money.of(new BigDecimal("20.23"), "EUR")); - entityManager.persist(salary2); - }); - - doInJPA(entityManager -> { - BigDecimal amount = BigDecimal.TEN; - List salaries = entityManager.createQuery("select s from Salary s where s.salary.amount >= :amount", Salary.class) - .setParameter("amount", amount) - .getResultList(); - - assertEquals(1L, salaries.get(0).getId()); - assertEquals(2L, salaries.get(1).getId()); - }); - - doInJPA(entityManager -> { - String currency = "USD"; - Salary salary = entityManager.createQuery("select s from Salary s where s.salary.currency = :currency", Salary.class) - .setParameter("currency", currency) - .getSingleResult(); - - assertEquals(1L, salary.getId()); - }); - } - - @Entity(name = "Salary") - @Table(name = "salary") - @TypeDef(name = "monetary-amount-currency", typeClass = MonetaryAmountType.class, defaultForType = MonetaryAmount.class) - public static class Salary { - @Id - @GeneratedValue - private long id; - - private String other; - - @Columns(columns = { - @Column(name = "salary_amount"), - @Column(name = "salary_currency") - }) - @Type(type = "monetary-amount-currency") - private MonetaryAmount salary; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public MonetaryAmount getSalary() { - return salary; - } - - public void setSalary(MonetaryAmount salary) { - this.salary = salary; - } - - public String getOther() { - return other; - } - - public void setOther(String other) { - this.other = other; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeTypeDSTTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeTypeDSTTest.java deleted file mode 100644 index 453b4ef41..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeTypeDSTTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package io.hypersistence.utils.hibernate.type.range; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; - -import static io.hypersistence.utils.hibernate.type.range.Range.zonedDateTimeRange; -import static org.junit.Assert.assertEquals; - -/** - * @author Edgar Asatryan - */ -public class PostgreSQLRangeTypeDSTTest extends AbstractPostgreSQLIntegrationTest { - - // updated to cross DST boundary (31/9/2018) - private final Range tsTz = zonedDateTimeRange("[\"2018-05-03T10:15:30+12:00\",\"2018-12-03T10:15:30+12:00\"]"); - - @Override - protected Class[] entities() { - return new Class[]{ - Restriction.class - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Restriction restriction = new Restriction(); - restriction.setId(1L); - restriction.setRangeZonedDateTime(tsTz); - entityManager.persist(restriction); - - return restriction; - }); - - doInJPA(entityManager -> { - Restriction ar = entityManager.find(Restriction.class, 1L); - - ZoneId zone = ar.getRangeZonedDateTime().lower().getZone(); - - ZonedDateTime lower = tsTz.lower().withZoneSameInstant(zone); - - assertEquals(lower, ar.getRangeZonedDateTime().lower()); - assertEquals(LocalDateTime.parse("2018-12-03T10:15:30").atZone(ZoneId.systemDefault()).getOffset(), ar.getRangeZonedDateTime().upper().getOffset()); - }); - } - - @Entity(name = "AgeRestriction") - @Table(name = "age_restriction") - @TypeDef(name = "range", typeClass = PostgreSQLRangeType.class, defaultForType = Range.class) - public static class Restriction { - - @Id - private Long id; - - @Column(name = "r_tstzrange", columnDefinition = "tstzrange") - private Range rangeZonedDateTime; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Range getRangeZonedDateTime() { - return rangeZonedDateTime; - } - - public void setRangeZonedDateTime(Range rangeZonedDateTime) { - this.rangeZonedDateTime = rangeZonedDateTime; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeTypeTest.java deleted file mode 100644 index 6211a5935..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/PostgreSQLRangeTypeTest.java +++ /dev/null @@ -1,241 +0,0 @@ -package io.hypersistence.utils.hibernate.type.range; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; - -import static io.hypersistence.utils.hibernate.type.range.Range.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Edgar Asatryan - */ -public class PostgreSQLRangeTypeTest extends AbstractPostgreSQLIntegrationTest { - - private final Range numeric = Range.bigDecimalRange("[0.5,0.89]"); - - private final Range int8Range = Range.longRange("[0,18)"); - - private final Range int4Range = infinite(Integer.class); - - private final Range int4RangeEmpty = Range.integerRange("[123,123)"); - - private final Range int4RangeInfinity = Range.integerRange("[123,infinity)"); - - private final Range localDateTimeRange = Range.localDateTimeRange("[2014-04-28 16:00:49,2015-04-28 16:00:49]"); - - private final Range tsTz = zonedDateTimeRange("[\"2007-12-03T10:15:30+01:00\",\"2008-12-03T10:15:30+01:00\"]"); - - private final Range tsTzEmpty = zonedDateTimeRange("empty"); - - private final Range infinityTsTz = zonedDateTimeRange("[\"2007-12-03T10:15:30+01:00\",infinity)"); - - private final Range dateRange = Range.localDateRange("[1992-01-13,1995-01-13)"); - - @Override - protected Class[] entities() { - return new Class[]{ - Restriction.class - }; - } - - @Test - public void test() { - Restriction _restriction = doInJPA(entityManager -> { - entityManager.persist(new Restriction()); - - Restriction restriction = new Restriction(); - restriction.setRangeInt(int4Range); - restriction.setRangeIntEmpty(int4RangeEmpty); - restriction.setRangeIntInfinity(int4RangeInfinity); - restriction.setRangeLong(int8Range); - restriction.setRangeBigDecimal(numeric); - restriction.setRangeLocalDateTime(localDateTimeRange); - restriction.setRangeZonedDateTime(tsTz); - restriction.setRangeZonedDateTimeInfinity(infinityTsTz); - restriction.setRangeZonedDateTimeEmpty(tsTzEmpty); - restriction.setRangeLocalDate(dateRange); - entityManager.persist(restriction); - - return restriction; - }); - - doInJPA(entityManager -> { - Restriction restriction = entityManager.find(Restriction.class, _restriction.getId()); - - assertEquals(int4Range, restriction.getRangeInt()); - assertEquals(Range.emptyRange(Integer.class), restriction.getRangeIntEmpty()); - assertEquals(int4RangeInfinity, restriction.getRangeIntInfinity()); - assertEquals(int8Range, restriction.getRangeLong()); - assertEquals(numeric, restriction.getRangeBigDecimal()); - assertEquals(localDateTimeRange, restriction.getLocalDateTimeRange()); - assertEquals(dateRange, restriction.getRangeLocalDate()); - - ZoneId zone = restriction.getRangeZonedDateTime().lower().getZone(); - - ZonedDateTime lower = tsTz.lower().withZoneSameInstant(zone); - ZonedDateTime upper = tsTz.upper().withZoneSameInstant(zone); - assertEquals(restriction.getRangeZonedDateTime(), Range.closed(lower, upper)); - - lower = infinityTsTz.lower().withZoneSameInstant(zone); - assertEquals(restriction.getRangeZonedDateTimeInfinity(), Range.closedInfinite(lower)); - }); - } - - @Test - public void testNullRange() { - Restriction _restriction = doInJPA(entityManager -> { - Restriction restriction = new Restriction(); - entityManager.persist(restriction); - - return restriction; - }); - - doInJPA(entityManager -> { - Restriction restriction = entityManager.find(Restriction.class, _restriction.getId()); - - assertNull(restriction.getRangeInt()); - assertNull(restriction.getRangeIntEmpty()); - assertNull(restriction.getRangeIntInfinity()); - assertNull(restriction.getRangeLong()); - assertNull(restriction.getRangeBigDecimal()); - assertNull(restriction.getLocalDateTimeRange()); - assertNull(restriction.getRangeLocalDate()); - assertNull(restriction.getRangeZonedDateTime()); - assertNull(restriction.getRangeZonedDateTimeInfinity()); - assertNull(restriction.getRangeZonedDateTimeEmpty()); - }); - } - - @Entity(name = "AgeRestriction") - @Table(name = "age_restriction") - @TypeDef(name = "range", typeClass = PostgreSQLRangeType.class, defaultForType = Range.class) - public static class Restriction { - - @Id - @GeneratedValue - private Long id; - - @Column(name = "r_int", columnDefinition = "int4Range") - private Range rangeInt; - - @Column(name = "r_int_empty", columnDefinition = "int4Range") - private Range rangeIntEmpty; - - @Column(name = "r_int_infinity", columnDefinition = "int4Range") - private Range rangeIntInfinity; - - @Column(name = "r_long", columnDefinition = "int8range") - private Range rangeLong; - - @Column(name = "r_numeric", columnDefinition = "numrange") - private Range rangeBigDecimal; - - @Column(name = "r_ts", columnDefinition = "tsrange") - private Range rangeLocalDateTime; - - @Column(name = "r_ts_tz", columnDefinition = "tstzrange") - private Range rangeZonedDateTime; - - @Column(name = "r_ts_tz_infinity", columnDefinition = "tstzrange") - private Range rangeZonedDateTimeInfinity; - - @Column(name = "r_ts_tz_empty", columnDefinition = "tstzrange") - private Range rangeZonedDateTimeEmpty; - - @Column(name = "r_date", columnDefinition = "daterange") - private Range rangeLocalDate; - - public Long getId() { - return id; - } - - public Range getRangeInt() { - return rangeInt; - } - - public void setRangeInt(Range rangeInt) { - this.rangeInt = rangeInt; - } - - public Range getRangeIntEmpty() { - return rangeIntEmpty; - } - - public void setRangeIntEmpty(Range rangeIntEmpty) { - this.rangeIntEmpty = rangeIntEmpty; - } - - public Range getRangeIntInfinity() { - return rangeIntInfinity; - } - - public void setRangeIntInfinity(Range rangeIntInfinity) { - this.rangeIntInfinity = rangeIntInfinity; - } - - public Range getRangeLong() { - return rangeLong; - } - - public void setRangeLong(Range rangeLong) { - this.rangeLong = rangeLong; - } - - public Range getRangeBigDecimal() { - return rangeBigDecimal; - } - - public void setRangeBigDecimal(Range rangeBigDecimal) { - this.rangeBigDecimal = rangeBigDecimal; - } - - public Range getLocalDateTimeRange() { - return rangeLocalDateTime; - } - - public void setRangeLocalDateTime(Range rangeLocalDateTime) { - this.rangeLocalDateTime = rangeLocalDateTime; - } - - public Range getRangeZonedDateTime() { - return rangeZonedDateTime; - } - - public void setRangeZonedDateTime(Range rangeZonedDateTime) { - this.rangeZonedDateTime = rangeZonedDateTime; - } - - public Range getRangeZonedDateTimeInfinity() { - return rangeZonedDateTimeInfinity; - } - - public Range getRangeZonedDateTimeEmpty() { - return rangeZonedDateTimeEmpty; - } - - public void setRangeZonedDateTimeEmpty(Range rangeZonedDateTimeEmpty) { - this.rangeZonedDateTimeEmpty = rangeZonedDateTimeEmpty; - } - - public void setRangeZonedDateTimeInfinity(Range rangeZonedDateTimeInfinity) { - this.rangeZonedDateTimeInfinity = rangeZonedDateTimeInfinity; - } - - public Range getRangeLocalDate() { - return rangeLocalDate; - } - - public void setRangeLocalDate(Range rangeLocalDate) { - this.rangeLocalDate = rangeLocalDate; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/RangeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/RangeTest.java deleted file mode 100644 index d618da552..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/RangeTest.java +++ /dev/null @@ -1,156 +0,0 @@ -package io.hypersistence.utils.hibernate.type.range; - -import org.junit.Test; - -import static io.hypersistence.utils.hibernate.type.range.Range.integerRange; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.time.LocalDate; - -/** - * @author Edgar Asatryan - */ -public class RangeTest { - - @Test - public void ofStringTest() { - assertThat(integerRange("[1,3]").lower(), is(1)); - assertThat(integerRange("[1,3]").upper(), is(3)); - assertThat(integerRange("[1,3]").isUpperBoundClosed(), is(true)); - assertThat(integerRange("[1,3]").isLowerBoundClosed(), is(true)); - - assertThat(integerRange("[,3]").lower(), is(nullValue())); - assertThat(integerRange("[,3]").upper(), is(3)); - assertThat(integerRange("[,3]").hasLowerBound(), is(false)); - assertThat(integerRange("[,3]").hasUpperBound(), is(true)); - assertThat(integerRange("[,3]").isUpperBoundClosed(), is(true)); - assertThat(integerRange("[,3]").isLowerBoundClosed(), is(false)); - - assertThat(integerRange("[,]").lower(), is(nullValue())); - assertThat(integerRange("[,]").upper(), is(nullValue())); - assertThat(integerRange("[,]").hasLowerBound(), is(false)); - assertThat(integerRange("[,]").hasUpperBound(), is(false)); - assertThat(integerRange("[,]").isUpperBoundClosed(), is(false)); - assertThat(integerRange("[,]").isLowerBoundClosed(), is(false)); - - assertThat(integerRange("(-5,5]").isUpperBoundClosed(), is(true)); - assertThat(integerRange("(-5,5]").isLowerBoundClosed(), is(false)); - assertThat(integerRange("(,)").contains(integerRange("empty")), is(true)); - - assertThat(integerRange("empty").contains(integerRange("(,)")), is(false)); - } - - @Test - public void containsRange() { - assertThat(integerRange("[-5,5]").contains(integerRange("[-4,4]")), is(true)); - assertThat(integerRange("[-5,5]").contains(integerRange("[-5,5]")), is(true)); - assertThat(integerRange("(-5,5]").contains(integerRange("[-4,4]")), is(true)); - assertThat(integerRange("(-5,5]").contains(integerRange("(-4,4]")), is(true)); - - assertThat(integerRange("(,)").contains(integerRange("(,)")), is(true)); - assertThat(integerRange("(5,)").contains(integerRange("(6,)")), is(true)); - assertThat(integerRange("(,5)").contains(integerRange("(,4)")), is(true)); - assertThat(integerRange("(,)").contains(integerRange("(6,)")), is(true)); - assertThat(integerRange("(,)").contains(integerRange("(,6)")), is(true)); - } - - @Test - public void localDateTimeTest() { - assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.1,)")); - assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.12,)")); - assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.123,)")); - assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.1234,)")); - assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.12345,)")); - assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.123456,)")); - assertNotNull(Range.localDateTimeRange("[2019-03-27 16:33:10.123456,infinity)")); - } - - @Test - public void zonedDateTimeTest() { - assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10.1-06,)")); - assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10.12-06,)")); - assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10.123-06,)")); - assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10.1234-06,)")); - assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10.12345-06,)")); - assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10.123456-06,)")); - assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10.123456+05:30,)")); - assertNotNull(Range.zonedDateTimeRange("[2019-03-27 16:33:10.123456-06,infinity)")); - } - - - @Test - public void emptyInfinityEquality() { - assertEquals(integerRange("empty"), integerRange("empty")); - assertEquals(integerRange("(infinity,infinity)"), integerRange("(infinity,infinity)")); - assertEquals(integerRange("(,)"), integerRange("(infinity,infinity)")); - assertEquals(integerRange("(infinity,infinity)"), integerRange("(,)")); - - assertNotEquals(integerRange("empty"), integerRange("(infinity,infinity)")); - assertNotEquals(integerRange("empty"), integerRange("(,)")); - assertNotEquals(integerRange("empty"), integerRange("(5,5)")); - } - - @Test - public void emptyRangeWithEmptyKeyword() { - Range empty = Range.localDateRange("empty"); - - assertTrue(empty.isEmpty()); - - assertFalse(empty.contains(LocalDate.MIN)); - assertFalse(empty.contains((LocalDate) null)); - assertFalse(empty.contains(LocalDate.now())); - assertFalse(empty.contains(LocalDate.MAX)); - - assertNull(empty.upper()); - assertNull(empty.lower()); - } - - @Test - public void asStringWithEmptyKeyword() { - Range empty = Range.integerRange("empty"); - - assertEquals("empty", empty.asString()); - } - - @Test - public void asStringWithEmptyValue() { - Range empty = Range.integerRange("(5,5)"); - - assertEquals("(5,5)", empty.asString()); - } - - @Test - public void asStringWithInfinity() { - Range infinity = Range.integerRange("(,)"); - - assertEquals("(,)", infinity.asString()); - } - - @Test - public void emptyRangeWithValues() { - Range empty = Range.localDateRange("(2019-03-27,2019-03-27)"); - - assertTrue(empty.isEmpty()); - assertFalse(empty.contains(LocalDate.MIN)); - assertFalse(empty.contains(LocalDate.now())); - assertFalse(empty.contains(LocalDate.MAX)); - - assertTrue(integerRange("(5,5)").isEmpty()); - } - - @Test - public void notEmptyWithValues() { - assertFalse(integerRange("(5,)").isEmpty()); - assertFalse(integerRange("(5,5]").isEmpty()); - assertFalse(integerRange("(,5)").isEmpty()); - assertFalse(integerRange("(,)").isEmpty()); - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/ZonedDateTimeMilliSecondTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/ZonedDateTimeMilliSecondTest.java deleted file mode 100644 index 7c6f12fae..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/ZonedDateTimeMilliSecondTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package io.hypersistence.utils.hibernate.type.range; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; - -import static io.hypersistence.utils.hibernate.type.range.Range.zonedDateTimeRange; -import static org.junit.Assert.assertEquals; - -/** - * @author Arun Mohandas - */ -public class ZonedDateTimeMilliSecondTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Restriction.class - }; - } - - @Test - public void test() { - validateTest( - zonedDateTimeRange( - "[" + - "\"2018-05-03T10:15:30.127110+12:00\"," + - "\"2018-12-03T10:15:30.127111+12:00\"" + - "]" - ) - ); - - validateTest( - zonedDateTimeRange( - "[" + - "\"2018-05-03T10:15:30.127100+12:00\"," + - "\"2018-12-03T10:15:30.127111+12:00\"" + - "]" - ) - ); - - validateTest( - zonedDateTimeRange( - "[" + - "\"2018-05-03T10:15:30.127000+12:00\"," + - "\"2018-12-03T10:15:30.127111+12:00\"" + - "]" - ) - ); - } - - private void validateTest(Range tsTz) { - Restriction _restriction = doInJPA(entityManager -> { - Restriction restriction = new Restriction(); - restriction.setRangeZonedDateTime(tsTz); - entityManager.persist(restriction); - - return restriction; - }); - - doInJPA(entityManager -> { - Restriction restriction = entityManager.find(Restriction.class, _restriction.getId()); - - ZoneId zone = restriction.getRangeZonedDateTime().lower().getZone(); - - ZonedDateTime lower = tsTz.lower().withZoneSameInstant(zone); - - assertEquals(lower, restriction.getRangeZonedDateTime().lower()); - assertEquals(LocalDateTime.parse("2018-12-03T10:15:30").atZone(ZoneId.systemDefault()).getOffset(), - restriction.getRangeZonedDateTime().upper().getOffset()); - }); - } - - @Entity(name = "AgeRestriction") - @Table(name = "age_restriction") - @TypeDef(name = "range", typeClass = PostgreSQLRangeType.class, defaultForType = Range.class) - public static class Restriction { - - @Id - @GeneratedValue - private Long id; - - @Column(name = "r_tstzrange", columnDefinition = "tstzrange") - private Range rangeZonedDateTime; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Range getRangeZonedDateTime() { - return rangeZonedDateTime; - } - - public void setRangeZonedDateTime(Range rangeZonedDateTime) { - this.rangeZonedDateTime = rangeZonedDateTime; - } - } -} \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/guava/PostgreSQLGuavaRangeTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/guava/PostgreSQLGuavaRangeTypeTest.java deleted file mode 100644 index 341beba50..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/range/guava/PostgreSQLGuavaRangeTypeTest.java +++ /dev/null @@ -1,238 +0,0 @@ -package io.hypersistence.utils.hibernate.type.range.guava; - -import com.google.common.collect.Range; -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.*; -import java.math.BigDecimal; -import java.time.*; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -/** - * @author Edgar Asatryan - * @author Jan-Willem Gmelig Meyling - */ -public class PostgreSQLGuavaRangeTypeTest extends AbstractPostgreSQLIntegrationTest { - - private static final ZoneOffset DEFAULT_OFFSET = OffsetDateTime.now().getOffset(); - - private final Range numeric = Range.closedOpen(new BigDecimal("0.5"), new BigDecimal("0.89")); - - private final Range int8Range = Range.closedOpen(0L, 18L); - - private final Range int4Range = Range.closedOpen(0, 18); - - private final Range localDateTimeRange = Range.closed( - LocalDateTime.of(2014, Month.APRIL, 28, 16, 0, 49), - LocalDateTime.of(2015, Month.APRIL, 28, 16, 0, 49)); - - private final Range tsTz = Range.closed( - OffsetDateTime.of(LocalDateTime.of(2007, Month.DECEMBER, 3, 10, 15, 30), ZoneOffset.ofHours(1)).toZonedDateTime(), - OffsetDateTime.of(LocalDateTime.of(2008, Month.DECEMBER, 3, 10, 15, 30), ZoneOffset.ofHours(1)).toZonedDateTime()); - - private final Range tsTzO = Range.closed( - OffsetDateTime.of(LocalDateTime.of(2007, Month.MAY, 3, 10, 15, 30), DEFAULT_OFFSET), - OffsetDateTime.of(LocalDateTime.of(2008, Month.MAY, 3, 10, 15, 30), DEFAULT_OFFSET) - ); - - private final Range dateRange = Range.closedOpen(LocalDate.of(1992, Month.JANUARY, 13), LocalDate.of(1995, Month.JANUARY, 13)); - - @Override - protected Class[] entities() { - return new Class[]{ - Restriction.class - }; - } - - @Test - public void test() { - Restriction ageRestrictionInt = doInJPA(entityManager -> { - entityManager.persist(new Restriction()); - - Restriction restriction = new Restriction(); - restriction.setRangeInt(int4Range); - restriction.setRangeLong(int8Range); - restriction.setRangeBigDecimal(numeric); - restriction.setRangeLocalDateTime(localDateTimeRange); - restriction.setRangeZonedDateTime(tsTz); - restriction.setLocalDateRange(dateRange); - restriction.setOffsetZonedDateTime(tsTzO); - entityManager.persist(restriction); - - return restriction; - }); - - doInJPA(entityManager -> { - Restriction ar = entityManager.find(Restriction.class, ageRestrictionInt.getId()); - - assertEquals(int4Range, ar.getRangeInt()); - assertEquals(int8Range, ar.getRangeLong()); - assertEquals(numeric, ar.getRangeBigDecimal()); - assertEquals(localDateTimeRange, ar.getLocalDateTimeRange()); - //assertEquals(tsTzO, ar.getOffsetZonedDateTime()); - assertEquals(dateRange, ar.getLocalDateRange()); - - ZoneId zone = ar.getRangeZonedDateTime().lowerEndpoint().getZone(); - - ZonedDateTime lower = tsTz.lowerEndpoint().withZoneSameInstant(zone); - ZonedDateTime upper = tsTz.upperEndpoint().withZoneSameInstant(zone); - - assertEquals(ar.getRangeZonedDateTime(), Range.closed(lower, upper)); - }); - } - - @Test - public void testNullRange() { - Restriction ageRestrictionInt = doInJPA(entityManager -> { - Restriction restriction = new Restriction(); - entityManager.persist(restriction); - - return restriction; - }); - - doInJPA(entityManager -> { - Restriction ar = entityManager.find(Restriction.class, ageRestrictionInt.getId()); - - assertNull(ar.getRangeInt()); - assertNull(ar.getRangeLong()); - assertNull(ar.getRangeBigDecimal()); - assertNull(ar.getLocalDateTimeRange()); - assertNull(ar.getLocalDateRange()); - assertNull(ar.getRangeZonedDateTime()); - }); - } - - @Test - public void testUnboundedRangeIsRejected() { - Restriction ageRestrictionInt = doInJPA(entityManager -> { - Restriction restriction = new Restriction(); - restriction.setRangeInt(Range.all()); - entityManager.persist(restriction); - - return restriction; - }); - - - doInJPA(entityManager -> { - Restriction ar = entityManager.find(Restriction.class, ageRestrictionInt.getId()); - assertEquals(ar.getRangeInt(), Range.all()); - }); - } - - @Test - public void testUnboundedRangeStringIsRejected() { - PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; - assertEquals(Range.all(), instance.integerRange("(,)")); - } - - @Test - public void testSingleBoundedRanges() { - PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; - - assertEquals("(,)", instance.asString(Range.all())); - assertEquals("(1,)", instance.asString(Range.greaterThan(1))); - assertEquals("[2,)", instance.asString(Range.atLeast(2))); - assertEquals("(,3)", instance.asString(Range.lessThan(3))); - assertEquals("(,4]", instance.asString(Range.atMost(4))); - - assertEquals(Range.greaterThan(5), instance.integerRange("(5,)")); - assertEquals(Range.atLeast(6), instance.integerRange("[6,)")); - assertEquals(Range.lessThan(7), instance.integerRange("(,7)")); - assertEquals(Range.atMost(8), instance.integerRange("(,8]")); - } - - @Entity(name = "AgeRestriction") - @Table(name = "age_restriction") - @TypeDef(name = "range", typeClass = PostgreSQLGuavaRangeType.class, defaultForType = Range.class) - public static class Restriction { - - @Id - @GeneratedValue - private Long id; - - @Column(name = "r_int", columnDefinition = "int4Range") - private Range rangeInt; - - @Column(name = "r_long", columnDefinition = "int8range") - private Range rangeLong; - - @Column(name = "r_numeric", columnDefinition = "numrange") - private Range rangeBigDecimal; - - @Column(name = "r_tsrange", columnDefinition = "tsrange") - private Range rangeLocalDateTime; - - @Column(name = "r_tstzrange", columnDefinition = "tstzrange") - private Range rangeZonedDateTime; - - @Column(name = "r_otstzrange", columnDefinition = "tstzrange") - private Range offsetZonedDateTime; - - @Column(name = "r_daterange", columnDefinition = "daterange") - private Range localDateRange; - - public Long getId() { - return id; - } - - public Range getRangeLong() { - return rangeLong; - } - - public void setRangeLong(Range rangeLong) { - this.rangeLong = rangeLong; - } - - public Range getRangeInt() { - return rangeInt; - } - - public void setRangeInt(Range rangeInt) { - this.rangeInt = rangeInt; - } - - public Range getRangeBigDecimal() { - return rangeBigDecimal; - } - - public void setRangeBigDecimal(Range rangeBigDecimal) { - this.rangeBigDecimal = rangeBigDecimal; - } - - public Range getLocalDateTimeRange() { - return rangeLocalDateTime; - } - - public void setRangeLocalDateTime(Range rangeLocalDateTime) { - this.rangeLocalDateTime = rangeLocalDateTime; - } - - public Range getRangeZonedDateTime() { - return rangeZonedDateTime; - } - - public void setRangeZonedDateTime(Range rangeZonedDateTime) { - this.rangeZonedDateTime = rangeZonedDateTime; - } - - public Range getLocalDateRange() { - return localDateRange; - } - - public void setLocalDateRange(Range localDateRange) { - this.localDateRange = localDateRange; - } - - public Range getOffsetZonedDateTime() { - return offsetZonedDateTime; - } - - public void setOffsetZonedDateTime(Range offsetZonedDateTime) { - this.offsetZonedDateTime = offsetZonedDateTime; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/search/PostgreSQLTSVectorTypeTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/search/PostgreSQLTSVectorTypeTest.java deleted file mode 100644 index 094d67d5b..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/search/PostgreSQLTSVectorTypeTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package io.hypersistence.utils.hibernate.type.search; - -import io.hypersistence.utils.hibernate.util.AbstractPostgreSQLIntegrationTest; -import org.hibernate.annotations.NaturalId; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -import static org.junit.Assert.assertTrue; - -/** - * @author Vlad Mihalcea - * @author Philip Riecks - */ -public class PostgreSQLTSVectorTypeTest extends AbstractPostgreSQLIntegrationTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Book.class - }; - } - - @Test - public void test() { - doInJPA(entityManager -> { - Book book = new Book(); - book.setId(1L); - book.setIsbn("978-9730228236"); - book.setFts( - "This book is a journey into Java data access performance tuning. From connection management, to batch" + - " updates, fetch sizes and concurrency control mechanisms, it unravels the inner workings of" + - " the most common Java data access frameworks." - ); - - entityManager.persist(book); - }); - - doInJPA(entityManager -> { - Book book = entityManager.find(Book.class, 1L); - - assertTrue(book.getFts().contains("Java")); - assertTrue(book.getFts().contains("concurrency")); - assertTrue(book.getFts().contains("book")); - }); - } - - @Entity(name = "Book") - @Table(name = "book") - @TypeDef(name = "tsvector", typeClass = PostgreSQLTSVectorType.class) - public static class Book { - - @Id - private Long id; - - @NaturalId - private String isbn; - - @Type(type = "tsvector") - @Column(columnDefinition = "tsvector") - private String fts; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public String getFts() { - return fts; - } - - public void setFts(String fts) { - this.fts = fts; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/ConfigurationTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/ConfigurationTest.java deleted file mode 100644 index 37d9ee166..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/ConfigurationTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -public class ConfigurationTest { - - @Test - public void testHibernateProperties() { - assertNull(Configuration.INSTANCE.getProperties().getProperty("hibernate.types.nothing")); - assertEquals("def", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.abc")); - } - - @Test - public void testHibernateTypesOverrideProperties() { - assertEquals("ghi", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.def")); - } - - @Test - public void testApplicationProperties() { - assertNull(Configuration.INSTANCE.getProperties().getProperty("hibernate.types.app.props.no")); - assertEquals("true", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.app.props")); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperJsonSerializerTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperJsonSerializerTest.java deleted file mode 100644 index f7359e6d2..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/ObjectMapperJsonSerializerTest.java +++ /dev/null @@ -1,300 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.collect.Lists; -import org.hibernate.annotations.Type; -import org.junit.Test; - -import javax.persistence.Column; -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.*; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; - -public class ObjectMapperJsonSerializerTest { - - private ObjectMapperWrapper mapper = new ObjectMapperWrapper(); - - private ObjectMapperJsonSerializer serializer = new ObjectMapperJsonSerializer(mapper); - - @Test - public void should_clone_serializable_object() { - Object original = new SerializableObject("value"); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_non_serializable_object() { - Object original = new NonSerializableObject("value"); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_collection_of_serializable_object() { - List original = new ArrayList<>(); - original.add(new SerializableObject("value")); - List cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_collection_of_non_serializable_object() { - List original = new ArrayList<>(); - original.add(new NonSerializableObject("value")); - List cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_empty_collection() { - List original = new ArrayList<>(); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_map_of_non_serializable_key() { - Map original = new HashMap<>(); - original.put(new NonSerializableObject("key"), "value"); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_map_of_non_serializable_value() { - Map original = new HashMap<>(); - original.put("key", new NonSerializableObject("value")); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_map_of_serializable_key_and_value() { - Map original = new HashMap<>(); - original.put("key", new SerializableObject("value")); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_map_with_null_value() { - Map original = new HashMap<>(); - original.put("null", null); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_map_of_non_serializable_value_with_null_value() { - Map original = new LinkedHashMap<>(); - original.put("null", null); - original.put("key", new NonSerializableObject("value")); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_map_of_serializable_key_and_value_with_null() { - Map original = new LinkedHashMap<>(); - original.put("null", null); - original.put("key", new SerializableObject("value")); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_serializable_complex_object_with_serializable_nested_object() { - Map> map = new LinkedHashMap<>(); - map.put("key1", Lists.newArrayList(new SerializableObject("name1"))); - map.put("key2", Lists.newArrayList( - new SerializableObject("name2"), - new SerializableObject("name3") - )); - Object original = new SerializableComplexObject(map); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_serializable_complex_object_with_non_serializable_nested_object() { - Map> map = new LinkedHashMap<>(); - map.put("key1", Lists.newArrayList(new NonSerializableObject("name1"))); - map.put("key2", Lists.newArrayList( - new NonSerializableObject("name2"), - new NonSerializableObject("name3") - )); - Object original = new SerializableComplexObjectWithNonSerializableNestedObject(map); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - @Test - public void should_clone_jsonnode() { - Object original = mapper.getObjectMapper().createArrayNode() - .add(BigDecimal.ONE) - .add(1.0) - .add("string"); - Object cloned = serializer.clone(original); - assertEquals(original, cloned); - assertNotSame(original, cloned); - } - - private static class SerializableObject implements Serializable { - private final String value; - - private SerializableObject(@JsonProperty("value") String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - - SerializableObject that = (SerializableObject) o; - - return value.equals(that.value); - } - - @Override - public int hashCode() { - return value.hashCode(); - } - - @Override - public String toString() { - return value; - } - } - - private static class NonSerializableObject { - private final String value; - - private NonSerializableObject(@JsonProperty("value") String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - - NonSerializableObject that = (NonSerializableObject) o; - - return value.equals(that.value); - } - - @Override - public int hashCode() { - return value.hashCode(); - } - - @Override - public String toString() { - return value; - } - } - - private static class SerializableComplexObject implements Serializable { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private final Map> value; - - private SerializableComplexObject(@JsonProperty("value") Map> value) { - this.value = value; - } - - public Map> getValue() { - return value; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - - SerializableComplexObject that = (SerializableComplexObject) o; - - return value.equals(that.value); - } - - @Override - public int hashCode() { - return value.hashCode(); - } - - @Override - public String toString() { - return value.toString(); - } - } - - private static class SerializableComplexObjectWithNonSerializableNestedObject implements Serializable { - - @Type(type = "jsonb") - @Column(columnDefinition = "jsonb") - private final Map> value; - - private SerializableComplexObjectWithNonSerializableNestedObject(@JsonProperty("value") Map> value) { - this.value = value; - } - - public Map> getValue() { - return value; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - - SerializableComplexObjectWithNonSerializableNestedObject that = (SerializableComplexObjectWithNonSerializableNestedObject) o; - - return value.equals(that.value); - } - - @Override - public int hashCode() { - return value.hashCode(); - } - - @Override - public String toString() { - return value.toString(); - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/DTOProjectionImportRelativePathTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/DTOProjectionImportRelativePathTest.java deleted file mode 100644 index 0889b5bd5..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/DTOProjectionImportRelativePathTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util.dto; - -import io.hypersistence.utils.hibernate.util.AbstractTest; -import io.hypersistence.utils.hibernate.type.util.ClassImportIntegrator; -import org.hibernate.integrator.spi.Integrator; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import java.sql.Timestamp; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneOffset; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class DTOProjectionImportRelativePathTest extends AbstractTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Post.class, - }; - } - - @Override - protected Integrator integrator() { - return new ClassImportIntegrator(Arrays.asList(PostDTO.class)) - .excludePath("io.hypersistence.utils.hibernate.type"); - } - - @Override - public void afterInit() { - doInJPA(entityManager -> { - Post post = new Post(); - post.setId(1L); - post.setTitle("High-Performance Java Persistence"); - post.setCreatedBy("Vlad Mihalcea"); - post.setCreatedOn(Timestamp.from( - LocalDateTime.of(2020, 11, 2, 12, 0, 0).toInstant(ZoneOffset.UTC) - )); - post.setUpdatedBy("Vlad Mihalcea"); - post.setUpdatedOn(Timestamp.from( - LocalDateTime.now().toInstant(ZoneOffset.UTC) - )); - - entityManager.persist(post); - }); - } - - @Test - public void testConstructorExpression() { - doInJPA(entityManager -> { - List postDTOs = entityManager.createQuery( - "select new util.dto.PostDTO(" + - " p.id, " + - " p.title " + - ") " + - "from Post p " + - "where p.createdOn > :fromTimestamp", PostDTO.class) - .setParameter( - "fromTimestamp", - Timestamp.from( - LocalDate.of(2020, 1, 1) - .atStartOfDay() - .toInstant(ZoneOffset.UTC) - ) - ) - .getResultList(); - - assertEquals(1, postDTOs.size()); - }); - } - - @Entity(name = "Post") - public static class Post { - - @Id - private Long id; - - private String title; - - @Column(name = "created_on") - private Timestamp createdOn; - - @Column(name = "created_by") - private String createdBy; - - @Column(name = "updated_on") - private Timestamp updatedOn; - - @Column(name = "updated_by") - private String updatedBy; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public Timestamp getCreatedOn() { - return createdOn; - } - - public void setCreatedOn(Timestamp createdOn) { - this.createdOn = createdOn; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public Timestamp getUpdatedOn() { - return updatedOn; - } - - public void setUpdatedOn(Timestamp updatedOn) { - this.updatedOn = updatedOn; - } - - public String getUpdatedBy() { - return updatedBy; - } - - public void setUpdatedBy(String updatedBy) { - this.updatedBy = updatedBy; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/DTOProjectionImportTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/DTOProjectionImportTest.java deleted file mode 100644 index cae0da857..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/DTOProjectionImportTest.java +++ /dev/null @@ -1,148 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util.dto; - -import io.hypersistence.utils.hibernate.util.AbstractTest; -import io.hypersistence.utils.hibernate.type.util.ClassImportIntegrator; -import org.hibernate.integrator.spi.Integrator; -import org.junit.Test; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import java.sql.Timestamp; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneOffset; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class DTOProjectionImportTest extends AbstractTest { - - @Override - protected Class[] entities() { - return new Class[]{ - Post.class, - }; - } - - @Override - protected Integrator integrator() { - return new ClassImportIntegrator(Arrays.asList(PostDTO.class)); - } - - @Override - public void afterInit() { - doInJPA(entityManager -> { - Post post = new Post(); - post.setId(1L); - post.setTitle("High-Performance Java Persistence"); - post.setCreatedBy("Vlad Mihalcea"); - post.setCreatedOn(Timestamp.from( - LocalDateTime.of(2020, 11, 2, 12, 0, 0).toInstant(ZoneOffset.UTC) - )); - post.setUpdatedBy("Vlad Mihalcea"); - post.setUpdatedOn(Timestamp.from( - LocalDateTime.now().toInstant(ZoneOffset.UTC) - )); - - entityManager.persist(post); - }); - } - - @Test - public void testConstructorExpression() { - doInJPA(entityManager -> { - List postDTOs = entityManager.createQuery( - "select new PostDTO(" + - " p.id, " + - " p.title " + - ") " + - "from Post p " + - "where p.createdOn > :fromTimestamp", PostDTO.class) - .setParameter( - "fromTimestamp", - Timestamp.from( - LocalDate.of(2020, 1, 1) - .atStartOfDay() - .toInstant(ZoneOffset.UTC) - ) - ) - .getResultList(); - - assertEquals(1, postDTOs.size()); - }); - } - - @Entity(name = "Post") - public static class Post { - - @Id - private Long id; - - private String title; - - @Column(name = "created_on") - private Timestamp createdOn; - - @Column(name = "created_by") - private String createdBy; - - @Column(name = "updated_on") - private Timestamp updatedOn; - - @Column(name = "updated_by") - private String updatedBy; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public Timestamp getCreatedOn() { - return createdOn; - } - - public void setCreatedOn(Timestamp createdOn) { - this.createdOn = createdOn; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public Timestamp getUpdatedOn() { - return updatedOn; - } - - public void setUpdatedOn(Timestamp updatedOn) { - this.updatedOn = updatedOn; - } - - public String getUpdatedBy() { - return updatedBy; - } - - public void setUpdatedBy(String updatedBy) { - this.updatedBy = updatedBy; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/PostDTO.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/PostDTO.java deleted file mode 100644 index 2198f4ccb..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/type/util/dto/PostDTO.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.hypersistence.utils.hibernate.type.util.dto; - -/** - * @author Vlad Mihalcea - */ -public class PostDTO { - - private Long id; - - private String title; - - public PostDTO(Number id, String title) { - this.id = id.longValue(); - this.title = title; - } - - public Long getId() { - return id; - } - - public String getTitle() { - return title; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractMySQLIntegrationTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractMySQLIntegrationTest.java deleted file mode 100644 index 157596bee..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractMySQLIntegrationTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.MySQLDataSourceProvider; - -/** - * AbstractMySQLIntegrationTest - Abstract MySQL IntegrationTest - * - * @author Vlad Mihalcea - */ -public abstract class AbstractMySQLIntegrationTest extends AbstractTest { - - @Override - protected DataSourceProvider dataSourceProvider() { - return new MySQLDataSourceProvider(); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractOracleIntegrationTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractOracleIntegrationTest.java deleted file mode 100644 index 97d39917f..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractOracleIntegrationTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.OracleDataSourceProvider; - -/** - * AbstractOracleIntegrationTest - Abstract Oracle IntegrationTest - * - * @author Vlad Mihalcea - */ -public abstract class AbstractOracleIntegrationTest extends AbstractTest { - - @Override - protected DataSourceProvider dataSourceProvider() { - return new OracleDataSourceProvider(); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractPostgreSQLIntegrationTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractPostgreSQLIntegrationTest.java deleted file mode 100644 index 7ff27a9a2..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractPostgreSQLIntegrationTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; - -/** - * AbstractPostgreSQLIntegrationTest - Abstract PostgreSQL IntegrationTest - * - * @author Vlad Mihalcea - */ -public abstract class AbstractPostgreSQLIntegrationTest extends AbstractTest { - - @Override - protected DataSourceProvider dataSourceProvider() { - return new PostgreSQLDataSourceProvider(); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractSQLServerIntegrationTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractSQLServerIntegrationTest.java deleted file mode 100644 index a51ff372a..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractSQLServerIntegrationTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.SQLServerDataSourceProvider; - -/** - * AbstractSQLServerIntegrationTest - Abstract SQL Server IntegrationTest - * - * @author Vlad Mihalcea - */ -public abstract class AbstractSQLServerIntegrationTest extends AbstractTest { - - @Override - protected DataSourceProvider dataSourceProvider() { - return new SQLServerDataSourceProvider(); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractTest.java deleted file mode 100644 index f86e70484..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/AbstractTest.java +++ /dev/null @@ -1,533 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.HSQLDBDataSourceProvider; -import io.hypersistence.utils.hibernate.util.transaction.*; -import org.hibernate.Interceptor; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.hibernate.boot.MetadataBuilder; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.SessionFactoryBuilder; -import org.hibernate.boot.model.TypeContributor; -import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; -import org.hibernate.boot.registry.BootstrapServiceRegistry; -import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.spi.MetadataImplementor; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.integrator.spi.Integrator; -import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; -import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; -import org.hibernate.jpa.boot.spi.IntegratorProvider; -import org.hibernate.jpa.boot.spi.TypeContributorList; -import org.hibernate.type.BasicType; -import org.hibernate.type.Type; -import org.hibernate.usertype.CompositeUserType; -import org.hibernate.usertype.UserType; -import org.junit.After; -import org.junit.Before; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.spi.PersistenceUnitInfo; -import javax.sql.DataSource; -import java.io.Closeable; -import java.io.IOException; -import java.util.*; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicReference; -import java.util.stream.Collectors; - -public abstract class AbstractTest { - - protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); - - private EntityManagerFactory emf; - - private SessionFactory sf; - - private List closeables = new ArrayList<>(); - - @Before - public void init() { - if(nativeHibernateSessionFactoryBootstrap()) { - sf = newSessionFactory(); - } else { - emf = newEntityManagerFactory(); - } - afterInit(); - } - - protected void afterInit() { - - } - - @After - public void destroy() { - if (nativeHibernateSessionFactoryBootstrap()) { - sf.close(); - } else { - emf.close(); - } - for (Closeable closeable : closeables) { - try { - closeable.close(); - } catch (IOException e) { - LOGGER.error("Failure", e); - } - } - closeables.clear(); - } - - public EntityManagerFactory entityManagerFactory() { - return nativeHibernateSessionFactoryBootstrap() ? sf : emf; - } - - public SessionFactory sessionFactory() { - return nativeHibernateSessionFactoryBootstrap() ? sf : entityManagerFactory().unwrap(SessionFactory.class); - } - - protected boolean nativeHibernateSessionFactoryBootstrap() { - return false; - } - - protected abstract Class[] entities(); - - protected List entityClassNames() { - return Arrays.asList(entities()).stream().map(Class::getName).collect(Collectors.toList()); - } - - protected String[] packages() { - return null; - } - - protected String[] resources() { - return null; - } - - protected Interceptor interceptor() { - return null; - } - - private SessionFactory newSessionFactory() { - final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder() - .enableAutoClose(); - - Integrator integrator = integrator(); - if (integrator != null) { - bsrb.applyIntegrator(integrator); - } - - final BootstrapServiceRegistry bsr = bsrb.build(); - - final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bsr) - .applySettings(properties()) - .build(); - - final MetadataSources metadataSources = new MetadataSources(serviceRegistry); - - for (Class annotatedClass : entities()) { - metadataSources.addAnnotatedClass(annotatedClass); - } - - String[] packages = packages(); - if (packages != null) { - for (String annotatedPackage : packages) { - metadataSources.addPackage(annotatedPackage); - } - } - - String[] resources = resources(); - if (resources != null) { - for (String resource : resources) { - metadataSources.addResource(resource); - } - } - - final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(); - metadataBuilder.enableNewIdentifierGeneratorSupport(true); - metadataBuilder.applyImplicitNamingStrategy(ImplicitNamingStrategyLegacyJpaImpl.INSTANCE); - - final List additionalTypes = additionalTypes(); - if (additionalTypes != null) { - additionalTypes.stream().forEach(type -> { - metadataBuilder.applyTypes((typeContributions, serviceRegistry1) -> { - if(type instanceof BasicType) { - typeContributions.contributeType((BasicType) type); - } else if (type instanceof UserType ){ - typeContributions.contributeType((UserType) type); - } else if (type instanceof CompositeUserType) { - typeContributions.contributeType((CompositeUserType) type); - } - }); - }); - } - - MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build(); - - final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder(); - Interceptor interceptor = interceptor(); - if (interceptor != null) { - sfb.applyInterceptor(interceptor); - } - - return sfb.build(); - } - - private SessionFactory newLegacySessionFactory() { - Properties properties = properties(); - Configuration configuration = new Configuration().addProperties(properties); - for (Class entityClass : entities()) { - configuration.addAnnotatedClass(entityClass); - } - String[] packages = packages(); - if (packages != null) { - for (String scannedPackage : packages) { - configuration.addPackage(scannedPackage); - } - } - String[] resources = resources(); - if (resources != null) { - for (String resource : resources) { - configuration.addResource(resource); - } - } - Interceptor interceptor = interceptor(); - if (interceptor != null) { - configuration.setInterceptor(interceptor); - } - - final List additionalTypes = additionalTypes(); - if (additionalTypes != null) { - configuration.registerTypeContributor((typeContributions, serviceRegistry) -> { - additionalTypes.stream().forEach(type -> { - if (type instanceof BasicType) { - typeContributions.contributeType((BasicType) type); - } else if (type instanceof UserType) { - typeContributions.contributeType((UserType) type); - } else if (type instanceof CompositeUserType) { - typeContributions.contributeType((CompositeUserType) type); - } - }); - }); - } - return configuration.buildSessionFactory( - new StandardServiceRegistryBuilder() - .applySettings(properties) - .build() - ); - } - - protected EntityManagerFactory newEntityManagerFactory() { - PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName()); - Map configuration = new HashMap<>(); - configuration.put(AvailableSettings.INTERCEPTOR, interceptor()); - Integrator integrator = integrator(); - if (integrator != null) { - configuration.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(integrator)); - } - - final List additionalTypes = additionalTypes(); - if (additionalTypes != null) { - configuration.put("hibernate.type_contributors", (TypeContributorList) () -> { - List typeContributors = new ArrayList<>(); - - for (Type additionalType : additionalTypes) { - if (additionalType instanceof BasicType) { - typeContributors.add((typeContributions, serviceRegistry) -> typeContributions.contributeType((BasicType) additionalType)); - - - } else if (additionalType instanceof UserType) { - typeContributors.add((typeContributions, serviceRegistry) -> typeContributions.contributeType((UserType) additionalType)); - } else if (additionalType instanceof CompositeUserType) { - typeContributors.add((typeContributions, serviceRegistry) -> typeContributions.contributeType((CompositeUserType) additionalType)); - } - } - return typeContributors; - }); - } - - EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl( - new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration - ); - return entityManagerFactoryBuilder.build(); - } - - protected Integrator integrator() { - return null; - } - - protected PersistenceUnitInfoImpl persistenceUnitInfo(String name) { - PersistenceUnitInfoImpl persistenceUnitInfo = new PersistenceUnitInfoImpl( - name, entityClassNames(), properties() - ); - String[] resources = resources(); - if (resources != null) { - persistenceUnitInfo.getMappingFileNames().addAll(Arrays.asList(resources)); - } - return persistenceUnitInfo; - } - - protected Properties properties() { - Properties properties = new Properties(); - properties.put("hibernate.dialect", dataSourceProvider().hibernateDialect()); - //log settings - properties.put("hibernate.hbm2ddl.auto", "create-drop"); - //data source settings - DataSource dataSource = newDataSource(); - if (dataSource != null) { - properties.put("hibernate.connection.datasource", dataSource); - } - properties.put("hibernate.cache.ehcache.missing_cache_strategy", "create"); - additionalProperties(properties); - return properties; - } - - protected void additionalProperties(Properties properties) { - - } - - protected DataSourceProxyType dataSourceProxyType() { - return DataSourceProxyType.DATA_SOURCE_PROXY; - } - - protected DataSource newDataSource() { - DataSource dataSource = - proxyDataSource() - ? dataSourceProxyType().dataSource(dataSourceProvider().dataSource()) - : dataSourceProvider().dataSource(); - return dataSource; - } - - protected boolean proxyDataSource() { - return true; - } - - protected DataSourceProvider dataSourceProvider() { - return new HSQLDBDataSourceProvider(); - } - - protected List additionalTypes() { - return null; - } - - protected T doInHibernate(HibernateTransactionFunction callable) { - T result = null; - Session session = null; - Transaction txn = null; - try { - session = sessionFactory().openSession(); - callable.beforeTransactionCompletion(); - txn = session.beginTransaction(); - - result = callable.apply(session); - if (!txn.getRollbackOnly()) { - txn.commit(); - } else { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - } catch (Throwable t) { - if (txn != null && txn.isActive()) { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - throw t; - } finally { - callable.afterTransactionCompletion(); - if (session != null) { - session.close(); - } - } - return result; - } - - protected void doInHibernate(HibernateTransactionConsumer callable) { - Session session = null; - Transaction txn = null; - try { - session = sessionFactory().openSession(); - callable.beforeTransactionCompletion(); - txn = session.beginTransaction(); - - callable.accept(session); - if (!txn.getRollbackOnly()) { - txn.commit(); - } else { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - } catch (Throwable t) { - if (txn != null && txn.isActive()) { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - throw t; - } finally { - callable.afterTransactionCompletion(); - if (session != null) { - session.close(); - } - } - } - - protected T doInJPA(JPATransactionFunction function) { - T result = null; - EntityManager entityManager = null; - EntityTransaction txn = null; - try { - entityManager = entityManagerFactory().createEntityManager(); - function.beforeTransactionCompletion(); - txn = entityManager.getTransaction(); - txn.begin(); - result = function.apply(entityManager); - if (!txn.getRollbackOnly()) { - txn.commit(); - } else { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - } catch (Throwable t) { - if (txn != null && txn.isActive()) { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - throw t; - } finally { - function.afterTransactionCompletion(); - if (entityManager != null) { - entityManager.close(); - } - } - return result; - } - - protected void doInJPA(JPATransactionVoidFunction function) { - EntityManager entityManager = null; - EntityTransaction txn = null; - try { - entityManager = entityManagerFactory().createEntityManager(); - function.beforeTransactionCompletion(); - txn = entityManager.getTransaction(); - txn.begin(); - function.accept(entityManager); - if (!txn.getRollbackOnly()) { - txn.commit(); - } else { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - } catch (Throwable t) { - if (txn != null && txn.isActive()) { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - throw t; - } finally { - function.afterTransactionCompletion(); - if (entityManager != null) { - entityManager.close(); - } - } - } - - protected T doInJDBC(ConnectionCallable callable) { - AtomicReference result = new AtomicReference<>(); - Session session = null; - Transaction txn = null; - try { - session = sessionFactory().openSession(); - txn = session.beginTransaction(); - session.doWork(connection -> { - result.set(callable.execute(connection)); - }); - if (!txn.getRollbackOnly()) { - txn.commit(); - } else { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - } catch (Throwable t) { - if (txn != null && txn.isActive()) { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - throw t; - } finally { - if (session != null) { - session.close(); - } - } - return result.get(); - } - - protected void doInJDBC(ConnectionVoidCallable callable) { - Session session = null; - Transaction txn = null; - try { - session = sessionFactory().openSession(); - txn = session.beginTransaction(); - session.doWork(callable::execute); - if (!txn.getRollbackOnly()) { - txn.commit(); - } else { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - } catch (Throwable t) { - if (txn != null && txn.isActive()) { - try { - txn.rollback(); - } catch (Exception e) { - LOGGER.error("Rollback failure", e); - } - } - throw t; - } finally { - if (session != null) { - session.close(); - } - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/DataSourceProxyType.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/DataSourceProxyType.java deleted file mode 100644 index 434ddafad..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/DataSourceProxyType.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import io.hypersistence.utils.logging.InlineQueryLogEntryCreator; -import net.ttddyy.dsproxy.listener.ChainListener; -import net.ttddyy.dsproxy.listener.DataSourceQueryCountListener; -import net.ttddyy.dsproxy.listener.logging.SLF4JQueryLoggingListener; -import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; - -import javax.sql.DataSource; - -/** - * @author Vlad Mihalcea - */ -public enum DataSourceProxyType { - DATA_SOURCE_PROXY { - @Override - DataSource dataSource(DataSource dataSource) { - ChainListener listener = new ChainListener(); - SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener(); - loggingListener.setQueryLogEntryCreator(new InlineQueryLogEntryCreator()); - listener.addListener(loggingListener); - listener.addListener(new DataSourceQueryCountListener()); - return ProxyDataSourceBuilder - .create(dataSource) - .name(name()) - .listener(listener) - .build(); - } - }; - - abstract DataSource dataSource(DataSource dataSource); -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/EntityProvider.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/EntityProvider.java deleted file mode 100644 index b6776aea9..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/EntityProvider.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -/** - * @author Vlad Mihalcea - */ -public interface EntityProvider { - - /** - * Entity types shared among multiple test configurations - * - * @return entity types - */ - Class[] entities(); -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/ExceptionUtil.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/ExceptionUtil.java deleted file mode 100644 index 78f434db8..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/ExceptionUtil.java +++ /dev/null @@ -1,129 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import org.hibernate.PessimisticLockException; -import org.hibernate.exception.LockAcquisitionException; - -import javax.persistence.LockTimeoutException; -import java.sql.SQLTimeoutException; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - -/** - * @author Vlad Mihalcea - */ -public interface ExceptionUtil { - - List> LOCK_TIMEOUT_EXCEPTIONS = Arrays.asList( - LockAcquisitionException.class, - LockTimeoutException.class, - PessimisticLockException.class, - javax.persistence.PessimisticLockException.class, - SQLTimeoutException.class - ); - - /** - * Get the root cause of a particular {@code Throwable} - * - * @param t exception - * - * @return exception root cause - */ - static T rootCause(Throwable t) { - Throwable cause = t.getCause(); - if (cause != null && cause != t) { - return rootCause(cause); - } - return (T) t; - } - - /** - * Is the given throwable caused by a database lock timeout? - * - * @param e exception - * - * @return is caused by a database lock timeout - */ - static boolean isLockTimeout(Throwable e) { - AtomicReference causeHolder = new AtomicReference<>(e); - do { - final Throwable cause = causeHolder.get(); - final String failureMessage = cause.getMessage().toLowerCase(); - if (LOCK_TIMEOUT_EXCEPTIONS.stream().anyMatch(c -> c.isInstance(cause)) || - failureMessage.contains("timeout") || - failureMessage.contains("timed out") || - failureMessage.contains("time out") || - failureMessage.contains("closed connection") || - failureMessage.contains("link failure") - ) { - return true; - } else { - if (cause.getCause() == null || cause.getCause() == cause) { - break; - } else { - causeHolder.set(cause.getCause()); - } - } - } - while (true); - return false; - } - - /** - * Is the given throwable caused by a database MVCC anomaly detection? - * - * @param e exception - * - * @return is caused by a database lock MVCC anomaly detection - */ - static boolean isMVCCAnomalyDetection(Throwable e) { - AtomicReference causeHolder = new AtomicReference<>(e); - do { - final Throwable cause = causeHolder.get(); - if ( - cause.getMessage().contains("ORA-08177: can't serialize access for this transaction") //Oracle - || cause.getMessage().toLowerCase().contains("could not serialize access due to concurrent update") //PSQLException - || cause.getMessage().toLowerCase().contains("ould not serialize access due to read/write dependencies among transactions") //PSQLException - || cause.getMessage().toLowerCase().contains("snapshot isolation transaction aborted due to update conflict") //SQLServerException - ) { - return true; - } else { - if (cause.getCause() == null || cause.getCause() == cause) { - break; - } else { - causeHolder.set(cause.getCause()); - } - } - } - while (true); - return false; - } - - /** - * Was the given exception caused by a SQL connection close - * - * @param e exception - * - * @return is caused by a SQL connection close - */ - static boolean isConnectionClose(Exception e) { - Throwable cause = e; - do { - if (cause.getMessage().toLowerCase().contains("connection is close") - || cause.getMessage().toLowerCase().contains("closed connection") - || cause.getMessage().toLowerCase().contains("link failure") - || cause.getMessage().toLowerCase().contains("closed") - ) { - return true; - } else { - if (cause.getCause() == null || cause.getCause() == cause) { - break; - } else { - cause = cause.getCause(); - } - } - } - while (true); - return false; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/PersistenceUnitInfoImpl.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/PersistenceUnitInfoImpl.java deleted file mode 100644 index a93616e5f..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/PersistenceUnitInfoImpl.java +++ /dev/null @@ -1,134 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import org.hibernate.jpa.HibernatePersistenceProvider; - -import javax.persistence.SharedCacheMode; -import javax.persistence.ValidationMode; -import javax.persistence.spi.ClassTransformer; -import javax.persistence.spi.PersistenceUnitInfo; -import javax.persistence.spi.PersistenceUnitTransactionType; -import javax.sql.DataSource; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; - -/** - * @author Vlad Mihalcea - */ -public class PersistenceUnitInfoImpl implements PersistenceUnitInfo { - - private final String persistenceUnitName; - private final List managedClassNames; - private final List mappingFileNames = new ArrayList<>(); - private final Properties properties; - private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; - private DataSource jtaDataSource; - - private DataSource nonJtaDataSource; - - public PersistenceUnitInfoImpl(String persistenceUnitName, List managedClassNames, Properties properties) { - this.persistenceUnitName = persistenceUnitName; - this.managedClassNames = managedClassNames; - this.properties = properties; - } - - @Override - public String getPersistenceUnitName() { - return persistenceUnitName; - } - - @Override - public String getPersistenceProviderClassName() { - return HibernatePersistenceProvider.class.getName(); - } - - @Override - public PersistenceUnitTransactionType getTransactionType() { - return transactionType; - } - - @Override - public DataSource getJtaDataSource() { - return jtaDataSource; - } - - public PersistenceUnitInfoImpl setJtaDataSource(DataSource jtaDataSource) { - this.jtaDataSource = jtaDataSource; - this.nonJtaDataSource = null; - transactionType = PersistenceUnitTransactionType.JTA; - return this; - } - - @Override - public DataSource getNonJtaDataSource() { - return nonJtaDataSource; - } - - public PersistenceUnitInfoImpl setNonJtaDataSource(DataSource nonJtaDataSource) { - this.nonJtaDataSource = nonJtaDataSource; - this.jtaDataSource = null; - transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; - return this; - } - - @Override - public List getMappingFileNames() { - return mappingFileNames; - } - - @Override - public List getJarFileUrls() { - return Collections.emptyList(); - } - - @Override - public URL getPersistenceUnitRootUrl() { - return null; - } - - @Override - public List getManagedClassNames() { - return managedClassNames; - } - - @Override - public boolean excludeUnlistedClasses() { - return false; - } - - @Override - public SharedCacheMode getSharedCacheMode() { - return SharedCacheMode.UNSPECIFIED; - } - - @Override - public ValidationMode getValidationMode() { - return ValidationMode.AUTO; - } - - public Properties getProperties() { - return properties; - } - - @Override - public String getPersistenceXMLSchemaVersion() { - return "2.1"; - } - - @Override - public ClassLoader getClassLoader() { - return Thread.currentThread().getContextClassLoader(); - } - - @Override - public void addTransformer(ClassTransformer transformer) { - - } - - @Override - public ClassLoader getNewTempClassLoader() { - return null; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/StringUtilsTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/StringUtilsTest.java deleted file mode 100644 index 823e66bf3..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/StringUtilsTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.hypersistence.utils.hibernate.util; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -public class StringUtilsTest { - - @Test - public void testJoin(){ - assertEquals( - "Oracle,PostgreSQL,MySQL,SQL Server", - StringUtils.join(",", "Oracle", "PostgreSQL", "MySQL", "SQL Server") - ); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/AbstractContainerDataSourceProvider.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/AbstractContainerDataSourceProvider.java deleted file mode 100644 index 1b387f1cc..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/AbstractContainerDataSourceProvider.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.hypersistence.utils.hibernate.util.providers; - -import org.testcontainers.containers.JdbcDatabaseContainer; - -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * @author Vlad Mihalcea - */ -public abstract class AbstractContainerDataSourceProvider implements DataSourceProvider { - - @Override - public DataSource dataSource() { - DataSource dataSource = newDataSource(); - Connection connection = null; - try { - connection = dataSource.getConnection(); - return dataSource; - } catch (SQLException e) { - Database database = database(); - if(database.getContainer() == null) { - database.initContainer(username(), password()); - } - return newDataSource(); - } finally { - if (connection != null) { - try { - connection.close(); - } catch (SQLException ignore) { - } - } - } - } - - @Override - public String url() { - JdbcDatabaseContainer container = database().getContainer(); - return container != null ? - container.getJdbcUrl() : - defaultJdbcUrl(); - } - - protected abstract String defaultJdbcUrl(); - - protected abstract DataSource newDataSource(); -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/DataSourceProvider.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/DataSourceProvider.java deleted file mode 100644 index 3b34eed8e..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/DataSourceProvider.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.hypersistence.utils.hibernate.util.providers; - -import javax.sql.DataSource; - -/** - * @author Vlad Mihalcea - */ -public interface DataSourceProvider { - - Database database(); - - String hibernateDialect(); - - DataSource dataSource(); - - String url(); - - String username(); - - String password(); -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/Database.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/Database.java deleted file mode 100644 index 718eec574..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/Database.java +++ /dev/null @@ -1,90 +0,0 @@ -package io.hypersistence.utils.hibernate.util.providers; - -import org.testcontainers.containers.*; - -import java.util.Collections; - -/** - * @author Vlad Mihalcea - */ -public enum Database { - POSTGRESQL { - @Override - protected JdbcDatabaseContainer newJdbcDatabaseContainer() { - return new PostgreSQLContainer("postgres:15.3"); - } - }, - ORACLE { - @Override - protected JdbcDatabaseContainer newJdbcDatabaseContainer() { - return new OracleContainer("gvenzl/oracle-xe:21.3.0-slim"); - } - - @Override - protected boolean supportsDatabaseName() { - return false; - } - }, - MYSQL { - @Override - protected JdbcDatabaseContainer newJdbcDatabaseContainer() { - return new MySQLContainer("mysql:8.0"); - } - }, - SQLSERVER { - @Override - protected JdbcDatabaseContainer newJdbcDatabaseContainer() { - return new MSSQLServerContainer("mcr.microsoft.com/mssql/server:2019-latest"); - } - - @Override - protected boolean supportsDatabaseName() { - return false; - } - - @Override - protected boolean supportsCredentials() { - return false; - } - }, - HSQLDB, - H2 - ; - - private JdbcDatabaseContainer container; - - public JdbcDatabaseContainer getContainer() { - return container; - } - - public void initContainer(String username, String password) { - container = (JdbcDatabaseContainer) newJdbcDatabaseContainer() - .withReuse(true) - .withEnv(Collections.singletonMap("ACCEPT_EULA", "Y")) - .withTmpFs(Collections.singletonMap("/testtmpfs", "rw")); - if(supportsDatabaseName()) { - container.withDatabaseName("high-performance-java-persistence"); - } - if(supportsCredentials()) { - container.withUsername(username).withPassword(password); - } - container.start(); - } - - protected JdbcDatabaseContainer newJdbcDatabaseContainer() { - throw new UnsupportedOperationException( - String.format( - "The [%s] database was not configured to use Testcontainers!", - name() - ) - ); - } - - protected boolean supportsDatabaseName() { - return true; - } - - protected boolean supportsCredentials() { - return true; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/H2DataSourceProvider.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/H2DataSourceProvider.java deleted file mode 100644 index 05ae686d3..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/H2DataSourceProvider.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.hypersistence.utils.hibernate.util.providers; - -import org.h2.jdbcx.JdbcConnectionPool; - -import javax.sql.DataSource; - -/** - * @author Vlad Mihalcea - */ -public class H2DataSourceProvider implements DataSourceProvider { - - @Override - public String hibernateDialect() { - return "org.hibernate.dialect.H2Dialect"; - } - - @Override - public DataSource dataSource() { - return JdbcConnectionPool.create( - url(), - username(), - password() - ); - } - - @Override - public String url() { - return "jdbc:h2:mem:test"; - } - - @Override - public String username() { - return "sa"; - } - - @Override - public String password() { - return ""; - } - - @Override - public Database database() { - return Database.H2; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/HSQLDBDataSourceProvider.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/HSQLDBDataSourceProvider.java deleted file mode 100644 index 86fd2e1c5..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/HSQLDBDataSourceProvider.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.hypersistence.utils.hibernate.util.providers; - -import org.hsqldb.jdbc.JDBCDataSource; - -import javax.sql.DataSource; - -/** - * @author Vlad Mihalcea - */ -public class HSQLDBDataSourceProvider implements DataSourceProvider { - - @Override - public String hibernateDialect() { - return "org.hibernate.dialect.HSQLDialect"; - } - - @Override - public DataSource dataSource() { - JDBCDataSource dataSource = new JDBCDataSource(); - dataSource.setUrl(url()); - dataSource.setUser(username()); - dataSource.setPassword(password()); - return dataSource; - } - - @Override - public String url() { - return "jdbc:hsqldb:mem:test"; - } - - @Override - public String username() { - return "sa"; - } - - @Override - public String password() { - return ""; - } - - @Override - public Database database() { - return Database.HSQLDB; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/MySQLDataSourceProvider.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/MySQLDataSourceProvider.java deleted file mode 100644 index 26cee53e3..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/MySQLDataSourceProvider.java +++ /dev/null @@ -1,125 +0,0 @@ -package io.hypersistence.utils.hibernate.util.providers; - -import com.mysql.cj.jdbc.MysqlDataSource; - -import javax.sql.DataSource; -import java.sql.SQLException; - -/** - * @author Vlad Mihalcea - */ -public class MySQLDataSourceProvider extends AbstractContainerDataSourceProvider { - - private boolean rewriteBatchedStatements = true; - - private boolean cachePrepStmts = false; - - private boolean useServerPrepStmts = false; - - private boolean useTimezone = false; - - private boolean useJDBCCompliantTimezoneShift = false; - - private boolean useLegacyDatetimeCode = true; - - public boolean isRewriteBatchedStatements() { - return rewriteBatchedStatements; - } - - public void setRewriteBatchedStatements(boolean rewriteBatchedStatements) { - this.rewriteBatchedStatements = rewriteBatchedStatements; - } - - public boolean isCachePrepStmts() { - return cachePrepStmts; - } - - public void setCachePrepStmts(boolean cachePrepStmts) { - this.cachePrepStmts = cachePrepStmts; - } - - public boolean isUseServerPrepStmts() { - return useServerPrepStmts; - } - - public void setUseServerPrepStmts(boolean useServerPrepStmts) { - this.useServerPrepStmts = useServerPrepStmts; - } - - public boolean isUseTimezone() { - return useTimezone; - } - - public void setUseTimezone(boolean useTimezone) { - this.useTimezone = useTimezone; - } - - public boolean isUseJDBCCompliantTimezoneShift() { - return useJDBCCompliantTimezoneShift; - } - - public void setUseJDBCCompliantTimezoneShift(boolean useJDBCCompliantTimezoneShift) { - this.useJDBCCompliantTimezoneShift = useJDBCCompliantTimezoneShift; - } - - public boolean isUseLegacyDatetimeCode() { - return useLegacyDatetimeCode; - } - - public void setUseLegacyDatetimeCode(boolean useLegacyDatetimeCode) { - this.useLegacyDatetimeCode = useLegacyDatetimeCode; - } - - @Override - public String hibernateDialect() { - return "org.hibernate.dialect.MySQL57Dialect"; - } - - @Override - protected String defaultJdbcUrl() { - return "jdbc:mysql://localhost/high_performance_java_persistence?useSSL=false"; - } - - protected DataSource newDataSource() { - try { - MysqlDataSource dataSource = new MysqlDataSource(); - dataSource.setURL(url()); - dataSource.setUser(username()); - dataSource.setPassword(password()); - dataSource.setRewriteBatchedStatements(rewriteBatchedStatements); - dataSource.setCachePrepStmts(cachePrepStmts); - dataSource.setUseServerPrepStmts(useServerPrepStmts); - - return dataSource; - } catch (SQLException e) { - throw new IllegalStateException("The DataSource could not be instantiated!"); - } - } - - @Override - public String username() { - return "mysql"; - } - - @Override - public String password() { - return "admin"; - } - - @Override - public Database database() { - return Database.MYSQL; - } - - @Override - public String toString() { - return "MySQLDataSourceProvider{" + - "rewriteBatchedStatements=" + rewriteBatchedStatements + - ", cachePrepStmts=" + cachePrepStmts + - ", useServerPrepStmts=" + useServerPrepStmts + - ", useTimezone=" + useTimezone + - ", useJDBCCompliantTimezoneShift=" + useJDBCCompliantTimezoneShift + - ", useLegacyDatetimeCode=" + useLegacyDatetimeCode + - '}'; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/OracleDataSourceProvider.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/OracleDataSourceProvider.java deleted file mode 100644 index f6992d1cb..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/OracleDataSourceProvider.java +++ /dev/null @@ -1,73 +0,0 @@ -package io.hypersistence.utils.hibernate.util.providers; - -import oracle.jdbc.pool.OracleDataSource; -import org.hibernate.dialect.Oracle12cDialect; -import org.hibernate.dialect.pagination.LimitHandler; -import org.hibernate.dialect.pagination.SQL2008StandardLimitHandler; -import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorNoOpImpl; -import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor; -import org.testcontainers.containers.JdbcDatabaseContainer; - -import javax.sql.DataSource; - -/** - * @author Vlad Mihalcea - */ -public class OracleDataSourceProvider extends AbstractContainerDataSourceProvider { - - @Override - public String hibernateDialect() { - return EnhancedOracle12cDialect.class.getName(); - } - - @Override - public String defaultJdbcUrl() { - return "jdbc:oracle:thin:@localhost:1521/xe"; - } - - @Override - public DataSource newDataSource() { - try { - OracleDataSource dataSource = new OracleDataSource(); - JdbcDatabaseContainer container = database().getContainer(); - if(container == null) { - dataSource.setDatabaseName("high_performance_java_persistence"); - } else { - dataSource.setDatabaseName(container.getDatabaseName()); - } - dataSource.setURL(url()); - dataSource.setUser(username()); - dataSource.setPassword(password()); - return dataSource; - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - @Override - public String username() { - return "oracle"; - } - - @Override - public String password() { - return "admin"; - } - - @Override - public Database database() { - return Database.ORACLE; - } - - public static class EnhancedOracle12cDialect extends Oracle12cDialect { - @Override - public LimitHandler getLimitHandler() { - return SQL2008StandardLimitHandler.INSTANCE; - } - - @Override - public SequenceInformationExtractor getSequenceInformationExtractor() { - return SequenceInformationExtractorNoOpImpl.INSTANCE; - } - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/PostgreSQLDataSourceProvider.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/PostgreSQLDataSourceProvider.java deleted file mode 100644 index 2853db9ff..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/PostgreSQLDataSourceProvider.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.hypersistence.utils.hibernate.util.providers; - -import org.hibernate.dialect.PostgreSQL10Dialect; -import org.postgresql.ds.PGSimpleDataSource; - -import javax.sql.DataSource; - -/** - * @author Vlad Mihalcea - */ -public class PostgreSQLDataSourceProvider extends AbstractContainerDataSourceProvider { - - @Override - public String hibernateDialect() { - return PostgreSQL10Dialect.class.getName(); - } - - @Override - protected String defaultJdbcUrl() { - return "jdbc:postgresql://localhost/high_performance_java_persistence"; - } - - protected DataSource newDataSource() { - PGSimpleDataSource dataSource = new PGSimpleDataSource(); - dataSource.setURL(url()); - dataSource.setUser(username()); - dataSource.setPassword(password()); - - return dataSource; - } - - @Override - public String username() { - return "postgres"; - } - - @Override - public String password() { - return "admin"; - } - - @Override - public Database database() { - return Database.POSTGRESQL; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/SQLServerDataSourceProvider.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/SQLServerDataSourceProvider.java deleted file mode 100644 index 9c1f90979..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/providers/SQLServerDataSourceProvider.java +++ /dev/null @@ -1,52 +0,0 @@ -package io.hypersistence.utils.hibernate.util.providers; - -import com.microsoft.sqlserver.jdbc.SQLServerDataSource; -import org.testcontainers.containers.JdbcDatabaseContainer; - -import javax.sql.DataSource; - -/** - * @author Vlad Mihalcea - */ -public class SQLServerDataSourceProvider extends AbstractContainerDataSourceProvider { - - @Override - public String hibernateDialect() { - return "org.hibernate.dialect.SQLServer2012Dialect"; - } - - @Override - public String defaultJdbcUrl() { - return "jdbc:sqlserver://localhost;instance=SQLEXPRESS;databaseName=high_performance_java_persistence;encrypt=true;trustServerCertificate=true"; - } - - @Override - public DataSource newDataSource() { - SQLServerDataSource dataSource = new SQLServerDataSource(); - dataSource.setURL(url()); - JdbcDatabaseContainer container = database().getContainer(); - if(container == null) { - dataSource.setUser(username()); - dataSource.setPassword(password()); - } else { - dataSource.setUser(container.getUsername()); - dataSource.setPassword(container.getPassword()); - } - return dataSource; - } - - @Override - public String username() { - return "sa"; - } - - @Override - public String password() { - return "adm1n"; - } - - @Override - public Database database() { - return Database.SQLSERVER; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/ConnectionCallable.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/ConnectionCallable.java deleted file mode 100644 index b07892e77..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/ConnectionCallable.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.hypersistence.utils.hibernate.util.transaction; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * @author Vlad Mihalcea - */ -@FunctionalInterface -public interface ConnectionCallable { - T execute(Connection connection) throws SQLException; -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/ConnectionVoidCallable.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/ConnectionVoidCallable.java deleted file mode 100644 index 07919ca39..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/ConnectionVoidCallable.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.hypersistence.utils.hibernate.util.transaction; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * @author Vlad Mihalcea - */ -@FunctionalInterface -public interface ConnectionVoidCallable { - void execute(Connection connection) throws SQLException; -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/HibernateTransactionConsumer.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/HibernateTransactionConsumer.java deleted file mode 100644 index 22c62f633..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/HibernateTransactionConsumer.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.hypersistence.utils.hibernate.util.transaction; - -import org.hibernate.Session; - -import java.util.function.Consumer; - -/** - * @author Vlad Mihalcea - */ -@FunctionalInterface -public interface HibernateTransactionConsumer extends Consumer { - default void beforeTransactionCompletion() { - - } - - default void afterTransactionCompletion() { - - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/HibernateTransactionFunction.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/HibernateTransactionFunction.java deleted file mode 100644 index c2a29a5d0..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/HibernateTransactionFunction.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.hypersistence.utils.hibernate.util.transaction; - -import org.hibernate.Session; - -import java.util.function.Function; - -/** - * @author Vlad Mihalcea - */ -@FunctionalInterface -public interface HibernateTransactionFunction extends Function { - default void beforeTransactionCompletion() { - - } - - default void afterTransactionCompletion() { - - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/JPATransactionFunction.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/JPATransactionFunction.java deleted file mode 100644 index bb0a1bc47..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/JPATransactionFunction.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.hypersistence.utils.hibernate.util.transaction; - -import javax.persistence.EntityManager; -import java.util.function.Function; - -/** - * @author Vlad Mihalcea - */ -@FunctionalInterface -public interface JPATransactionFunction extends Function { - default void beforeTransactionCompletion() { - - } - - default void afterTransactionCompletion() { - - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/JPATransactionVoidFunction.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/JPATransactionVoidFunction.java deleted file mode 100644 index 4ef3feb56..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/JPATransactionVoidFunction.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.hypersistence.utils.hibernate.util.transaction; - -import javax.persistence.EntityManager; -import java.util.function.Consumer; - -/** - * @author Vlad Mihalcea - */ -@FunctionalInterface -public interface JPATransactionVoidFunction extends Consumer { - default void beforeTransactionCompletion() { - - } - - default void afterTransactionCompletion() { - - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/VoidCallable.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/VoidCallable.java deleted file mode 100644 index 9d5147ca7..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/hibernate/util/transaction/VoidCallable.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.hypersistence.utils.hibernate.util.transaction; - -import java.util.concurrent.Callable; - -/** - * @author Vlad Mihalcea - */ -@FunctionalInterface -public interface VoidCallable extends Callable { - - void execute(); - - default Void call() throws Exception { - execute(); - return null; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/logging/InlineQueryLogEntryCreator.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/logging/InlineQueryLogEntryCreator.java deleted file mode 100644 index 135802dc4..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/logging/InlineQueryLogEntryCreator.java +++ /dev/null @@ -1,85 +0,0 @@ -package io.hypersistence.utils.logging; - -import net.ttddyy.dsproxy.ExecutionInfo; -import net.ttddyy.dsproxy.QueryInfo; -import net.ttddyy.dsproxy.listener.logging.DefaultQueryLogEntryCreator; - -import java.util.*; - -/** - * @author Vlad Mihalcea - */ -public class InlineQueryLogEntryCreator extends DefaultQueryLogEntryCreator { - @Override - protected void writeParamsEntry(StringBuilder sb, ExecutionInfo execInfo, List queryInfoList) { - sb.append("Params:["); - for (QueryInfo queryInfo : queryInfoList) { - boolean firstArg = true; - for (Map paramMap : queryInfo.getQueryArgsList()) { - - if (!firstArg) { - sb.append(", "); - } else { - firstArg = false; - } - - SortedMap sortedParamMap = new TreeMap(new CustomStringAsIntegerComparator()); - sortedParamMap.putAll(paramMap); - - sb.append("("); - boolean firstParam = true; - for (Map.Entry paramEntry : sortedParamMap.entrySet()) { - if (!firstParam) { - sb.append(", "); - } else { - firstParam = false; - } - Object parameter = paramEntry.getValue(); - if (parameter != null && parameter.getClass().isArray()) { - sb.append(arrayToString(parameter)); - } else { - sb.append(parameter); - } - } - sb.append(")"); - } - } - sb.append("]"); - } - - private String arrayToString(Object object) { - if (object.getClass().isArray()) { - if (object instanceof byte[]) { - return Arrays.toString((byte[]) object); - } - if (object instanceof short[]) { - return Arrays.toString((short[]) object); - } - if (object instanceof char[]) { - return Arrays.toString((char[]) object); - } - if (object instanceof int[]) { - return Arrays.toString((int[]) object); - } - if (object instanceof long[]) { - return Arrays.toString((long[]) object); - } - if (object instanceof float[]) { - return Arrays.toString((float[]) object); - } - if (object instanceof double[]) { - return Arrays.toString((double[]) object); - } - if (object instanceof boolean[]) { - return Arrays.toString((boolean[]) object); - } - if (object instanceof Object[]) { - return Arrays.toString((Object[]) object); - } - } - throw new UnsupportedOperationException("Array type not supported: " + object.getClass()); - } - - private static class CustomStringAsIntegerComparator extends StringAsIntegerComparator { - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/RetryAspectConfiguration.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/RetryAspectConfiguration.java deleted file mode 100644 index 6bb06f3af..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/RetryAspectConfiguration.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.hypersistence.utils.spring.aop; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -/** - * - * @author Vlad Mihalcea - */ -@Configuration -@EnableTransactionManagement -@EnableAspectJAutoProxy -@ComponentScan( - basePackages = { - "io.hypersistence.utils.spring.aop" - } -) -public class RetryAspectConfiguration { - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/RetryAspectTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/RetryAspectTest.java deleted file mode 100644 index a7db29ef4..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/RetryAspectTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package io.hypersistence.utils.spring.aop; - -import io.hypersistence.utils.spring.aop.service.CustomerService; -import io.hypersistence.utils.spring.aop.service.ItemService; -import io.hypersistence.utils.spring.aop.service.ProductService; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.persistence.OptimisticLockException; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = RetryAspectConfiguration.class) -public class RetryAspectTest { - - @Autowired - private ProductService productService; - - @Autowired - private CustomerService customerService; - - @Autowired - private ItemService itemService; - - @Before - public void before() { - productService.resetCalls(); - customerService.resetCalls(); - itemService.resetCalls(); - } - - @Test - @Ignore("https://github.com/spring-projects/spring-framework/issues/22311") - public void testRetryOnInterface() { - assertEquals(0, productService.getCalls()); - try { - productService.saveProduct(); - } catch (OptimisticLockException expected) { - } - assertEquals(3, productService.getCalls()); - } - - @Test - public void testRetryOnImplementation() { - assertEquals(0, customerService.getCalls()); - try { - customerService.saveCustomer(); - } catch (OptimisticLockException expected) { - } - assertEquals(3, customerService.getCalls()); - } - - @Test - public void testRetryOnImplementationWithArgs() { - assertEquals(0, customerService.getCalls()); - try { - customerService.saveCustomer("User A", "client"); - } catch (OptimisticLockException expected) { - } - assertEquals(3, customerService.getCalls()); - } - - @Test - public void testRetryOnImplementationWithNullArg() { - assertEquals(0, customerService.getCalls()); - try { - customerService.saveCustomer("Unknown user", null); - } catch (OptimisticLockException expected) { - } - assertEquals(3, customerService.getCalls()); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/BaseService.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/BaseService.java deleted file mode 100644 index 812a73f23..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/BaseService.java +++ /dev/null @@ -1,8 +0,0 @@ -package io.hypersistence.utils.spring.aop.service; - -public interface BaseService { - - int getCalls(); - - void resetCalls(); -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/BaseServiceImpl.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/BaseServiceImpl.java deleted file mode 100644 index 0c0910550..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/BaseServiceImpl.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.hypersistence.utils.spring.aop.service; - -import org.springframework.stereotype.Service; - -@Service -public class BaseServiceImpl { - - private volatile int calls = 0; - - protected void incrementCalls() { - calls++; - } - - public int getCalls() { - return calls; - } - - public void resetCalls() { - this.calls = 0; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/CustomerService.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/CustomerService.java deleted file mode 100644 index a4e6db1e3..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/CustomerService.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.hypersistence.utils.spring.aop.service; - -import io.hypersistence.utils.spring.annotation.Retry; -import org.springframework.stereotype.Service; - -import javax.persistence.OptimisticLockException; - -@Service -public class CustomerService extends BaseServiceImpl { - - @Retry(times = 2, on = OptimisticLockException.class) - public void saveCustomer() { - incrementCalls(); - throw new OptimisticLockException("Stale state!"); - } - - @Retry(times = 2, on = OptimisticLockException.class) - public void saveCustomer(String name, String type) { - incrementCalls(); - throw new OptimisticLockException("Stale state!"); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ItemService.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ItemService.java deleted file mode 100644 index d97ebbaba..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ItemService.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.hypersistence.utils.spring.aop.service; - -import io.hypersistence.utils.spring.annotation.Retry; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import javax.persistence.OptimisticLockException; - -/** - * ItemServiceImpl - ItemService Impl - * - * @author Vlad Mihalcea - */ -@Service -public class ItemService extends BaseServiceImpl { - - @Retry(times = 2, on = OptimisticLockException.class) - @Transactional - public void saveItem() { - incrementCalls(); - throw new OptimisticLockException("Save Item!"); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ProductService.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ProductService.java deleted file mode 100644 index 080107e5a..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ProductService.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.hypersistence.utils.spring.aop.service; - -import io.hypersistence.utils.spring.annotation.Retry; - -import javax.persistence.OptimisticLockException; - -/** - * ProductService - Product Service - * - * @author Vlad Mihalcea - */ -public interface ProductService extends BaseService { - - @Retry(times = 2, on = OptimisticLockException.class) - void saveProduct(); -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ProductServiceImpl.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ProductServiceImpl.java deleted file mode 100644 index b8fc9f620..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/aop/service/ProductServiceImpl.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.hypersistence.utils.spring.aop.service; - -import org.springframework.stereotype.Service; - -import javax.persistence.OptimisticLockException; - -@Service -public class ProductServiceImpl extends BaseServiceImpl implements ProductService { - - @Override - public void saveProduct() { - incrementCalls(); - throw new OptimisticLockException("Save Product!"); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/config/AbstractSpringDataJPAConfiguration.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/config/AbstractSpringDataJPAConfiguration.java deleted file mode 100644 index 2cc6b1e92..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/config/AbstractSpringDataJPAConfiguration.java +++ /dev/null @@ -1,116 +0,0 @@ -package io.hypersistence.utils.spring.config; - -import io.hypersistence.utils.logging.InlineQueryLogEntryCreator; -import io.hypersistence.utils.hibernate.util.providers.DataSourceProvider; -import io.hypersistence.utils.hibernate.util.providers.PostgreSQLDataSourceProvider; -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import net.ttddyy.dsproxy.listener.logging.SLF4JQueryLoggingListener; -import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; -import org.hibernate.jpa.HibernatePersistenceProvider; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.JpaVendorAdapter; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.support.TransactionTemplate; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; -import java.util.Properties; - -/** - * - * @author Vlad Mihalcea - */ -@Configuration -@EnableTransactionManagement -@EnableAspectJAutoProxy -public abstract class AbstractSpringDataJPAConfiguration { - - private DataSourceProvider dataSourceProvider = new PostgreSQLDataSourceProvider(); - - @Bean - public static PropertySourcesPlaceholderConfigurer propertySources() { - return new PropertySourcesPlaceholderConfigurer(); - } - - @Bean(destroyMethod = "close") - public HikariDataSource actualDataSource() { - Properties properties = new Properties(); - properties.setProperty("maximumPoolSize", String.valueOf(3)); - HikariConfig hikariConfig = new HikariConfig(properties); - hikariConfig.setAutoCommit(false); - hikariConfig.setDataSource(dataSourceProvider.dataSource()); - return new HikariDataSource(hikariConfig); - } - - @Bean - public DataSource dataSource() { - SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener(); - loggingListener.setQueryLogEntryCreator(new InlineQueryLogEntryCreator()); - DataSource dataSource = ProxyDataSourceBuilder - .create(actualDataSource()) - .name("DATA_SOURCE_PROXY") - .listener(loggingListener) - .build(); - return dataSource; - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); - entityManagerFactoryBean.setPersistenceUnitName(getClass().getSimpleName()); - entityManagerFactoryBean.setPersistenceProvider(new HibernatePersistenceProvider()); - entityManagerFactoryBean.setDataSource(dataSource()); - entityManagerFactoryBean.setPackagesToScan(packagesToScan()); - - JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter); - entityManagerFactoryBean.setJpaProperties(properties()); - return entityManagerFactoryBean; - } - - @Bean - public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory){ - JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(entityManagerFactory); - return transactionManager; - } - - @Bean - public TransactionTemplate transactionTemplate(EntityManagerFactory entityManagerFactory) { - return new TransactionTemplate(transactionManager(entityManagerFactory)); - } - - @Bean - public JdbcTemplate jdbcTemplate(DataSource dataSource) { - return new JdbcTemplate(dataSource); - } - - protected Properties properties() { - Properties properties = new Properties(); - properties.setProperty("hibernate.dialect", dataSourceProvider.hibernateDialect()); - properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); - additionalProperties(properties); - return properties; - } - - protected void additionalProperties(Properties properties) { - } - - protected String[] packagesToScan() { - return new String[]{ - packageToScan() - }; - } - - protected String packageToScan() { - return "io.hypersistence.utils.spring.domain"; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/domain/Post.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/domain/Post.java deleted file mode 100644 index eab2b8bb5..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/domain/Post.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.hypersistence.utils.spring.domain; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; - -/** - * @author Vlad Mihalcea - */ -@Entity -@Table( - name = "post", - uniqueConstraints = @UniqueConstraint( - name = "UK_POST_SLUG", - columnNames = "slug" - ) -) -public class Post { - - @Id - private Long id; - - private String title; - - private String slug; - - public Long getId() { - return id; - } - - public Post setId(Long id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public Post setTitle(String title) { - this.title = title; - return this; - } - - public Post setSlug(String slug) { - this.slug = slug; - return this; - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/PostRepository.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/PostRepository.java deleted file mode 100644 index a53ff6c6b..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/PostRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.hypersistence.utils.spring.repo.base; - -import io.hypersistence.utils.spring.domain.Post; -import io.hypersistence.utils.spring.repository.BaseJpaRepository; -import org.springframework.stereotype.Repository; - -/** - * @author Vlad Mihalcea - */ -@Repository -public interface PostRepository extends BaseJpaRepository { - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/SpringDataJPABaseConfiguration.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/SpringDataJPABaseConfiguration.java deleted file mode 100644 index 5d8463912..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/SpringDataJPABaseConfiguration.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.hypersistence.utils.spring.repo.base; - -import io.hypersistence.utils.spring.config.AbstractSpringDataJPAConfiguration; -import io.hypersistence.utils.spring.domain.Post; -import io.hypersistence.utils.spring.repository.BaseJpaRepositoryImpl; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -import java.util.Properties; - -/** - * - * @author Vlad Mihalcea - */ -@ComponentScan( - basePackages = { - "io.hypersistence.utils.spring.repo.base", - } -) -@EnableJpaRepositories( - value = "io.hypersistence.utils.spring.repo.base", - repositoryBaseClass = BaseJpaRepositoryImpl.class -) -public class SpringDataJPABaseConfiguration extends AbstractSpringDataJPAConfiguration { - - @Override - protected String packageToScan() { - return Post.class.getPackage().getName(); - } - - @Override - protected void additionalProperties(Properties properties) { - properties.put("hibernate.jdbc.batch_size", "100"); - properties.put("hibernate.order_inserts", "true"); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/SpringDataJPABaseTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/SpringDataJPABaseTest.java deleted file mode 100644 index c3fe3ef8a..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/base/SpringDataJPABaseTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package io.hypersistence.utils.spring.repo.base; - -import io.hypersistence.utils.spring.domain.Post; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.support.TransactionCallback; -import org.springframework.transaction.support.TransactionTemplate; - -import javax.persistence.EntityManager; -import javax.persistence.LockModeType; -import javax.persistence.PersistenceContext; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.LongStream; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * @author Vlad Mihalcea - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = SpringDataJPABaseConfiguration.class) -@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) -public class SpringDataJPABaseTest { - - protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); - - @Autowired - private TransactionTemplate transactionTemplate; - - @Autowired - private PostRepository postRepository; - - @PersistenceContext - private EntityManager entityManager; - - @Test - public void testPersistAndMerge() { - String slug = "high-performance-java-persistence"; - - transactionTemplate.execute((TransactionCallback) transactionStatus -> { - postRepository.persist( - new Post() - .setId(1L) - .setTitle("High-Performance Java Persistence") - .setSlug("high-performance-java-persistence") - ); - - postRepository.persistAndFlush( - new Post() - .setId(2L) - .setTitle("Hypersistence Optimizer") - .setSlug("hypersistence-optimizer") - ); - - postRepository.persistAllAndFlush( - LongStream.range(3, 1000) - .mapToObj(i -> new Post() - .setId(i) - .setTitle(String.format("Post %d", i)) - .setSlug(String.format("post-%d", i)) - ) - .collect(Collectors.toList()) - ); - - return null; - }); - - List posts = transactionTemplate.execute(transactionStatus -> - entityManager.createQuery( - "select p " + - "from Post p " + - "where p.id < 10", Post.class) - .getResultList() - ); - - posts.forEach(post -> post.setTitle(post.getTitle() + " rocks!")); - - transactionTemplate.execute(transactionStatus -> - postRepository.updateAll(posts) - ); - } - - @Test - public void testLockById() { - transactionTemplate.execute((TransactionCallback) transactionStatus -> { - postRepository.persist( - new Post() - .setId(1L) - .setTitle("High-Performance Java Persistence") - .setSlug("high-performance-java-persistence") - ); - return null; - }); - - transactionTemplate.execute((TransactionCallback) transactionStatus -> { - Post post = postRepository.lockById(1L, LockModeType.PESSIMISTIC_WRITE); - - assertEquals(LockModeType.PESSIMISTIC_WRITE, entityManager.getLockMode(post)); - - return null; - }); - } - - @Test - public void testGetReferenceById() { - transactionTemplate.execute((TransactionCallback) transactionStatus -> { - postRepository.persist( - new Post() - .setId(1L) - .setTitle("High-Performance Java Persistence") - .setSlug("high-performance-java-persistence") - ); - return null; - }); - - Post post = transactionTemplate.execute(transactionStatus -> postRepository.getReferenceById(1L)); - - assertEquals(Long.valueOf(1L), post.getId()); - - try { - post.getTitle(); - - fail("Should have thrown LazyInitializationException"); - } catch (Exception expected) { - } - } -} - diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/PostRepository.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/PostRepository.java deleted file mode 100644 index cd133bd95..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/PostRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.hypersistence.utils.spring.repo.hibernate; - -import io.hypersistence.utils.spring.domain.Post; -import io.hypersistence.utils.spring.repository.HibernateRepository; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -/** - * @author Vlad Mihalcea - */ -@Repository -public interface PostRepository extends HibernateRepository, JpaRepository { - -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/SpringDataJPAHibernateConfiguration.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/SpringDataJPAHibernateConfiguration.java deleted file mode 100644 index 5369200c6..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/SpringDataJPAHibernateConfiguration.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.hypersistence.utils.spring.repo.hibernate; - -import io.hypersistence.utils.spring.config.AbstractSpringDataJPAConfiguration; -import io.hypersistence.utils.spring.domain.Post; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -import java.util.Properties; - -/** - * - * @author Vlad Mihalcea - */ -@ComponentScan( - basePackages = { - "io.hypersistence.utils.spring.repo.hibernate", - } -) -@EnableJpaRepositories( - value = { - "io.hypersistence.utils.spring.repository", - "io.hypersistence.utils.spring.repo.hibernate" - } -) -public class SpringDataJPAHibernateConfiguration extends AbstractSpringDataJPAConfiguration { - - @Override - protected String packageToScan() { - return Post.class.getPackage().getName(); - } - - @Override - protected void additionalProperties(Properties properties) { - properties.put("hibernate.jdbc.batch_size", "100"); - properties.put("hibernate.order_inserts", "true"); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/SpringDataJPAHibernateTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/SpringDataJPAHibernateTest.java deleted file mode 100644 index 4bda843a5..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/hibernate/SpringDataJPAHibernateTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package io.hypersistence.utils.spring.repo.hibernate; - -import io.hypersistence.utils.spring.domain.Post; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.support.TransactionCallback; -import org.springframework.transaction.support.TransactionTemplate; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.LongStream; - -import static org.junit.Assert.fail; - -/** - * @author Vlad Mihalcea - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = SpringDataJPAHibernateConfiguration.class) -public class SpringDataJPAHibernateTest { - - protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); - - @Autowired - private TransactionTemplate transactionTemplate; - - @Autowired - private PostRepository postRepository; - - @PersistenceContext - private EntityManager entityManager; - - @Test - public void testPersistAndMerge() { - String slug = "high-performance-java-persistence"; - - transactionTemplate.execute((TransactionCallback) transactionStatus -> { - postRepository.persist( - new Post() - .setId(1L) - .setTitle("High-Performance Java Persistence") - .setSlug("high-performance-java-persistence") - ); - - postRepository.persistAndFlush( - new Post() - .setId(2L) - .setTitle("Hypersistence Optimizer") - .setSlug("hypersistence-optimizer") - ); - - postRepository.persistAllAndFlush( - LongStream.range(3, 1000) - .mapToObj(i -> new Post() - .setId(i) - .setTitle(String.format("Post %d", i)) - .setSlug(String.format("post-%d", i)) - ) - .collect(Collectors.toList()) - ); - - return null; - }); - - List posts = transactionTemplate.execute(transactionStatus -> - entityManager.createQuery( - "select p " + - "from Post p " + - "where p.id < 10", Post.class) - .getResultList() - ); - - posts.forEach(post -> post.setTitle(post.getTitle() + " rocks!")); - - transactionTemplate.execute(transactionStatus -> - postRepository.updateAll(posts) - ); - } - - @Test - public void testSave() { - try { - transactionTemplate.execute((TransactionCallback) transactionStatus -> { - postRepository.save( - new Post() - .setId(1L) - .setTitle("High-Performance Java Persistence") - .setSlug("high-performance-java-persistence") - ); - return null; - }); - - fail("Should throw UnsupportedOperationException!"); - } catch (UnsupportedOperationException expected) { - LOGGER.warn("You shouldn't call the JpaRepository save method!"); - } - } - - @Test - public void testFindAll() { - try { - transactionTemplate.execute((TransactionCallback) transactionStatus -> { - postRepository.findAll(); - return null; - }); - - fail("Should throw UnsupportedOperationException!"); - } catch (UnsupportedOperationException expected) { - LOGGER.warn("You shouldn't call the JpaRepository findAll method!"); - } - } -} - diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/PostRepository.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/PostRepository.java deleted file mode 100644 index f157f8156..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/PostRepository.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.hypersistence.utils.spring.repo.projection; - -import io.hypersistence.utils.spring.domain.Post; -import io.hypersistence.utils.spring.repository.BaseJpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.stereotype.Repository; - -import javax.annotation.Nullable; -import java.util.List; - -/** - * @author Vlad Mihalcea - */ -@Repository -public interface PostRepository extends BaseJpaRepository { - - @Query( - value = "select p.title as title, array_agg(p.slug) as slugs " + - "from Post p " + - "group by p.title", - nativeQuery = true) - @Nullable - List findAllSlugGroupedByTitle(); - - - interface TestProjection { - @Nullable - String getTitle(); - - @Nullable - List getSlugs(); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/SpringDataProjectionConfiguration.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/SpringDataProjectionConfiguration.java deleted file mode 100644 index 19a3496d3..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/SpringDataProjectionConfiguration.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.hypersistence.utils.spring.repo.projection; - -import io.hypersistence.utils.hibernate.type.array.ListArrayType; -import io.hypersistence.utils.spring.config.AbstractSpringDataJPAConfiguration; -import io.hypersistence.utils.spring.domain.Post; -import io.hypersistence.utils.spring.repository.BaseJpaRepositoryImpl; -import org.hibernate.boot.spi.MetadataBuilderContributor; -import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -import java.util.Properties; - -/** - * @author Vlad Mihalcea - */ -@ComponentScan( - basePackages = { - "io.hypersistence.utils.spring.repo.projection", - } -) -@EnableJpaRepositories( - value = "io.hypersistence.utils.spring.repo.projection", - repositoryBaseClass = BaseJpaRepositoryImpl.class -) -public class SpringDataProjectionConfiguration extends AbstractSpringDataJPAConfiguration { - - @Override - protected String packageToScan() { - return Post.class.getPackage().getName(); - } - - @Override - protected void additionalProperties(Properties properties) { - properties.put("hibernate.jdbc.batch_size", "100"); - properties.put("hibernate.order_inserts", "true"); - - properties.put( - EntityManagerFactoryBuilderImpl.METADATA_BUILDER_CONTRIBUTOR, - (MetadataBuilderContributor) metadataBuilder -> metadataBuilder.applyBasicType( - ListArrayType.INSTANCE - ) - ); - } -} diff --git a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/SpringDataProjectionTest.java b/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/SpringDataProjectionTest.java deleted file mode 100644 index 7a0d112c3..000000000 --- a/hypersistence-utils-hibernate-52/src/test/java/io/hypersistence/utils/spring/repo/projection/SpringDataProjectionTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package io.hypersistence.utils.spring.repo.projection; - -import io.hypersistence.utils.spring.domain.Post; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.support.TransactionCallback; -import org.springframework.transaction.support.TransactionTemplate; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * @author Vlad Mihalcea - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = SpringDataProjectionConfiguration.class) -@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) -public class SpringDataProjectionTest { - - protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); - - @Autowired - private TransactionTemplate transactionTemplate; - - @Autowired - private PostRepository postRepository; - - @PersistenceContext - private EntityManager entityManager; - - @Test - public void myTest() { - transactionTemplate.execute((TransactionCallback) transactionStatus -> { - postRepository.persist( - new Post() - .setId(1L) - .setTitle("test title") - .setSlug("slug1") - ); - - postRepository.persistAndFlush( - new Post() - .setId(2L) - .setTitle("test title") - .setSlug("slug2") - ); - - return null; - }); - - List postsSummary = transactionTemplate.execute(transactionStatus -> - postRepository.findAllSlugGroupedByTitle() - ); - - // then - PostRepository.TestProjection result = postsSummary.get(0); - assertEquals("test title", result.getTitle()); - - List expectedSlugs = new ArrayList<>(); - expectedSlugs.add("slug1"); - expectedSlugs.add("slug2"); - assertEquals(expectedSlugs, result.getSlugs()); - } -} - diff --git a/hypersistence-utils-hibernate-52/src/test/resources/PostgreSQLJsonBinaryTypeConfigurationTest.properties b/hypersistence-utils-hibernate-52/src/test/resources/PostgreSQLJsonBinaryTypeConfigurationTest.properties deleted file mode 100644 index b21fc24a3..000000000 --- a/hypersistence-utils-hibernate-52/src/test/resources/PostgreSQLJsonBinaryTypeConfigurationTest.properties +++ /dev/null @@ -1 +0,0 @@ -hibernate.types.jackson.object.mapper=io.hypersistence.utils.hibernate.type.json.configuration.CustomObjectMapperSupplier \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/resources/PostgreSQLJsonBinaryTypeCustomJsonSerializerConfigurationTest.properties b/hypersistence-utils-hibernate-52/src/test/resources/PostgreSQLJsonBinaryTypeCustomJsonSerializerConfigurationTest.properties deleted file mode 100644 index 7a5189019..000000000 --- a/hypersistence-utils-hibernate-52/src/test/resources/PostgreSQLJsonBinaryTypeCustomJsonSerializerConfigurationTest.properties +++ /dev/null @@ -1 +0,0 @@ -hibernate.types.json.serializer=io.hypersistence.utils.hibernate.type.json.configuration.CustomJsonSerializerSupplier \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/resources/application.properties b/hypersistence-utils-hibernate-52/src/test/resources/application.properties deleted file mode 100644 index c960d79f9..000000000 --- a/hypersistence-utils-hibernate-52/src/test/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -hibernate.types.app.props=true \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/resources/hbm/type/json/HbmJsonTypeTest.hbm.xml b/hypersistence-utils-hibernate-52/src/test/resources/hbm/type/json/HbmJsonTypeTest.hbm.xml deleted file mode 100644 index 4d6b225a5..000000000 --- a/hypersistence-utils-hibernate-52/src/test/resources/hbm/type/json/HbmJsonTypeTest.hbm.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - io.hypersistence.utils.hibernate.type.model.Location - - - - - - - - - - - - - \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/resources/hibernate-types.properties b/hypersistence-utils-hibernate-52/src/test/resources/hibernate-types.properties deleted file mode 100644 index ceba8af08..000000000 --- a/hypersistence-utils-hibernate-52/src/test/resources/hibernate-types.properties +++ /dev/null @@ -1 +0,0 @@ -hibernate.types.def=ghi \ No newline at end of file diff --git a/hypersistence-utils-hibernate-52/src/test/resources/hibernate.properties b/hypersistence-utils-hibernate-52/src/test/resources/hibernate.properties deleted file mode 100644 index d3014a3da..000000000 --- a/hypersistence-utils-hibernate-52/src/test/resources/hibernate.properties +++ /dev/null @@ -1,3 +0,0 @@ -hibernate.types.print.banner=false -hibernate.types.abc=def -hibernate.types.def=def diff --git a/hypersistence-utils-hibernate-52/src/test/resources/logback-test.xml b/hypersistence-utils-hibernate-52/src/test/resources/logback-test.xml deleted file mode 100644 index 1a284d9cd..000000000 --- a/hypersistence-utils-hibernate-52/src/test/resources/logback-test.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - ${console.log.level} - - - %-5p [%t]: %c{1} - %m%n - UTF-8 - - - - - - - - - - - - - - \ No newline at end of file diff --git a/pom.xml b/pom.xml index ce48dfd58..d45d0ac8b 100644 --- a/pom.xml +++ b/pom.xml @@ -58,7 +58,6 @@ hypersistence-utils-hibernate-62 hypersistence-utils-hibernate-60 hypersistence-utils-hibernate-55 - hypersistence-utils-hibernate-52