diff --git a/generators/base-application/support/prepare-entity.mts b/generators/base-application/support/prepare-entity.mts index 1821f2fa3a91..41089a5fd209 100644 --- a/generators/base-application/support/prepare-entity.mts +++ b/generators/base-application/support/prepare-entity.mts @@ -353,10 +353,12 @@ export function prepareEntityPrimaryKeyForTemplates(entityWithConfig, generator, entityWithConfig.primaryKey = { fieldName: 'id', derived: true, - // MapsId copy the id from the relationship. - autoGenerate: true, get fields() { - return this.derivedFields; + return this.derivedFields.map(field => preparePrimaryKeyFields(field)); + }, + get autoGenerate() { + // MapsId=!composite is autoGenerate because it copies the id from the relationship. + return !this.composite; }, get derivedFields() { return relationshipId.derivedPrimaryKey.derivedFields; @@ -380,9 +382,6 @@ export function prepareEntityPrimaryKeyForTemplates(entityWithConfig, generator, get composite() { return relationshipId.otherEntity.primaryKey.composite; }, - get ids() { - return this.fields.map(field => fieldToId(field)); - }, }; } else { const composite = enableCompositeId ? idCount > 1 : false; @@ -414,7 +413,7 @@ export function prepareEntityPrimaryKeyForTemplates(entityWithConfig, generator, ownFields: idFields, // Fields declared and inherited get fields() { - return [...this.ownFields, ...this.derivedFields]; + return [...this.ownFields, ...this.derivedFields].map(field => preparePrimaryKeyFields(field)); }, get autoGenerate() { return this.composite ? false : this.fields[0].autoGenerate; @@ -423,42 +422,27 @@ export function prepareEntityPrimaryKeyForTemplates(entityWithConfig, generator, get derivedFields() { return this.relationships.map(rel => rel.derivedPrimaryKey.derivedFields).flat(); }, - get ids() { - return this.fields.map(field => fieldToId(field)); - }, }; } return entityWithConfig; } -function fieldToId(field) { - return { - field, - get name() { - return field.fieldName; - }, - get nameCapitalized() { - return field.fieldNameCapitalized; - }, - get nameDotted() { +function preparePrimaryKeyFields(field) { + Object.defineProperty(field, 'fieldNameDotted', { + get() { return field.derivedPath ? field.derivedPath.join('.') : field.fieldName; }, - get nameDottedAsserted() { + enumerable: true, + configurable: true, + }); + Object.defineProperty(field, 'fieldNameDottedAsserted', { + get() { return field.derivedPath ? `${field.derivedPath.join('!.')}!` : `${field.fieldName}!`; }, - get setter() { - return `set${this.nameCapitalized}`; - }, - get getter() { - return (field.fieldType === BOOLEAN ? 'is' : 'get') + this.nameCapitalized; - }, - get autoGenerate() { - return !!field.autoGenerate; - }, - get relationshipsPath() { - return field.relationshipsPath; - }, - }; + enumerable: true, + configurable: true, + }); + return field; } /** diff --git a/generators/base-application/support/prepare-entity.spec.mts b/generators/base-application/support/prepare-entity.spec.mts index 8328f9901d6a..fff257ab4109 100644 --- a/generators/base-application/support/prepare-entity.spec.mts +++ b/generators/base-application/support/prepare-entity.spec.mts @@ -246,6 +246,8 @@ describe('generator - base-application - support - prepareEntity', () => { expect(field).to.deep.include({ ...entity1.primaryKey.fields[0], fieldName: 'otherEntity1Id', + fieldNameDotted: 'otherEntity1.id', + fieldNameDottedAsserted: 'otherEntity1!.id!', fieldNameCapitalized: 'OtherEntity1Id', columnName: 'other_entity1_id', derivedPath: ['otherEntity1', 'id'], @@ -258,14 +260,12 @@ describe('generator - base-application - support - prepareEntity', () => { }); it('should prepare correct relationship id ids', () => { - const field = entity4.primaryKey.ids[1]; + const field = entity4.primaryKey.fields[1]; expect(field).to.deep.include({ - name: 'otherEntity1Id', - nameCapitalized: 'OtherEntity1Id', - nameDotted: 'otherEntity1.id', - nameDottedAsserted: 'otherEntity1!.id!', - setter: 'setOtherEntity1Id', - getter: 'getOtherEntity1Id', + fieldName: 'otherEntity1Id', + fieldNameCapitalized: 'OtherEntity1Id', + fieldNameDotted: 'otherEntity1.id', + fieldNameDottedAsserted: 'otherEntity1!.id!', }); }); @@ -275,6 +275,8 @@ describe('generator - base-application - support - prepareEntity', () => { ...entity3.primaryKey.fields[0], derived: true, fieldName: 'otherEntity3Uuid', + fieldNameDotted: 'otherEntity3.uuid', + fieldNameDottedAsserted: 'otherEntity3!.uuid!', fieldNameCapitalized: 'OtherEntity3Uuid', columnName: 'other_entity3_uuid', derivedPath: ['otherEntity3', 'uuid'], @@ -286,14 +288,12 @@ describe('generator - base-application - support - prepareEntity', () => { }); it('should prepare correct relationship id with derived primaryKey field ids', () => { - const field = entity4.primaryKey.ids[2]; + const field = entity4.primaryKey.fields[2]; expect(field).to.deep.include({ - name: 'otherEntity3Uuid', - nameCapitalized: 'OtherEntity3Uuid', - nameDotted: 'otherEntity3.uuid', - nameDottedAsserted: 'otherEntity3!.uuid!', - setter: 'setOtherEntity3Uuid', - getter: 'getOtherEntity3Uuid', + fieldName: 'otherEntity3Uuid', + fieldNameCapitalized: 'OtherEntity3Uuid', + fieldNameDotted: 'otherEntity3.uuid', + fieldNameDottedAsserted: 'otherEntity3!.uuid!', }); }); }); diff --git a/generators/bootstrap-application/generator.spec.mts b/generators/bootstrap-application/generator.spec.mts index 924b628760a8..542dc0cd9fca 100644 --- a/generators/bootstrap-application/generator.spec.mts +++ b/generators/bootstrap-application/generator.spec.mts @@ -50,15 +50,10 @@ const expectedRelationship = () => ({ otherEntity: expect.any(Object), }); -const expectedPrimaryKeyId = () => ({ - field: expect.any(Object), -}); - const expectedPrimaryKey = primaryKey => ({ ownFields: expect.any(Array), fields: expect.any(Array), derivedFields: expect.any(Array), - ids: primaryKey.ids.map(expectedPrimaryKeyId), }); const expectedEntity = entity => ({ @@ -118,529 +113,518 @@ describe(`generator - ${generator}`, () => { it('should write files', () => { expect(runResult.getSnapshot('**/{.jhipster/**, entities.json}')).toMatchInlineSnapshot(` -{ - ".jhipster/EntityA.json": { - "contents": "{ - "changelogDate": "20220129025419", - "fields": [ - { - "fieldName": "id", - "fieldType": "UUID" - } - ], - "name": "EntityA", - "relationships": [] -} -", - "stateCleared": "modified", - }, - ".jhipster/User.json": { - "contents": "{ - "changelogDate": "20220129025420", - "fields": [ - { - "fieldName": "id", - "fieldType": "UUID" - } - ], - "name": "User", - "relationships": [] -} -", - "stateCleared": "modified", - }, -} -`); + { + ".jhipster/EntityA.json": { + "contents": "{ + "changelogDate": "20220129025419", + "fields": [ + { + "fieldName": "id", + "fieldType": "UUID" + } + ], + "name": "EntityA", + "relationships": [] + } + ", + "stateCleared": "modified", + }, + ".jhipster/User.json": { + "contents": "{ + "changelogDate": "20220129025420", + "fields": [ + { + "fieldName": "id", + "fieldType": "UUID" + } + ], + "name": "User", + "relationships": [] + } + ", + "stateCleared": "modified", + }, + } + `); }); it('should prepare entities', () => { expect(Object.keys(runResult.generator.sharedData.getEntitiesMap())).toMatchInlineSnapshot(` -[ - "User", - "EntityA", -] -`); + [ + "User", + "EntityA", + ] + `); }); it('should prepare User', () => { const entity = runResult.generator.sharedData.getEntitiesMap().User; expect(entity).toMatchInlineSnapshot( expectedEntity(entity), ` -{ - "adminUserDto": "AdminUserDTO", - "allReferences": Any, - "anyFieldHasDocumentation": false, - "anyFieldHasFileBasedContentType": false, - "anyFieldHasImageContentType": false, - "anyFieldHasTextContentType": false, - "anyFieldIsBigDecimal": false, - "anyFieldIsBlobDerived": false, - "anyFieldIsDateDerived": false, - "anyFieldIsDuration": false, - "anyFieldIsInstant": false, - "anyFieldIsLocalDate": false, - "anyFieldIsTimeDerived": false, - "anyFieldIsUUID": true, - "anyFieldIsZonedDateTime": false, - "anyPropertyHasValidation": false, - "applicationType": "monolith", - "authenticationType": "jwt", - "baseName": "jhipster", - "builtIn": true, - "builtInUser": true, - "changelogDate": "20220129025420", - "changelogDateForRecent": 2022-01-29T02:54:20.000Z, - "clientFramework": "angular", - "clientRootFolder": "", - "containsBagRelationships": false, - "cypressBootstrapEntities": true, - "databaseType": "sql", - "differentRelationships": {}, - "dto": true, - "dtoClass": "UserDTO", - "dtoInstance": "userDTO", - "dtoMapstruct": false, - "dtoReferences": Any, - "dtoSuffix": "DTO", - "eagerRelations": [], - "embedded": false, - "entityAbsoluteClass": "com.mycompany.myapp.domain.User", - "entityAbsoluteFolder": "com/mycompany/myapp/", - "entityAbsolutePackage": "com.mycompany.myapp", - "entityAngularJSSuffix": undefined, - "entityAngularName": "User", - "entityAngularNamePlural": "Users", - "entityApi": "", - "entityApiUrl": "users", - "entityClass": "User", - "entityClassHumanized": "User", - "entityClassPlural": "Users", - "entityClassPluralHumanized": "Users", - "entityContainsCollectionField": false, - "entityFileName": "user", - "entityFolderName": "user", - "entityI18nVariant": "default", - "entityInstance": "user", - "entityInstanceDbSafe": "jhiUser", - "entityInstancePlural": "users", - "entityJavaPackageFolder": "com/mycompany/myapp/", - "entityModelFileName": "user", - "entityNameCapitalized": "User", - "entityNamePlural": "Users", - "entityNamePluralizedAndSpinalCased": "users", - "entityPackage": undefined, - "entityPage": "user", - "entityParentPathAddition": "", - "entityPluralFileName": "usersundefined", - "entityReactName": "User", - "entityServiceFileName": "user", - "entityStateName": "user", - "entitySuffix": "", - "entityTableName": "jhi_user", - "entityTranslationKey": "user", - "entityTranslationKeyMenu": "user", - "entityUrl": "user", - "enums": [], - "existingEnum": false, - "faker": Any, - "fieldNameChoices": [], - "fields": [ - { - "autoGenerate": true, - "autoGenerateByRepository": true, - "autoGenerateByService": false, - "blobContentTypeAny": false, - "blobContentTypeImage": false, - "blobContentTypeText": false, - "builtIn": true, - "columnName": "id", - "columnType": "\${uuidType}", - "createRandexp": Any, - "dynamic": false, - "entity": Any, - "fieldInJavaBeanMethod": "Id", - "fieldIsEnum": false, - "fieldName": "id", - "fieldNameAsDatabaseColumn": "id", - "fieldNameCapitalized": "Id", - "fieldNameHumanized": "ID", - "fieldNameUnderscored": "id", - "fieldTranslationKey": "global.field.id", - "fieldType": "UUID", - "fieldTypeAnyBlob": false, - "fieldTypeBigDecimal": false, - "fieldTypeBinary": false, - "fieldTypeBlob": false, - "fieldTypeBoolean": false, - "fieldTypeByteBuffer": false, - "fieldTypeBytes": false, - "fieldTypeCharSequence": true, - "fieldTypeDouble": false, - "fieldTypeDuration": false, - "fieldTypeFloat": false, - "fieldTypeImageBlob": false, - "fieldTypeInstant": false, - "fieldTypeInteger": false, - "fieldTypeLocalDate": false, - "fieldTypeLong": false, - "fieldTypeNumeric": false, - "fieldTypeString": false, - "fieldTypeTemporal": false, - "fieldTypeTextBlob": false, - "fieldTypeTimed": false, - "fieldTypeUUID": true, - "fieldTypeZonedDateTime": false, - "fieldValidate": false, - "fieldValidateRulesMaxlength": undefined, - "fieldValidateRulesPatternAngular": undefined, - "fieldValidateRulesPatternJava": undefined, - "fieldValidateRulesPatternReact": undefined, - "fieldValidationMax": false, - "fieldValidationMaxBytes": false, - "fieldValidationMaxLength": false, - "fieldValidationMin": false, - "fieldValidationMinBytes": false, - "fieldValidationMinLength": false, - "fieldValidationPattern": false, - "fieldValidationRequired": false, - "fieldValidationUnique": false, - "fieldWithContentType": false, - "filterableField": true, - "generateFakeData": Any, - "id": true, - "javaFieldType": "UUID", - "jpaGeneratedValue": true, - "loadColumnType": "\${uuidType}", - "nullable": true, - "path": [ - "id", - ], - "propertyName": "id", - "readonly": true, - "reference": Any, - "relationshipsPath": [], - "requiresPersistableImplementation": false, - "shouldCreateContentType": false, - "shouldDropDefaultValue": false, - "tsType": "string", - "unique": false, - "uniqueValue": [], - }, - { - "blobContentTypeAny": false, - "blobContentTypeImage": false, - "blobContentTypeText": false, - "builtIn": true, - "columnName": "login", - "columnType": "varchar(255)", - "createRandexp": Any, - "entity": Any, - "fieldInJavaBeanMethod": "Login", - "fieldIsEnum": false, - "fieldName": "login", - "fieldNameAsDatabaseColumn": "login", - "fieldNameCapitalized": "Login", - "fieldNameHumanized": "Login", - "fieldNameUnderscored": "login", - "fieldTranslationKey": "jhipsterApp.user.login", - "fieldType": "String", - "fieldTypeAnyBlob": false, - "fieldTypeBigDecimal": false, - "fieldTypeBinary": false, - "fieldTypeBlob": false, - "fieldTypeBoolean": false, - "fieldTypeByteBuffer": false, - "fieldTypeBytes": false, - "fieldTypeCharSequence": true, - "fieldTypeDouble": false, - "fieldTypeDuration": false, - "fieldTypeFloat": false, - "fieldTypeImageBlob": false, - "fieldTypeInstant": false, - "fieldTypeInteger": false, - "fieldTypeLocalDate": false, - "fieldTypeLong": false, - "fieldTypeNumeric": false, - "fieldTypeString": true, - "fieldTypeTemporal": false, - "fieldTypeTextBlob": false, - "fieldTypeTimed": false, - "fieldTypeUUID": false, - "fieldTypeZonedDateTime": false, - "fieldValidate": false, - "fieldValidateRulesPatternAngular": undefined, - "fieldValidateRulesPatternJava": undefined, - "fieldValidateRulesPatternReact": undefined, - "fieldValidationMax": false, - "fieldValidationMaxBytes": false, - "fieldValidationMaxLength": false, - "fieldValidationMin": false, - "fieldValidationMinBytes": false, - "fieldValidationMinLength": false, - "fieldValidationPattern": false, - "fieldValidationRequired": false, - "fieldValidationUnique": false, - "fieldWithContentType": false, - "filterableField": true, - "generateFakeData": Any, - "javaFieldType": "String", - "loadColumnType": "string", - "nullable": true, - "path": [ - "login", - ], - "propertyName": "login", - "reference": Any, - "relationshipsPath": [], - "shouldCreateContentType": false, - "shouldDropDefaultValue": false, - "tsType": "string", - "unique": false, - "uniqueValue": [], - }, - { - "blobContentTypeAny": false, - "blobContentTypeImage": false, - "blobContentTypeText": false, - "builtIn": true, - "columnName": "first_name", - "columnType": "varchar(255)", - "createRandexp": Any, - "entity": Any, - "fieldInJavaBeanMethod": "FirstName", - "fieldIsEnum": false, - "fieldName": "firstName", - "fieldNameAsDatabaseColumn": "first_name", - "fieldNameCapitalized": "FirstName", - "fieldNameHumanized": "First Name", - "fieldNameUnderscored": "first_name", - "fieldTranslationKey": "jhipsterApp.user.firstName", - "fieldType": "String", - "fieldTypeAnyBlob": false, - "fieldTypeBigDecimal": false, - "fieldTypeBinary": false, - "fieldTypeBlob": false, - "fieldTypeBoolean": false, - "fieldTypeByteBuffer": false, - "fieldTypeBytes": false, - "fieldTypeCharSequence": true, - "fieldTypeDouble": false, - "fieldTypeDuration": false, - "fieldTypeFloat": false, - "fieldTypeImageBlob": false, - "fieldTypeInstant": false, - "fieldTypeInteger": false, - "fieldTypeLocalDate": false, - "fieldTypeLong": false, - "fieldTypeNumeric": false, - "fieldTypeString": true, - "fieldTypeTemporal": false, - "fieldTypeTextBlob": false, - "fieldTypeTimed": false, - "fieldTypeUUID": false, - "fieldTypeZonedDateTime": false, - "fieldValidate": false, - "fieldValidateRulesPatternAngular": undefined, - "fieldValidateRulesPatternJava": undefined, - "fieldValidateRulesPatternReact": undefined, - "fieldValidationMax": false, - "fieldValidationMaxBytes": false, - "fieldValidationMaxLength": false, - "fieldValidationMin": false, - "fieldValidationMinBytes": false, - "fieldValidationMinLength": false, - "fieldValidationPattern": false, - "fieldValidationRequired": false, - "fieldValidationUnique": false, - "fieldWithContentType": false, - "filterableField": true, - "generateFakeData": Any, - "javaFieldType": "String", - "loadColumnType": "string", - "nullable": true, - "path": [ - "firstName", - ], - "propertyName": "firstName", - "reference": Any, - "relationshipsPath": [], - "shouldCreateContentType": false, - "shouldDropDefaultValue": false, - "tsType": "string", - "unique": false, - "uniqueValue": [], - }, - { - "blobContentTypeAny": false, - "blobContentTypeImage": false, - "blobContentTypeText": false, - "builtIn": true, - "columnName": "last_name", - "columnType": "varchar(255)", - "createRandexp": Any, - "entity": Any, - "fieldInJavaBeanMethod": "LastName", - "fieldIsEnum": false, - "fieldName": "lastName", - "fieldNameAsDatabaseColumn": "last_name", - "fieldNameCapitalized": "LastName", - "fieldNameHumanized": "Last Name", - "fieldNameUnderscored": "last_name", - "fieldTranslationKey": "jhipsterApp.user.lastName", - "fieldType": "String", - "fieldTypeAnyBlob": false, - "fieldTypeBigDecimal": false, - "fieldTypeBinary": false, - "fieldTypeBlob": false, - "fieldTypeBoolean": false, - "fieldTypeByteBuffer": false, - "fieldTypeBytes": false, - "fieldTypeCharSequence": true, - "fieldTypeDouble": false, - "fieldTypeDuration": false, - "fieldTypeFloat": false, - "fieldTypeImageBlob": false, - "fieldTypeInstant": false, - "fieldTypeInteger": false, - "fieldTypeLocalDate": false, - "fieldTypeLong": false, - "fieldTypeNumeric": false, - "fieldTypeString": true, - "fieldTypeTemporal": false, - "fieldTypeTextBlob": false, - "fieldTypeTimed": false, - "fieldTypeUUID": false, - "fieldTypeZonedDateTime": false, - "fieldValidate": false, - "fieldValidateRulesPatternAngular": undefined, - "fieldValidateRulesPatternJava": undefined, - "fieldValidateRulesPatternReact": undefined, - "fieldValidationMax": false, - "fieldValidationMaxBytes": false, - "fieldValidationMaxLength": false, - "fieldValidationMin": false, - "fieldValidationMinBytes": false, - "fieldValidationMinLength": false, - "fieldValidationPattern": false, - "fieldValidationRequired": false, - "fieldValidationUnique": false, - "fieldWithContentType": false, - "filterableField": true, - "generateFakeData": Any, - "javaFieldType": "String", - "loadColumnType": "string", - "nullable": true, - "path": [ - "lastName", - ], - "propertyName": "lastName", - "reference": Any, - "relationshipsPath": [], - "shouldCreateContentType": false, - "shouldDropDefaultValue": false, - "tsType": "string", - "unique": false, - "uniqueValue": [], - }, - ], - "fieldsContainNoOwnerOneToOne": false, - "fluentMethods": true, - "frontendAppName": "jhipsterApp", - "generateFakeData": Any, - "i18nAlertHeaderPrefix": "jhipsterApp.user", - "i18nKeyPrefix": "jhipsterApp.user", - "implementsEagerLoadApis": false, - "importApiModelProperty": false, - "isUsingMapsId": false, - "jhiPrefix": "jhi", - "jhiTablePrefix": "jhi", - "jpaMetamodelFiltering": false, - "mapsIdAssoc": null, - "microfrontend": false, - "microserviceAppName": "", - "microserviceName": undefined, - "name": "User", - "officialDatabaseType": "SQL", - "otherDtoReferences": Any, - "otherEntities": Any, - "otherEntityPrimaryKeyTypes": [], - "otherEntityPrimaryKeyTypesIncludesUUID": false, - "otherReferences": Any, - "otherRelationships": [], - "packageFolder": "com/mycompany/myapp/", - "packageName": "com.mycompany.myapp", - "pagination": "no", - "paginationInfiniteScroll": false, - "paginationNo": true, - "paginationPagination": false, - "persistClass": "User", - "persistInstance": "user", - "primaryKey": { - "autoGenerate": true, - "composite": false, - "derived": false, - "derivedFields": Any, - "fields": Any, - "hasLong": false, - "hasUUID": true, - "ids": [ - { - "autoGenerate": true, - "field": Any, - "getter": "getId", - "name": "id", - "nameCapitalized": "Id", - "nameDotted": "id", - "nameDottedAsserted": "id!", - "relationshipsPath": [], - "setter": "setId", - }, - ], - "name": "id", - "nameCapitalized": "Id", - "ownFields": Any, - "relationships": [], - "tsType": "string", - "type": "UUID", - "typeLong": false, - "typeNumeric": false, - "typeString": false, - "typeUUID": true, - }, - "prodDatabaseType": "postgresql", - "reactive": false, - "reactiveEagerRelations": Any, - "reactiveOtherEntities": Any, - "reactiveRegularEagerRelations": Any, - "reactiveUniqueEntityTypes": Any, - "readOnly": false, - "regularEagerRelations": Any, - "relationships": [], - "relationshipsByOtherEntity": {}, - "relationshipsContainEagerLoad": false, - "relationshipsContainOtherSideIgnore": false, - "requiresPersistableImplementation": false, - "resetFakerSeed": Any, - "restClass": "UserDTO", - "restInstance": "userDTO", - "saveUserSnapshot": false, - "searchEngine": "no", - "searchEngineAny": false, - "searchEngineCouchbase": false, - "searchEngineElasticsearch": false, - "searchEngineNo": true, - "service": "no", - "serviceImpl": false, - "serviceNo": true, - "skipUiGrouping": false, - "springDataDescription": "Spring Data JPA", - "tsKeyType": "string", - "uniqueEnums": {}, - "updatableEntity": true, - "useMicroserviceJson": false, - "workaroundEntityCannotBeEmpty": false, - "workaroundInstantReactiveMariaDB": false, -} -` + { + "adminUserDto": "AdminUserDTO", + "allReferences": Any, + "anyFieldHasDocumentation": false, + "anyFieldHasFileBasedContentType": false, + "anyFieldHasImageContentType": false, + "anyFieldHasTextContentType": false, + "anyFieldIsBigDecimal": false, + "anyFieldIsBlobDerived": false, + "anyFieldIsDateDerived": false, + "anyFieldIsDuration": false, + "anyFieldIsInstant": false, + "anyFieldIsLocalDate": false, + "anyFieldIsTimeDerived": false, + "anyFieldIsUUID": true, + "anyFieldIsZonedDateTime": false, + "anyPropertyHasValidation": false, + "applicationType": "monolith", + "authenticationType": "jwt", + "baseName": "jhipster", + "builtIn": true, + "builtInUser": true, + "changelogDate": "20220129025420", + "changelogDateForRecent": 2022-01-29T02:54:20.000Z, + "clientFramework": "angular", + "clientRootFolder": "", + "containsBagRelationships": false, + "cypressBootstrapEntities": true, + "databaseType": "sql", + "differentRelationships": {}, + "dto": true, + "dtoClass": "UserDTO", + "dtoInstance": "userDTO", + "dtoMapstruct": false, + "dtoReferences": Any, + "dtoSuffix": "DTO", + "eagerRelations": [], + "embedded": false, + "entityAbsoluteClass": "com.mycompany.myapp.domain.User", + "entityAbsoluteFolder": "com/mycompany/myapp/", + "entityAbsolutePackage": "com.mycompany.myapp", + "entityAngularJSSuffix": undefined, + "entityAngularName": "User", + "entityAngularNamePlural": "Users", + "entityApi": "", + "entityApiUrl": "users", + "entityClass": "User", + "entityClassHumanized": "User", + "entityClassPlural": "Users", + "entityClassPluralHumanized": "Users", + "entityContainsCollectionField": false, + "entityFileName": "user", + "entityFolderName": "user", + "entityI18nVariant": "default", + "entityInstance": "user", + "entityInstanceDbSafe": "jhiUser", + "entityInstancePlural": "users", + "entityJavaPackageFolder": "com/mycompany/myapp/", + "entityModelFileName": "user", + "entityNameCapitalized": "User", + "entityNamePlural": "Users", + "entityNamePluralizedAndSpinalCased": "users", + "entityPackage": undefined, + "entityPage": "user", + "entityParentPathAddition": "", + "entityPluralFileName": "usersundefined", + "entityReactName": "User", + "entityServiceFileName": "user", + "entityStateName": "user", + "entitySuffix": "", + "entityTableName": "jhi_user", + "entityTranslationKey": "user", + "entityTranslationKeyMenu": "user", + "entityUrl": "user", + "enums": [], + "existingEnum": false, + "faker": Any, + "fieldNameChoices": [], + "fields": [ + { + "autoGenerate": true, + "autoGenerateByRepository": true, + "autoGenerateByService": false, + "blobContentTypeAny": false, + "blobContentTypeImage": false, + "blobContentTypeText": false, + "builtIn": true, + "columnName": "id", + "columnType": "\${uuidType}", + "createRandexp": Any, + "dynamic": false, + "entity": Any, + "fieldInJavaBeanMethod": "Id", + "fieldIsEnum": false, + "fieldName": "id", + "fieldNameAsDatabaseColumn": "id", + "fieldNameCapitalized": "Id", + "fieldNameDotted": "id", + "fieldNameDottedAsserted": "id!", + "fieldNameHumanized": "ID", + "fieldNameUnderscored": "id", + "fieldTranslationKey": "global.field.id", + "fieldType": "UUID", + "fieldTypeAnyBlob": false, + "fieldTypeBigDecimal": false, + "fieldTypeBinary": false, + "fieldTypeBlob": false, + "fieldTypeBoolean": false, + "fieldTypeByteBuffer": false, + "fieldTypeBytes": false, + "fieldTypeCharSequence": true, + "fieldTypeDouble": false, + "fieldTypeDuration": false, + "fieldTypeFloat": false, + "fieldTypeImageBlob": false, + "fieldTypeInstant": false, + "fieldTypeInteger": false, + "fieldTypeLocalDate": false, + "fieldTypeLong": false, + "fieldTypeNumeric": false, + "fieldTypeString": false, + "fieldTypeTemporal": false, + "fieldTypeTextBlob": false, + "fieldTypeTimed": false, + "fieldTypeUUID": true, + "fieldTypeZonedDateTime": false, + "fieldValidate": false, + "fieldValidateRulesMaxlength": undefined, + "fieldValidateRulesPatternAngular": undefined, + "fieldValidateRulesPatternJava": undefined, + "fieldValidateRulesPatternReact": undefined, + "fieldValidationMax": false, + "fieldValidationMaxBytes": false, + "fieldValidationMaxLength": false, + "fieldValidationMin": false, + "fieldValidationMinBytes": false, + "fieldValidationMinLength": false, + "fieldValidationPattern": false, + "fieldValidationRequired": false, + "fieldValidationUnique": false, + "fieldWithContentType": false, + "filterableField": true, + "generateFakeData": Any, + "id": true, + "javaFieldType": "UUID", + "jpaGeneratedValue": true, + "loadColumnType": "\${uuidType}", + "nullable": true, + "path": [ + "id", + ], + "propertyName": "id", + "readonly": true, + "reference": Any, + "relationshipsPath": [], + "requiresPersistableImplementation": false, + "shouldCreateContentType": false, + "shouldDropDefaultValue": false, + "tsType": "string", + "unique": false, + "uniqueValue": [], + }, + { + "blobContentTypeAny": false, + "blobContentTypeImage": false, + "blobContentTypeText": false, + "builtIn": true, + "columnName": "login", + "columnType": "varchar(255)", + "createRandexp": Any, + "entity": Any, + "fieldInJavaBeanMethod": "Login", + "fieldIsEnum": false, + "fieldName": "login", + "fieldNameAsDatabaseColumn": "login", + "fieldNameCapitalized": "Login", + "fieldNameHumanized": "Login", + "fieldNameUnderscored": "login", + "fieldTranslationKey": "jhipsterApp.user.login", + "fieldType": "String", + "fieldTypeAnyBlob": false, + "fieldTypeBigDecimal": false, + "fieldTypeBinary": false, + "fieldTypeBlob": false, + "fieldTypeBoolean": false, + "fieldTypeByteBuffer": false, + "fieldTypeBytes": false, + "fieldTypeCharSequence": true, + "fieldTypeDouble": false, + "fieldTypeDuration": false, + "fieldTypeFloat": false, + "fieldTypeImageBlob": false, + "fieldTypeInstant": false, + "fieldTypeInteger": false, + "fieldTypeLocalDate": false, + "fieldTypeLong": false, + "fieldTypeNumeric": false, + "fieldTypeString": true, + "fieldTypeTemporal": false, + "fieldTypeTextBlob": false, + "fieldTypeTimed": false, + "fieldTypeUUID": false, + "fieldTypeZonedDateTime": false, + "fieldValidate": false, + "fieldValidateRulesPatternAngular": undefined, + "fieldValidateRulesPatternJava": undefined, + "fieldValidateRulesPatternReact": undefined, + "fieldValidationMax": false, + "fieldValidationMaxBytes": false, + "fieldValidationMaxLength": false, + "fieldValidationMin": false, + "fieldValidationMinBytes": false, + "fieldValidationMinLength": false, + "fieldValidationPattern": false, + "fieldValidationRequired": false, + "fieldValidationUnique": false, + "fieldWithContentType": false, + "filterableField": true, + "generateFakeData": Any, + "javaFieldType": "String", + "loadColumnType": "string", + "nullable": true, + "path": [ + "login", + ], + "propertyName": "login", + "reference": Any, + "relationshipsPath": [], + "shouldCreateContentType": false, + "shouldDropDefaultValue": false, + "tsType": "string", + "unique": false, + "uniqueValue": [], + }, + { + "blobContentTypeAny": false, + "blobContentTypeImage": false, + "blobContentTypeText": false, + "builtIn": true, + "columnName": "first_name", + "columnType": "varchar(255)", + "createRandexp": Any, + "entity": Any, + "fieldInJavaBeanMethod": "FirstName", + "fieldIsEnum": false, + "fieldName": "firstName", + "fieldNameAsDatabaseColumn": "first_name", + "fieldNameCapitalized": "FirstName", + "fieldNameHumanized": "First Name", + "fieldNameUnderscored": "first_name", + "fieldTranslationKey": "jhipsterApp.user.firstName", + "fieldType": "String", + "fieldTypeAnyBlob": false, + "fieldTypeBigDecimal": false, + "fieldTypeBinary": false, + "fieldTypeBlob": false, + "fieldTypeBoolean": false, + "fieldTypeByteBuffer": false, + "fieldTypeBytes": false, + "fieldTypeCharSequence": true, + "fieldTypeDouble": false, + "fieldTypeDuration": false, + "fieldTypeFloat": false, + "fieldTypeImageBlob": false, + "fieldTypeInstant": false, + "fieldTypeInteger": false, + "fieldTypeLocalDate": false, + "fieldTypeLong": false, + "fieldTypeNumeric": false, + "fieldTypeString": true, + "fieldTypeTemporal": false, + "fieldTypeTextBlob": false, + "fieldTypeTimed": false, + "fieldTypeUUID": false, + "fieldTypeZonedDateTime": false, + "fieldValidate": false, + "fieldValidateRulesPatternAngular": undefined, + "fieldValidateRulesPatternJava": undefined, + "fieldValidateRulesPatternReact": undefined, + "fieldValidationMax": false, + "fieldValidationMaxBytes": false, + "fieldValidationMaxLength": false, + "fieldValidationMin": false, + "fieldValidationMinBytes": false, + "fieldValidationMinLength": false, + "fieldValidationPattern": false, + "fieldValidationRequired": false, + "fieldValidationUnique": false, + "fieldWithContentType": false, + "filterableField": true, + "generateFakeData": Any, + "javaFieldType": "String", + "loadColumnType": "string", + "nullable": true, + "path": [ + "firstName", + ], + "propertyName": "firstName", + "reference": Any, + "relationshipsPath": [], + "shouldCreateContentType": false, + "shouldDropDefaultValue": false, + "tsType": "string", + "unique": false, + "uniqueValue": [], + }, + { + "blobContentTypeAny": false, + "blobContentTypeImage": false, + "blobContentTypeText": false, + "builtIn": true, + "columnName": "last_name", + "columnType": "varchar(255)", + "createRandexp": Any, + "entity": Any, + "fieldInJavaBeanMethod": "LastName", + "fieldIsEnum": false, + "fieldName": "lastName", + "fieldNameAsDatabaseColumn": "last_name", + "fieldNameCapitalized": "LastName", + "fieldNameHumanized": "Last Name", + "fieldNameUnderscored": "last_name", + "fieldTranslationKey": "jhipsterApp.user.lastName", + "fieldType": "String", + "fieldTypeAnyBlob": false, + "fieldTypeBigDecimal": false, + "fieldTypeBinary": false, + "fieldTypeBlob": false, + "fieldTypeBoolean": false, + "fieldTypeByteBuffer": false, + "fieldTypeBytes": false, + "fieldTypeCharSequence": true, + "fieldTypeDouble": false, + "fieldTypeDuration": false, + "fieldTypeFloat": false, + "fieldTypeImageBlob": false, + "fieldTypeInstant": false, + "fieldTypeInteger": false, + "fieldTypeLocalDate": false, + "fieldTypeLong": false, + "fieldTypeNumeric": false, + "fieldTypeString": true, + "fieldTypeTemporal": false, + "fieldTypeTextBlob": false, + "fieldTypeTimed": false, + "fieldTypeUUID": false, + "fieldTypeZonedDateTime": false, + "fieldValidate": false, + "fieldValidateRulesPatternAngular": undefined, + "fieldValidateRulesPatternJava": undefined, + "fieldValidateRulesPatternReact": undefined, + "fieldValidationMax": false, + "fieldValidationMaxBytes": false, + "fieldValidationMaxLength": false, + "fieldValidationMin": false, + "fieldValidationMinBytes": false, + "fieldValidationMinLength": false, + "fieldValidationPattern": false, + "fieldValidationRequired": false, + "fieldValidationUnique": false, + "fieldWithContentType": false, + "filterableField": true, + "generateFakeData": Any, + "javaFieldType": "String", + "loadColumnType": "string", + "nullable": true, + "path": [ + "lastName", + ], + "propertyName": "lastName", + "reference": Any, + "relationshipsPath": [], + "shouldCreateContentType": false, + "shouldDropDefaultValue": false, + "tsType": "string", + "unique": false, + "uniqueValue": [], + }, + ], + "fieldsContainNoOwnerOneToOne": false, + "fluentMethods": true, + "frontendAppName": "jhipsterApp", + "generateFakeData": Any, + "i18nAlertHeaderPrefix": "jhipsterApp.user", + "i18nKeyPrefix": "jhipsterApp.user", + "implementsEagerLoadApis": false, + "importApiModelProperty": false, + "isUsingMapsId": false, + "jhiPrefix": "jhi", + "jhiTablePrefix": "jhi", + "jpaMetamodelFiltering": false, + "mapsIdAssoc": null, + "microfrontend": false, + "microserviceAppName": "", + "microserviceName": undefined, + "name": "User", + "officialDatabaseType": "SQL", + "otherDtoReferences": Any, + "otherEntities": Any, + "otherEntityPrimaryKeyTypes": [], + "otherEntityPrimaryKeyTypesIncludesUUID": false, + "otherReferences": Any, + "otherRelationships": [], + "packageFolder": "com/mycompany/myapp/", + "packageName": "com.mycompany.myapp", + "pagination": "no", + "paginationInfiniteScroll": false, + "paginationNo": true, + "paginationPagination": false, + "persistClass": "User", + "persistInstance": "user", + "primaryKey": { + "autoGenerate": true, + "composite": false, + "derived": false, + "derivedFields": Any, + "fields": Any, + "hasLong": false, + "hasUUID": true, + "name": "id", + "nameCapitalized": "Id", + "ownFields": Any, + "relationships": [], + "tsType": "string", + "type": "UUID", + "typeLong": false, + "typeNumeric": false, + "typeString": false, + "typeUUID": true, + }, + "prodDatabaseType": "postgresql", + "reactive": false, + "reactiveEagerRelations": Any, + "reactiveOtherEntities": Any, + "reactiveRegularEagerRelations": Any, + "reactiveUniqueEntityTypes": Any, + "readOnly": false, + "regularEagerRelations": Any, + "relationships": [], + "relationshipsByOtherEntity": {}, + "relationshipsContainEagerLoad": false, + "relationshipsContainOtherSideIgnore": false, + "requiresPersistableImplementation": false, + "resetFakerSeed": Any, + "restClass": "UserDTO", + "restInstance": "userDTO", + "saveUserSnapshot": false, + "searchEngine": "no", + "searchEngineAny": false, + "searchEngineCouchbase": false, + "searchEngineElasticsearch": false, + "searchEngineNo": true, + "service": "no", + "serviceImpl": false, + "serviceNo": true, + "skipUiGrouping": false, + "springDataDescription": "Spring Data JPA", + "tsKeyType": "string", + "uniqueEnums": {}, + "updatableEntity": true, + "useMicroserviceJson": false, + "workaroundEntityCannotBeEmpty": false, + "workaroundInstantReactiveMariaDB": false, + } + ` ); }); it('should prepare EntityA', () => { @@ -648,259 +632,248 @@ describe(`generator - ${generator}`, () => { expect(entity).toMatchInlineSnapshot( expectedEntity(entity), ` -{ - "allReferences": Any, - "anyFieldHasDocumentation": false, - "anyFieldHasFileBasedContentType": false, - "anyFieldHasImageContentType": false, - "anyFieldHasTextContentType": false, - "anyFieldIsBigDecimal": false, - "anyFieldIsBlobDerived": false, - "anyFieldIsDateDerived": false, - "anyFieldIsDuration": false, - "anyFieldIsInstant": false, - "anyFieldIsLocalDate": false, - "anyFieldIsTimeDerived": false, - "anyFieldIsUUID": true, - "anyFieldIsZonedDateTime": false, - "anyPropertyHasValidation": false, - "applicationType": "monolith", - "authenticationType": "jwt", - "baseName": "jhipster", - "changelogDate": "20220129025419", - "changelogDateForRecent": 2022-01-29T02:54:19.000Z, - "clientFramework": "angular", - "clientRootFolder": "", - "containsBagRelationships": false, - "cypressBootstrapEntities": true, - "databaseType": "sql", - "differentRelationships": {}, - "dto": "no", - "dtoMapstruct": false, - "dtoReferences": Any, - "dtoSuffix": "DTO", - "eagerRelations": [], - "embedded": false, - "entityAbsoluteClass": "com.mycompany.myapp.domain.EntityA", - "entityAbsoluteFolder": "com/mycompany/myapp/", - "entityAbsolutePackage": "com.mycompany.myapp", - "entityAngularJSSuffix": undefined, - "entityAngularName": "EntityA", - "entityAngularNamePlural": "EntityAS", - "entityApi": "", - "entityApiUrl": "entity-as", - "entityClass": "EntityA", - "entityClassHumanized": "Entity A", - "entityClassPlural": "EntityAS", - "entityClassPluralHumanized": "Entity AS", - "entityContainsCollectionField": false, - "entityFileName": "entity-a", - "entityFolderName": "entity-a", - "entityI18nVariant": "default", - "entityInstance": "entityA", - "entityInstanceDbSafe": "entityA", - "entityInstancePlural": "entityAS", - "entityJavaPackageFolder": "com/mycompany/myapp/", - "entityModelFileName": "entity-a", - "entityNameCapitalized": "EntityA", - "entityNamePlural": "EntityAS", - "entityNamePluralizedAndSpinalCased": "entity-as", - "entityPackage": undefined, - "entityPage": "entity-a", - "entityParentPathAddition": "", - "entityPluralFileName": "entity-asundefined", - "entityReactName": "EntityA", - "entityServiceFileName": "entity-a", - "entityStateName": "entity-a", - "entitySuffix": "", - "entityTableName": "entitya", - "entityTranslationKey": "entityA", - "entityTranslationKeyMenu": "entityA", - "entityUrl": "entity-a", - "enums": [], - "existingEnum": false, - "faker": Any, - "fieldNameChoices": [], - "fields": [ - { - "autoGenerate": true, - "autoGenerateByRepository": true, - "autoGenerateByService": false, - "blobContentTypeAny": false, - "blobContentTypeImage": false, - "blobContentTypeText": false, - "columnName": "id", - "columnType": "\${uuidType}", - "createRandexp": Any, - "dynamic": false, - "entity": Any, - "fieldInJavaBeanMethod": "Id", - "fieldIsEnum": false, - "fieldName": "id", - "fieldNameAsDatabaseColumn": "id", - "fieldNameCapitalized": "Id", - "fieldNameHumanized": "Id", - "fieldNameUnderscored": "id", - "fieldTranslationKey": "jhipsterApp.entityA.id", - "fieldType": "UUID", - "fieldTypeAnyBlob": false, - "fieldTypeBigDecimal": false, - "fieldTypeBinary": false, - "fieldTypeBlob": false, - "fieldTypeBoolean": false, - "fieldTypeByteBuffer": false, - "fieldTypeBytes": false, - "fieldTypeCharSequence": true, - "fieldTypeDouble": false, - "fieldTypeDuration": false, - "fieldTypeFloat": false, - "fieldTypeImageBlob": false, - "fieldTypeInstant": false, - "fieldTypeInteger": false, - "fieldTypeLocalDate": false, - "fieldTypeLong": false, - "fieldTypeNumeric": false, - "fieldTypeString": false, - "fieldTypeTemporal": false, - "fieldTypeTextBlob": false, - "fieldTypeTimed": false, - "fieldTypeUUID": true, - "fieldTypeZonedDateTime": false, - "fieldValidate": false, - "fieldValidateRulesPatternAngular": undefined, - "fieldValidateRulesPatternJava": undefined, - "fieldValidateRulesPatternReact": undefined, - "fieldValidationMax": false, - "fieldValidationMaxBytes": false, - "fieldValidationMaxLength": false, - "fieldValidationMin": false, - "fieldValidationMinBytes": false, - "fieldValidationMinLength": false, - "fieldValidationPattern": false, - "fieldValidationRequired": false, - "fieldValidationUnique": false, - "fieldWithContentType": false, - "filterableField": true, - "generateFakeData": Any, - "id": true, - "javaFieldType": "UUID", - "jpaGeneratedValue": true, - "loadColumnType": "\${uuidType}", - "nullable": true, - "path": [ - "id", - ], - "propertyName": "id", - "readonly": true, - "reference": Any, - "relationshipsPath": [], - "requiresPersistableImplementation": false, - "shouldCreateContentType": false, - "shouldDropDefaultValue": false, - "tsType": "string", - "unique": false, - "uniqueValue": [], - }, - ], - "fieldsContainNoOwnerOneToOne": false, - "fluentMethods": true, - "frontendAppName": "jhipsterApp", - "generateFakeData": Any, - "i18nAlertHeaderPrefix": "jhipsterApp.entityA", - "i18nKeyPrefix": "jhipsterApp.entityA", - "implementsEagerLoadApis": false, - "importApiModelProperty": false, - "isUsingMapsId": false, - "jhiPrefix": "jhi", - "jhiTablePrefix": "jhi", - "jpaMetamodelFiltering": false, - "mapsIdAssoc": null, - "microfrontend": false, - "microserviceAppName": "", - "microserviceName": undefined, - "name": "EntityA", - "officialDatabaseType": "SQL", - "otherDtoReferences": Any, - "otherEntities": Any, - "otherEntityPrimaryKeyTypes": [], - "otherEntityPrimaryKeyTypesIncludesUUID": false, - "otherReferences": Any, - "otherRelationships": [], - "packageFolder": "com/mycompany/myapp/", - "packageName": "com.mycompany.myapp", - "pagination": "no", - "paginationInfiniteScroll": false, - "paginationNo": true, - "paginationPagination": false, - "persistClass": "EntityA", - "persistInstance": "entityA", - "primaryKey": { - "autoGenerate": true, - "composite": false, - "derived": false, - "derivedFields": Any, - "fields": Any, - "hasLong": false, - "hasUUID": true, - "ids": [ - { - "autoGenerate": true, - "field": Any, - "getter": "getId", - "name": "id", - "nameCapitalized": "Id", - "nameDotted": "id", - "nameDottedAsserted": "id!", - "relationshipsPath": [], - "setter": "setId", - }, - ], - "name": "id", - "nameCapitalized": "Id", - "ownFields": Any, - "relationships": [], - "tsType": "string", - "type": "UUID", - "typeLong": false, - "typeNumeric": false, - "typeString": false, - "typeUUID": true, - }, - "prodDatabaseType": "postgresql", - "reactive": false, - "reactiveEagerRelations": Any, - "reactiveOtherEntities": Any, - "reactiveRegularEagerRelations": Any, - "reactiveUniqueEntityTypes": Any, - "readOnly": false, - "regularEagerRelations": Any, - "relationships": [], - "relationshipsByOtherEntity": {}, - "relationshipsContainEagerLoad": false, - "relationshipsContainOtherSideIgnore": false, - "requiresPersistableImplementation": false, - "resetFakerSeed": Any, - "restClass": "EntityA", - "restInstance": "entityA", - "saveUserSnapshot": false, - "searchEngine": "no", - "searchEngineAny": false, - "searchEngineCouchbase": false, - "searchEngineElasticsearch": false, - "searchEngineNo": true, - "service": "no", - "serviceImpl": false, - "serviceNo": true, - "skipUiGrouping": false, - "springDataDescription": "Spring Data JPA", - "tsKeyType": "string", - "uniqueEnums": {}, - "updatableEntity": false, - "useMicroserviceJson": false, - "workaroundEntityCannotBeEmpty": false, - "workaroundInstantReactiveMariaDB": false, -} -` + { + "allReferences": Any, + "anyFieldHasDocumentation": false, + "anyFieldHasFileBasedContentType": false, + "anyFieldHasImageContentType": false, + "anyFieldHasTextContentType": false, + "anyFieldIsBigDecimal": false, + "anyFieldIsBlobDerived": false, + "anyFieldIsDateDerived": false, + "anyFieldIsDuration": false, + "anyFieldIsInstant": false, + "anyFieldIsLocalDate": false, + "anyFieldIsTimeDerived": false, + "anyFieldIsUUID": true, + "anyFieldIsZonedDateTime": false, + "anyPropertyHasValidation": false, + "applicationType": "monolith", + "authenticationType": "jwt", + "baseName": "jhipster", + "changelogDate": "20220129025419", + "changelogDateForRecent": 2022-01-29T02:54:19.000Z, + "clientFramework": "angular", + "clientRootFolder": "", + "containsBagRelationships": false, + "cypressBootstrapEntities": true, + "databaseType": "sql", + "differentRelationships": {}, + "dto": "no", + "dtoMapstruct": false, + "dtoReferences": Any, + "dtoSuffix": "DTO", + "eagerRelations": [], + "embedded": false, + "entityAbsoluteClass": "com.mycompany.myapp.domain.EntityA", + "entityAbsoluteFolder": "com/mycompany/myapp/", + "entityAbsolutePackage": "com.mycompany.myapp", + "entityAngularJSSuffix": undefined, + "entityAngularName": "EntityA", + "entityAngularNamePlural": "EntityAS", + "entityApi": "", + "entityApiUrl": "entity-as", + "entityClass": "EntityA", + "entityClassHumanized": "Entity A", + "entityClassPlural": "EntityAS", + "entityClassPluralHumanized": "Entity AS", + "entityContainsCollectionField": false, + "entityFileName": "entity-a", + "entityFolderName": "entity-a", + "entityI18nVariant": "default", + "entityInstance": "entityA", + "entityInstanceDbSafe": "entityA", + "entityInstancePlural": "entityAS", + "entityJavaPackageFolder": "com/mycompany/myapp/", + "entityModelFileName": "entity-a", + "entityNameCapitalized": "EntityA", + "entityNamePlural": "EntityAS", + "entityNamePluralizedAndSpinalCased": "entity-as", + "entityPackage": undefined, + "entityPage": "entity-a", + "entityParentPathAddition": "", + "entityPluralFileName": "entity-asundefined", + "entityReactName": "EntityA", + "entityServiceFileName": "entity-a", + "entityStateName": "entity-a", + "entitySuffix": "", + "entityTableName": "entitya", + "entityTranslationKey": "entityA", + "entityTranslationKeyMenu": "entityA", + "entityUrl": "entity-a", + "enums": [], + "existingEnum": false, + "faker": Any, + "fieldNameChoices": [], + "fields": [ + { + "autoGenerate": true, + "autoGenerateByRepository": true, + "autoGenerateByService": false, + "blobContentTypeAny": false, + "blobContentTypeImage": false, + "blobContentTypeText": false, + "columnName": "id", + "columnType": "\${uuidType}", + "createRandexp": Any, + "dynamic": false, + "entity": Any, + "fieldInJavaBeanMethod": "Id", + "fieldIsEnum": false, + "fieldName": "id", + "fieldNameAsDatabaseColumn": "id", + "fieldNameCapitalized": "Id", + "fieldNameDotted": "id", + "fieldNameDottedAsserted": "id!", + "fieldNameHumanized": "Id", + "fieldNameUnderscored": "id", + "fieldTranslationKey": "jhipsterApp.entityA.id", + "fieldType": "UUID", + "fieldTypeAnyBlob": false, + "fieldTypeBigDecimal": false, + "fieldTypeBinary": false, + "fieldTypeBlob": false, + "fieldTypeBoolean": false, + "fieldTypeByteBuffer": false, + "fieldTypeBytes": false, + "fieldTypeCharSequence": true, + "fieldTypeDouble": false, + "fieldTypeDuration": false, + "fieldTypeFloat": false, + "fieldTypeImageBlob": false, + "fieldTypeInstant": false, + "fieldTypeInteger": false, + "fieldTypeLocalDate": false, + "fieldTypeLong": false, + "fieldTypeNumeric": false, + "fieldTypeString": false, + "fieldTypeTemporal": false, + "fieldTypeTextBlob": false, + "fieldTypeTimed": false, + "fieldTypeUUID": true, + "fieldTypeZonedDateTime": false, + "fieldValidate": false, + "fieldValidateRulesPatternAngular": undefined, + "fieldValidateRulesPatternJava": undefined, + "fieldValidateRulesPatternReact": undefined, + "fieldValidationMax": false, + "fieldValidationMaxBytes": false, + "fieldValidationMaxLength": false, + "fieldValidationMin": false, + "fieldValidationMinBytes": false, + "fieldValidationMinLength": false, + "fieldValidationPattern": false, + "fieldValidationRequired": false, + "fieldValidationUnique": false, + "fieldWithContentType": false, + "filterableField": true, + "generateFakeData": Any, + "id": true, + "javaFieldType": "UUID", + "jpaGeneratedValue": true, + "loadColumnType": "\${uuidType}", + "nullable": true, + "path": [ + "id", + ], + "propertyName": "id", + "readonly": true, + "reference": Any, + "relationshipsPath": [], + "requiresPersistableImplementation": false, + "shouldCreateContentType": false, + "shouldDropDefaultValue": false, + "tsType": "string", + "unique": false, + "uniqueValue": [], + }, + ], + "fieldsContainNoOwnerOneToOne": false, + "fluentMethods": true, + "frontendAppName": "jhipsterApp", + "generateFakeData": Any, + "i18nAlertHeaderPrefix": "jhipsterApp.entityA", + "i18nKeyPrefix": "jhipsterApp.entityA", + "implementsEagerLoadApis": false, + "importApiModelProperty": false, + "isUsingMapsId": false, + "jhiPrefix": "jhi", + "jhiTablePrefix": "jhi", + "jpaMetamodelFiltering": false, + "mapsIdAssoc": null, + "microfrontend": false, + "microserviceAppName": "", + "microserviceName": undefined, + "name": "EntityA", + "officialDatabaseType": "SQL", + "otherDtoReferences": Any, + "otherEntities": Any, + "otherEntityPrimaryKeyTypes": [], + "otherEntityPrimaryKeyTypesIncludesUUID": false, + "otherReferences": Any, + "otherRelationships": [], + "packageFolder": "com/mycompany/myapp/", + "packageName": "com.mycompany.myapp", + "pagination": "no", + "paginationInfiniteScroll": false, + "paginationNo": true, + "paginationPagination": false, + "persistClass": "EntityA", + "persistInstance": "entityA", + "primaryKey": { + "autoGenerate": true, + "composite": false, + "derived": false, + "derivedFields": Any, + "fields": Any, + "hasLong": false, + "hasUUID": true, + "name": "id", + "nameCapitalized": "Id", + "ownFields": Any, + "relationships": [], + "tsType": "string", + "type": "UUID", + "typeLong": false, + "typeNumeric": false, + "typeString": false, + "typeUUID": true, + }, + "prodDatabaseType": "postgresql", + "reactive": false, + "reactiveEagerRelations": Any, + "reactiveOtherEntities": Any, + "reactiveRegularEagerRelations": Any, + "reactiveUniqueEntityTypes": Any, + "readOnly": false, + "regularEagerRelations": Any, + "relationships": [], + "relationshipsByOtherEntity": {}, + "relationshipsContainEagerLoad": false, + "relationshipsContainOtherSideIgnore": false, + "requiresPersistableImplementation": false, + "resetFakerSeed": Any, + "restClass": "EntityA", + "restInstance": "entityA", + "saveUserSnapshot": false, + "searchEngine": "no", + "searchEngineAny": false, + "searchEngineCouchbase": false, + "searchEngineElasticsearch": false, + "searchEngineNo": true, + "service": "no", + "serviceImpl": false, + "serviceNo": true, + "skipUiGrouping": false, + "springDataDescription": "Spring Data JPA", + "tsKeyType": "string", + "uniqueEnums": {}, + "updatableEntity": false, + "useMicroserviceJson": false, + "workaroundEntityCannotBeEmpty": false, + "workaroundInstantReactiveMariaDB": false, + } + ` ); }); }); @@ -929,290 +902,279 @@ describe(`generator - ${generator}`, () => { it('should write files', () => { expect(runResult.getSnapshot('**/{.jhipster/**, entities.json}')).toMatchInlineSnapshot(` -{ - ".jhipster/EntityA.json": { - "contents": "{ - "changelogDate": "20220129025419", - "fields": [ - { - "fieldName": "id", - "fieldType": "UUID" - } - ], - "name": "EntityA", - "relationships": [] -} -", - "stateCleared": "modified", - }, -} -`); + { + ".jhipster/EntityA.json": { + "contents": "{ + "changelogDate": "20220129025419", + "fields": [ + { + "fieldName": "id", + "fieldType": "UUID" + } + ], + "name": "EntityA", + "relationships": [] + } + ", + "stateCleared": "modified", + }, + } + `); }); it('should prepare entities', () => { expect(Object.keys(runResult.generator.sharedData.getEntitiesMap())).toMatchInlineSnapshot(` -[ - "EntityA", -] -`); + [ + "EntityA", + ] + `); }); it('should prepare EntityA', () => { const entity = runResult.generator.sharedData.getEntitiesMap().EntityA; expect(entity).toMatchInlineSnapshot( expectedEntity(entity), ` -{ - "allReferences": Any, - "anyFieldHasDocumentation": false, - "anyFieldHasFileBasedContentType": false, - "anyFieldHasImageContentType": false, - "anyFieldHasTextContentType": false, - "anyFieldIsBigDecimal": false, - "anyFieldIsBlobDerived": false, - "anyFieldIsDateDerived": false, - "anyFieldIsDuration": false, - "anyFieldIsInstant": false, - "anyFieldIsLocalDate": false, - "anyFieldIsTimeDerived": false, - "anyFieldIsUUID": true, - "anyFieldIsZonedDateTime": false, - "anyPropertyHasValidation": false, - "applicationType": "monolith", - "authenticationType": "jwt", - "baseName": "jhipster", - "changelogDate": "20220129025419", - "changelogDateForRecent": 2022-01-29T02:54:19.000Z, - "clientFramework": "angular", - "clientRootFolder": "", - "containsBagRelationships": false, - "cypressBootstrapEntities": true, - "databaseType": "sql", - "differentRelationships": {}, - "dto": "no", - "dtoMapstruct": false, - "dtoReferences": Any, - "dtoSuffix": "DTO", - "eagerRelations": [], - "embedded": false, - "entityAbsoluteClass": "com.mycompany.myapp.domain.EntityA", - "entityAbsoluteFolder": "com/mycompany/myapp/", - "entityAbsolutePackage": "com.mycompany.myapp", - "entityAngularJSSuffix": undefined, - "entityAngularName": "EntityA", - "entityAngularNamePlural": "EntityAS", - "entityApi": "", - "entityApiUrl": "entity-as", - "entityClass": "EntityA", - "entityClassHumanized": "Entity A", - "entityClassPlural": "EntityAS", - "entityClassPluralHumanized": "Entity AS", - "entityContainsCollectionField": false, - "entityFileName": "entity-a", - "entityFolderName": "entity-a", - "entityI18nVariant": "default", - "entityInstance": "entityA", - "entityInstanceDbSafe": "entityA", - "entityInstancePlural": "entityAS", - "entityJavaPackageFolder": "com/mycompany/myapp/", - "entityModelFileName": "entity-a", - "entityNameCapitalized": "EntityA", - "entityNamePlural": "EntityAS", - "entityNamePluralizedAndSpinalCased": "entity-as", - "entityPackage": undefined, - "entityPage": "entity-a", - "entityParentPathAddition": "", - "entityPluralFileName": "entity-asundefined", - "entityReactName": "EntityA", - "entityServiceFileName": "entity-a", - "entityStateName": "entity-a", - "entitySuffix": "", - "entityTableName": "entitya", - "entityTranslationKey": "entityA", - "entityTranslationKeyMenu": "entityA", - "entityUrl": "entity-a", - "enums": [], - "existingEnum": false, - "faker": Any, - "fieldNameChoices": [], - "fields": [ - { - "autoGenerate": true, - "autoGenerateByRepository": true, - "autoGenerateByService": false, - "blobContentTypeAny": false, - "blobContentTypeImage": false, - "blobContentTypeText": false, - "columnName": "id", - "columnType": "\${uuidType}", - "createRandexp": Any, - "dynamic": false, - "entity": Any, - "fieldInJavaBeanMethod": "Id", - "fieldIsEnum": false, - "fieldName": "id", - "fieldNameAsDatabaseColumn": "id", - "fieldNameCapitalized": "Id", - "fieldNameHumanized": "Id", - "fieldNameUnderscored": "id", - "fieldTranslationKey": "jhipsterApp.entityA.id", - "fieldType": "UUID", - "fieldTypeAnyBlob": false, - "fieldTypeBigDecimal": false, - "fieldTypeBinary": false, - "fieldTypeBlob": false, - "fieldTypeBoolean": false, - "fieldTypeByteBuffer": false, - "fieldTypeBytes": false, - "fieldTypeCharSequence": true, - "fieldTypeDouble": false, - "fieldTypeDuration": false, - "fieldTypeFloat": false, - "fieldTypeImageBlob": false, - "fieldTypeInstant": false, - "fieldTypeInteger": false, - "fieldTypeLocalDate": false, - "fieldTypeLong": false, - "fieldTypeNumeric": false, - "fieldTypeString": false, - "fieldTypeTemporal": false, - "fieldTypeTextBlob": false, - "fieldTypeTimed": false, - "fieldTypeUUID": true, - "fieldTypeZonedDateTime": false, - "fieldValidate": false, - "fieldValidateRulesPatternAngular": undefined, - "fieldValidateRulesPatternJava": undefined, - "fieldValidateRulesPatternReact": undefined, - "fieldValidationMax": false, - "fieldValidationMaxBytes": false, - "fieldValidationMaxLength": false, - "fieldValidationMin": false, - "fieldValidationMinBytes": false, - "fieldValidationMinLength": false, - "fieldValidationPattern": false, - "fieldValidationRequired": false, - "fieldValidationUnique": false, - "fieldWithContentType": false, - "filterableField": true, - "generateFakeData": Any, - "id": true, - "javaFieldType": "UUID", - "jpaGeneratedValue": true, - "loadColumnType": "\${uuidType}", - "nullable": true, - "path": [ - "id", - ], - "propertyName": "id", - "readonly": true, - "reference": Any, - "relationshipsPath": [], - "requiresPersistableImplementation": false, - "shouldCreateContentType": false, - "shouldDropDefaultValue": false, - "tsType": "string", - "unique": false, - "uniqueValue": [], - }, - ], - "fieldsContainNoOwnerOneToOne": false, - "fluentMethods": true, - "frontendAppName": "jhipsterApp", - "generateFakeData": Any, - "i18nAlertHeaderPrefix": "jhipsterApp.entityA", - "i18nKeyPrefix": "jhipsterApp.entityA", - "implementsEagerLoadApis": false, - "importApiModelProperty": false, - "isUsingMapsId": false, - "jhiPrefix": "jhi", - "jhiTablePrefix": "jhi", - "jpaMetamodelFiltering": false, - "mapsIdAssoc": null, - "microfrontend": false, - "microserviceAppName": "", - "microserviceName": undefined, - "name": "EntityA", - "officialDatabaseType": "SQL", - "otherDtoReferences": Any, - "otherEntities": Any, - "otherEntityPrimaryKeyTypes": [], - "otherEntityPrimaryKeyTypesIncludesUUID": false, - "otherReferences": Any, - "otherRelationships": [], - "packageFolder": "com/mycompany/myapp/", - "packageName": "com.mycompany.myapp", - "pagination": "no", - "paginationInfiniteScroll": false, - "paginationNo": true, - "paginationPagination": false, - "persistClass": "EntityA", - "persistInstance": "entityA", - "primaryKey": { - "autoGenerate": true, - "composite": false, - "derived": false, - "derivedFields": Any, - "fields": Any, - "hasLong": false, - "hasUUID": true, - "ids": [ - { - "autoGenerate": true, - "field": Any, - "getter": "getId", - "name": "id", - "nameCapitalized": "Id", - "nameDotted": "id", - "nameDottedAsserted": "id!", - "relationshipsPath": [], - "setter": "setId", - }, - ], - "name": "id", - "nameCapitalized": "Id", - "ownFields": Any, - "relationships": [], - "tsType": "string", - "type": "UUID", - "typeLong": false, - "typeNumeric": false, - "typeString": false, - "typeUUID": true, - }, - "prodDatabaseType": "postgresql", - "reactive": false, - "reactiveEagerRelations": Any, - "reactiveOtherEntities": Any, - "reactiveRegularEagerRelations": Any, - "reactiveUniqueEntityTypes": Any, - "readOnly": false, - "regularEagerRelations": Any, - "relationships": [], - "relationshipsByOtherEntity": {}, - "relationshipsContainEagerLoad": false, - "relationshipsContainOtherSideIgnore": false, - "requiresPersistableImplementation": false, - "resetFakerSeed": Any, - "restClass": "EntityA", - "restInstance": "entityA", - "saveUserSnapshot": false, - "searchEngine": "no", - "searchEngineAny": false, - "searchEngineCouchbase": false, - "searchEngineElasticsearch": false, - "searchEngineNo": true, - "service": "no", - "serviceImpl": false, - "serviceNo": true, - "skipUiGrouping": false, - "springDataDescription": "Spring Data JPA", - "tsKeyType": "string", - "uniqueEnums": {}, - "updatableEntity": false, - "useMicroserviceJson": false, - "workaroundEntityCannotBeEmpty": false, - "workaroundInstantReactiveMariaDB": false, -} -` + { + "allReferences": Any, + "anyFieldHasDocumentation": false, + "anyFieldHasFileBasedContentType": false, + "anyFieldHasImageContentType": false, + "anyFieldHasTextContentType": false, + "anyFieldIsBigDecimal": false, + "anyFieldIsBlobDerived": false, + "anyFieldIsDateDerived": false, + "anyFieldIsDuration": false, + "anyFieldIsInstant": false, + "anyFieldIsLocalDate": false, + "anyFieldIsTimeDerived": false, + "anyFieldIsUUID": true, + "anyFieldIsZonedDateTime": false, + "anyPropertyHasValidation": false, + "applicationType": "monolith", + "authenticationType": "jwt", + "baseName": "jhipster", + "changelogDate": "20220129025419", + "changelogDateForRecent": 2022-01-29T02:54:19.000Z, + "clientFramework": "angular", + "clientRootFolder": "", + "containsBagRelationships": false, + "cypressBootstrapEntities": true, + "databaseType": "sql", + "differentRelationships": {}, + "dto": "no", + "dtoMapstruct": false, + "dtoReferences": Any, + "dtoSuffix": "DTO", + "eagerRelations": [], + "embedded": false, + "entityAbsoluteClass": "com.mycompany.myapp.domain.EntityA", + "entityAbsoluteFolder": "com/mycompany/myapp/", + "entityAbsolutePackage": "com.mycompany.myapp", + "entityAngularJSSuffix": undefined, + "entityAngularName": "EntityA", + "entityAngularNamePlural": "EntityAS", + "entityApi": "", + "entityApiUrl": "entity-as", + "entityClass": "EntityA", + "entityClassHumanized": "Entity A", + "entityClassPlural": "EntityAS", + "entityClassPluralHumanized": "Entity AS", + "entityContainsCollectionField": false, + "entityFileName": "entity-a", + "entityFolderName": "entity-a", + "entityI18nVariant": "default", + "entityInstance": "entityA", + "entityInstanceDbSafe": "entityA", + "entityInstancePlural": "entityAS", + "entityJavaPackageFolder": "com/mycompany/myapp/", + "entityModelFileName": "entity-a", + "entityNameCapitalized": "EntityA", + "entityNamePlural": "EntityAS", + "entityNamePluralizedAndSpinalCased": "entity-as", + "entityPackage": undefined, + "entityPage": "entity-a", + "entityParentPathAddition": "", + "entityPluralFileName": "entity-asundefined", + "entityReactName": "EntityA", + "entityServiceFileName": "entity-a", + "entityStateName": "entity-a", + "entitySuffix": "", + "entityTableName": "entitya", + "entityTranslationKey": "entityA", + "entityTranslationKeyMenu": "entityA", + "entityUrl": "entity-a", + "enums": [], + "existingEnum": false, + "faker": Any, + "fieldNameChoices": [], + "fields": [ + { + "autoGenerate": true, + "autoGenerateByRepository": true, + "autoGenerateByService": false, + "blobContentTypeAny": false, + "blobContentTypeImage": false, + "blobContentTypeText": false, + "columnName": "id", + "columnType": "\${uuidType}", + "createRandexp": Any, + "dynamic": false, + "entity": Any, + "fieldInJavaBeanMethod": "Id", + "fieldIsEnum": false, + "fieldName": "id", + "fieldNameAsDatabaseColumn": "id", + "fieldNameCapitalized": "Id", + "fieldNameDotted": "id", + "fieldNameDottedAsserted": "id!", + "fieldNameHumanized": "Id", + "fieldNameUnderscored": "id", + "fieldTranslationKey": "jhipsterApp.entityA.id", + "fieldType": "UUID", + "fieldTypeAnyBlob": false, + "fieldTypeBigDecimal": false, + "fieldTypeBinary": false, + "fieldTypeBlob": false, + "fieldTypeBoolean": false, + "fieldTypeByteBuffer": false, + "fieldTypeBytes": false, + "fieldTypeCharSequence": true, + "fieldTypeDouble": false, + "fieldTypeDuration": false, + "fieldTypeFloat": false, + "fieldTypeImageBlob": false, + "fieldTypeInstant": false, + "fieldTypeInteger": false, + "fieldTypeLocalDate": false, + "fieldTypeLong": false, + "fieldTypeNumeric": false, + "fieldTypeString": false, + "fieldTypeTemporal": false, + "fieldTypeTextBlob": false, + "fieldTypeTimed": false, + "fieldTypeUUID": true, + "fieldTypeZonedDateTime": false, + "fieldValidate": false, + "fieldValidateRulesPatternAngular": undefined, + "fieldValidateRulesPatternJava": undefined, + "fieldValidateRulesPatternReact": undefined, + "fieldValidationMax": false, + "fieldValidationMaxBytes": false, + "fieldValidationMaxLength": false, + "fieldValidationMin": false, + "fieldValidationMinBytes": false, + "fieldValidationMinLength": false, + "fieldValidationPattern": false, + "fieldValidationRequired": false, + "fieldValidationUnique": false, + "fieldWithContentType": false, + "filterableField": true, + "generateFakeData": Any, + "id": true, + "javaFieldType": "UUID", + "jpaGeneratedValue": true, + "loadColumnType": "\${uuidType}", + "nullable": true, + "path": [ + "id", + ], + "propertyName": "id", + "readonly": true, + "reference": Any, + "relationshipsPath": [], + "requiresPersistableImplementation": false, + "shouldCreateContentType": false, + "shouldDropDefaultValue": false, + "tsType": "string", + "unique": false, + "uniqueValue": [], + }, + ], + "fieldsContainNoOwnerOneToOne": false, + "fluentMethods": true, + "frontendAppName": "jhipsterApp", + "generateFakeData": Any, + "i18nAlertHeaderPrefix": "jhipsterApp.entityA", + "i18nKeyPrefix": "jhipsterApp.entityA", + "implementsEagerLoadApis": false, + "importApiModelProperty": false, + "isUsingMapsId": false, + "jhiPrefix": "jhi", + "jhiTablePrefix": "jhi", + "jpaMetamodelFiltering": false, + "mapsIdAssoc": null, + "microfrontend": false, + "microserviceAppName": "", + "microserviceName": undefined, + "name": "EntityA", + "officialDatabaseType": "SQL", + "otherDtoReferences": Any, + "otherEntities": Any, + "otherEntityPrimaryKeyTypes": [], + "otherEntityPrimaryKeyTypesIncludesUUID": false, + "otherReferences": Any, + "otherRelationships": [], + "packageFolder": "com/mycompany/myapp/", + "packageName": "com.mycompany.myapp", + "pagination": "no", + "paginationInfiniteScroll": false, + "paginationNo": true, + "paginationPagination": false, + "persistClass": "EntityA", + "persistInstance": "entityA", + "primaryKey": { + "autoGenerate": true, + "composite": false, + "derived": false, + "derivedFields": Any, + "fields": Any, + "hasLong": false, + "hasUUID": true, + "name": "id", + "nameCapitalized": "Id", + "ownFields": Any, + "relationships": [], + "tsType": "string", + "type": "UUID", + "typeLong": false, + "typeNumeric": false, + "typeString": false, + "typeUUID": true, + }, + "prodDatabaseType": "postgresql", + "reactive": false, + "reactiveEagerRelations": Any, + "reactiveOtherEntities": Any, + "reactiveRegularEagerRelations": Any, + "reactiveUniqueEntityTypes": Any, + "readOnly": false, + "regularEagerRelations": Any, + "relationships": [], + "relationshipsByOtherEntity": {}, + "relationshipsContainEagerLoad": false, + "relationshipsContainOtherSideIgnore": false, + "requiresPersistableImplementation": false, + "resetFakerSeed": Any, + "restClass": "EntityA", + "restInstance": "entityA", + "saveUserSnapshot": false, + "searchEngine": "no", + "searchEngineAny": false, + "searchEngineCouchbase": false, + "searchEngineElasticsearch": false, + "searchEngineNo": true, + "service": "no", + "serviceImpl": false, + "serviceNo": true, + "skipUiGrouping": false, + "springDataDescription": "Spring Data JPA", + "tsKeyType": "string", + "uniqueEnums": {}, + "updatableEntity": false, + "useMicroserviceJson": false, + "workaroundEntityCannotBeEmpty": false, + "workaroundInstantReactiveMariaDB": false, + } + ` ); }); }); diff --git a/generators/liquibase-changelogs/templates/src/main/resources/config/liquibase/changelog/added_entity.xml.ejs b/generators/liquibase-changelogs/templates/src/main/resources/config/liquibase/changelog/added_entity.xml.ejs index 9e5c5a1a6c38..3927298c14d5 100644 --- a/generators/liquibase-changelogs/templates/src/main/resources/config/liquibase/changelog/added_entity.xml.ejs +++ b/generators/liquibase-changelogs/templates/src/main/resources/config/liquibase/changelog/added_entity.xml.ejs @@ -47,12 +47,12 @@ <%_ } _%> <%_ for (relationship of relationships) { if ((relationship.relationshipType === 'many-to-one' || (relationship.relationshipType === 'one-to-one' && relationship.ownerSide === true)) - && !relationship.id) { + && (!relationship.id || entity.primaryKey.composite)) { relationship.otherEntity.primaryKey.fields.forEach(idField => { - const uniqueConstraintName = relationship.relationshipType === 'one-to-one' ? this.getUXConstraintName(entity.entityTableName, relationship.columnName + '_' + idField.columnName, entity.prodDatabaseType) : null; + const uniqueConstraintName = relationship.relationshipType === 'one-to-one' ? this.getUXConstraintName(entity.entityTableName, relationship.columnNamePrefix + idField.columnName, entity.prodDatabaseType) : null; _%> - - unique="true" uniqueConstraintName="<%= uniqueConstraintName %>"<% } %> /> + + primaryKey="true" <% } %>nullable="<%= relationship.nullable %>"<% if (uniqueConstraintName) { %> unique="true" uniqueConstraintName="<%= uniqueConstraintName %>"<% } %> /> <%_ }); } @@ -74,7 +74,7 @@ _%> <%_ for (field of relationship.otherEntity.primaryKey.fields) { _%> - + <%_ } _%> @@ -85,7 +85,7 @@ _%> <%_ } _%> - + <%_ } _%> <%_ } _%> @@ -113,17 +113,12 @@ _%> <%_ } _%> <%_ } _%> - <%_ for (relationship of relationships) { - if (relationship.relationshipValidate === true && relationship.relationshipRequired - && (relationship.relationshipType === "many-to-one" - || (relationship.relationshipType === "one-to-one" && relationship.ownerSide === true - && (relationship.id == null || relationship.id === false)) - )) { - _%> - <%_ for (field of relationship.otherEntity.primaryKey.fields) { _%> - - <%_ } _%> - <%_ } _%> + <%_ const relationshipsToGenerate = [...relationships.filter(r => r.id && entity.primaryKey.composite), ...relationships.filter(r => !r.id && r.relationshipRequired && (r.relationshipManyToOne || (r.relationshipOneToOne && r.ownerSide)))]; + for (relationship of relationshipsToGenerate) { + _%> + <%_ for (field of relationship.otherEntity.primaryKey.fields) { _%> + + <%_ } _%> <%_ } _%> diff --git a/generators/liquibase-changelogs/templates/src/main/resources/config/liquibase/fake-data/table_entity.csv.ejs b/generators/liquibase-changelogs/templates/src/main/resources/config/liquibase/fake-data/table_entity.csv.ejs index 964bae903bcf..1be93d10c13b 100644 --- a/generators/liquibase-changelogs/templates/src/main/resources/config/liquibase/fake-data/table_entity.csv.ejs +++ b/generators/liquibase-changelogs/templates/src/main/resources/config/liquibase/fake-data/table_entity.csv.ejs @@ -28,16 +28,9 @@ for (field of fieldsToGenerate) { header.push(field.columnName + '_content_type'); } } -for (relationship of relationships) { - const { relationshipType, joinColumnNames } = relationship; - if ( - (relationshipType === "many-to-one" - || (relationshipType === "one-to-one" && relationship.ownerSide === true - && (relationship.id == null || relationship.id === false)) - ) && (relationship.relationshipValidate === true && relationship.relationshipRequired) - ) { - header.push(joinColumnNames[0]); - } +const relationshipsToGenerate = [...relationships.filter(r => r.id && entity.primaryKey.composite), ...relationships.filter(r => !r.id && r.relationshipRequired && (r.relationshipManyToOne || (r.relationshipOneToOne && r.ownerSide)))]; +for (relationship of relationshipsToGenerate) { + header.push(...relationship.joinColumnNames); } table.push(header); @@ -64,22 +57,16 @@ for (lineNb = 0; lineNb < entity.fakeDataCount; lineNb++) { } } - for (relationship of relationships) { - const relationshipType = relationship.relationshipType; - if ( - (relationshipType === "many-to-one" - || (relationshipType === "one-to-one" && relationship.ownerSide === true - && (relationship.id == null || relationship.id === false)) - ) && (relationship.relationshipValidate === true && relationship.relationshipRequired) - ) { - const otherLiquibaseFakeData = relationship.otherEntity.liquibaseFakeData; - let relationshipRow = lineNb; - if (relationship.otherEntity.fakeDataCount > 0 && relationshipRow >= relationship.otherEntity.fakeDataCount && !relationship.unique) { - relationshipRow = entity.faker.datatype.number({min: 1, max: relationship.otherEntity.fakeDataCount}) - 1; - } - if (relationshipRow < relationship.otherEntity.fakeDataCount) { - line.push(otherLiquibaseFakeData[relationshipRow][relationship.otherEntity.primaryKey.name]); - } + for (relationship of relationshipsToGenerate) { + let relationshipRow = lineNb; + if (relationship.otherEntity.fakeDataCount > 0 && relationshipRow >= relationship.otherEntity.fakeDataCount && !relationship.unique) { + relationshipRow = entity.faker.datatype.number({min: 1, max: relationship.otherEntity.fakeDataCount}) - 1; + } + if (relationshipRow < relationship.otherEntity.fakeDataCount) { + relationship.otherEntity.primaryKey.fields.forEach(field => { + const otherLiquibaseFakeData = field.entity.liquibaseFakeData; + line.push(otherLiquibaseFakeData[relationshipRow][field.propertyName]); + }) } } if (line.length === header.length) { diff --git a/generators/server/__snapshots__/generator.spec.mjs.snap b/generators/server/__snapshots__/generator.spec.mjs.snap index 74dcdfbd34d8..5806e15fbde4 100644 --- a/generators/server/__snapshots__/generator.spec.mjs.snap +++ b/generators/server/__snapshots__/generator.spec.mjs.snap @@ -68,6 +68,9 @@ exports[`generator - server composing databaseType option no with jwt should mat "src/main/java/com/mycompany/myapp/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/com/mycompany/myapp/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/com/mycompany/myapp/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -310,6 +313,9 @@ exports[`generator - server composing databaseType option no with oauth2 should "src/main/java/com/mycompany/myapp/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/com/mycompany/myapp/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/com/mycompany/myapp/config/OAuth2Configuration.java": { "stateCleared": "modified", }, @@ -552,6 +558,9 @@ exports[`generator - server composing databaseType option no with session should "src/main/java/com/mycompany/myapp/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/com/mycompany/myapp/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/com/mycompany/myapp/config/SecurityConfiguration.java": { "stateCleared": "modified", }, diff --git a/generators/server/entity-files.mjs b/generators/server/entity-files.mjs index 8d3aa0d459f6..9e0e64975d82 100644 --- a/generators/server/entity-files.mjs +++ b/generators/server/entity-files.mjs @@ -43,6 +43,12 @@ export const modelFiles = { renameTo: moveToJavaEntityPackageSrcDir, templates: ['domain/_PersistClass_.java.jhi'], }, + { + condition: generator => generator.primaryKey && generator.primaryKey.composite && !generator.primaryKey.derived, + path: `${SERVER_MAIN_SRC_DIR}package/`, + renameTo: moveToJavaEntityPackageSrcDir, + templates: ['domain/_PersistClass_Id.java'], + }, ], modelTestFiles: [ { @@ -260,7 +266,7 @@ export function writeFiles() { await this.writeFiles({ sections: serverFiles, rootTemplatesPath: application.reactive ? ['entity/reactive', 'entity'] : 'entity', - context: { ...application, ...entity }, + context: { ...application, ...entity, entity }, }); } } diff --git a/generators/server/files.mjs b/generators/server/files.mjs index fdd86502d0b4..eedd4fc12ae2 100644 --- a/generators/server/files.mjs +++ b/generators/server/files.mjs @@ -477,6 +477,12 @@ export const baseServerFiles = { 'config/WebConfigurer.java', ], }, + { + condition: generator => !generator.reactive, + path: `${SERVER_MAIN_SRC_DIR}package/`, + renameTo: moveToJavaPackageSrcDir, + templates: ['config/MatrixVariableConfiguration.java'], + }, { condition: generator => generator.generateUserManagement || diff --git a/generators/server/generator.mjs b/generators/server/generator.mjs index 90d0df3b5dda..3f887c30cfa5 100644 --- a/generators/server/generator.mjs +++ b/generators/server/generator.mjs @@ -1101,6 +1101,13 @@ export default class JHipsterServerGenerator extends BaseApplicationGenerator { return getPKValue(primaryKey, databaseType, defaultValue); } + getJavaValueGeneratorForPrimaryKey(primaryKey) { + if (primaryKey.composite) { + return `new ${primaryKey.type}(${primaryKey.fields.map(f => this.getJavaValueGeneratorForType(f.fieldType)).join(', ')})`; + } + return this.getJavaValueGeneratorForType(primaryKey.type); + } + /** * @private * Convert to Java bean name case diff --git a/generators/server/support/__snapshots__/needles.spec.mts.snap b/generators/server/support/__snapshots__/needles.spec.mts.snap index 83bdc19869d3..6eb2a562dfc1 100644 --- a/generators/server/support/__snapshots__/needles.spec.mts.snap +++ b/generators/server/support/__snapshots__/needles.spec.mts.snap @@ -125,6 +125,9 @@ exports[`generator - server - support - needles generated project should match s "src/main/java/com/mycompany/myapp/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/com/mycompany/myapp/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/com/mycompany/myapp/config/SecurityConfiguration.java": { "stateCleared": "modified", }, diff --git a/generators/server/support/prepare-field.mjs b/generators/server/support/prepare-field.mjs index bdbf57cfcb14..b8d5e87ff3b6 100644 --- a/generators/server/support/prepare-field.mjs +++ b/generators/server/support/prepare-field.mjs @@ -51,7 +51,8 @@ export default function prepareField(entityWithConfig, field, generator) { if (field.id && entityWithConfig.primaryKey) { if (field.autoGenerate === undefined) { - field.autoGenerate = !entityWithConfig.primaryKey.composite && [LONG, UUID].includes(field.fieldType); + field.autoGenerate = + !entityWithConfig.primaryKey.composite && entityWithConfig.databaseType === SQL && [LONG, UUID].includes(field.fieldType); } if (!field.autoGenerate) { diff --git a/generators/server/templates/entity/partials/it_patch_update.partial.java.ejs b/generators/server/templates/entity/partials/it_patch_update.partial.java.ejs index c460d389b3ef..032d6a99a6d4 100644 --- a/generators/server/templates/entity/partials/it_patch_update.partial.java.ejs +++ b/generators/server/templates/entity/partials/it_patch_update.partial.java.ejs @@ -21,6 +21,12 @@ int databaseSizeBeforeUpdate = <%= entityInstance %>Repository.findAll()<%= call // Update the <%= entityInstance %> using partial update <%= persistClass %> partialUpdated<%= persistClass %> = new <%= persistClass %>(); partialUpdated<%= persistClass %>.set<%= primaryKey.nameCapitalized %>(<%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()); +<%_ primaryKey.composite && fields.filter(f => f.id).forEach(f => { _%> +partialUpdated<%= persistClass %>.set<%= f.fieldNameCapitalized %>(<%= persistInstance %>.get<%= f.fieldNameCapitalized %>()); +<%_ }) _%> +<%_ relationships.filter(r => r.id).forEach(r => { _%> +partialUpdated<%= persistClass %>.set<%= r.relationshipNameCapitalized %>(<%= persistInstance %>.get<%= r.relationshipNameCapitalized %>()); +<%_ }) _%> <%_ fieldsToUpdate = fields.filter(field => field.includeField) %> <%_ if (fluentMethods && fieldsToUpdate.length > 0) { _%> partialUpdated<%= persistClass %><% for (field of fieldsToUpdate) { %> @@ -47,7 +53,7 @@ webTestClient .expectStatus() .isOk(); <%_ } else { _%> -rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, partialUpdated<%= persistClass %>.get<%= primaryKey.nameCapitalized %>())<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%> +rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, <%- persistInstanceUrlId.replaceAll(persistInstance, 'partialUpdated' + persistClass) %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%> .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(<%= 'partialUpdated' + persistClass %>))) .andExpect(status().isOk()); diff --git a/generators/server/templates/entity/partials/save_template.ejs b/generators/server/templates/entity/partials/save_template.ejs index 9b0333dd955d..6b737645a676 100644 --- a/generators/server/templates/entity/partials/save_template.ejs +++ b/generators/server/templates/entity/partials/save_template.ejs @@ -43,7 +43,7 @@ if (isUsingMapsId) { <%_ resultEntity = persistInstance; _%> <%= persistClass %> <%= persistInstance %> = <%= dtoToEntity %>(<%= instanceName %>); <%_ if (isUsingMapsId) { _%> - <%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= instanceName %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>().get<%= primaryKey.nameCapitalized %>(); + <%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <% if (primaryKey.composite) { %><%= mapper %>.toEntity(<%= instanceName %>)<% } else { %><%= instanceName %><% } %><% if (primaryKey.fields.length === 1) { %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>()<% } %>.get<%= primaryKey.nameCapitalized %>(); <%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= persistInstance %>::<%_ if (!fluentMethods) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= mapsIdAssoc.relationshipName %><%_ } _%>); <%_ } _%> <%= persistInstance %> = <%= entityInstance %>Repository.save(<%= persistInstance %>); @@ -51,7 +51,7 @@ if (isUsingMapsId) { <%_ } else { resultEntity = 'result'; _%> <%_ if (isUsingMapsId) { _%> - <%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= instanceName %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>().get<%= primaryKey.nameCapitalized %>(); + <%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= instanceName %><% if (primaryKey.fields.length === 1) { %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>()<% } %>.get<%= primaryKey.nameCapitalized %>(); <%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= instanceName %>::<%_ if (!fluentMethods) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= otherEntityName %><%_ } _%>); <%_ } _%> <%= returnPrefix %> <%= entityInstance %>Repository.save(<%= persistInstance %>); diff --git a/generators/server/templates/entity/partials/update_template.ejs b/generators/server/templates/entity/partials/update_template.ejs index d4e59bef4871..9e33f71c0508 100644 --- a/generators/server/templates/entity/partials/update_template.ejs +++ b/generators/server/templates/entity/partials/update_template.ejs @@ -41,7 +41,7 @@ if (isUsingMapsId) { <%= persistInstance %>.setIsPersisted(); <%_ } _%> <%_ if (isUsingMapsId) { _%> - <%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= instanceName %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>().get<%= primaryKey.nameCapitalized %>(); + <%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <% if (primaryKey.composite) { %><%= mapper %>.toEntity(<%= instanceName %>)<% } else { %><%= instanceName %><% } %><% if (primaryKey.fields.length === 1) { %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>()<% } %>.get<%= primaryKey.nameCapitalized %>(); <%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= persistInstance %>::<%_ if (!fluentMethods) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= mapsIdAssoc.relationshipName %><%_ } _%>); <%_ } _%> <%_ if (updatableEntity) { _%> @@ -53,7 +53,7 @@ if (isUsingMapsId) { <%_ } else { resultEntity = 'result'; _%> <%_ if (isUsingMapsId) { _%> - <%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= instanceName %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>().get<%= primaryKey.nameCapitalized %>(); + <%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= instanceName %><% if (primaryKey.fields.length === 1) { %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>()<% } %>.get<%= primaryKey.nameCapitalized %>(); <%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= instanceName %>::<%_ if (!fluentMethods) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= otherEntityName %><%_ } _%>); <%_ } _%> <%_ if (isPersisted) { _%> diff --git a/generators/server/templates/entity/src/main/java/package/common/field_validators.ejs b/generators/server/templates/entity/src/main/java/package/common/field_validators.ejs index e2202da0aade..116e7a498eb8 100644 --- a/generators/server/templates/entity/src/main/java/package/common/field_validators.ejs +++ b/generators/server/templates/entity/src/main/java/package/common/field_validators.ejs @@ -25,7 +25,7 @@ if (field.fieldValidate) { const MAX_VALUE = 2147483647; const isBlob = field.fieldTypeBytes; - if (field.fieldValidationRequired && !isBlob) { + if (field.fieldValidationRequired && !field.autoGenerate && !isBlob) { // reactive tests need a default validation message because lookup is blocking validators.push('@NotNull' + (reactive ? '(message = "must not be null")' : '')); } diff --git a/generators/server/templates/entity/src/main/java/package/common/inject_template.ejs b/generators/server/templates/entity/src/main/java/package/common/inject_template.ejs index 48331c58f0f1..e63514b1e6bd 100644 --- a/generators/server/templates/entity/src/main/java/package/common/inject_template.ejs +++ b/generators/server/templates/entity/src/main/java/package/common/inject_template.ejs @@ -21,6 +21,9 @@ if (viaService) { beans.push({class: `${entityClass}Service`, instance: `${entityInstance}Service`}); beans.push({class: `${entityClass}Repository`, instance: `${entityInstance}Repository`}); + if (dtoMapstruct && primaryKey.composite) { + beans.push({class: `${entityClass}Mapper`, instance: `${entityInstance}Mapper`}); + } if (queryService && !reactive) { beans.push({class: `${entityClass}QueryService`, instance: `${entityInstance}QueryService`}); } @@ -32,7 +35,7 @@ } } else { beans.push({class: `${entityClass}Repository`, instance: `${entityInstance}Repository`}); - if (dtoMapstruct) { + if (dtoMapstruct || primaryKey.composite) { beans.push({class: `${entityClass}Mapper`, instance: `${entityInstance}Mapper`}); } if (searchEngineElasticsearch) { diff --git a/generators/server/templates/entity/src/main/java/package/common/patch_template.ejs b/generators/server/templates/entity/src/main/java/package/common/patch_template.ejs index 2189481e2c34..5a07a7f17dc3 100644 --- a/generators/server/templates/entity/src/main/java/package/common/patch_template.ejs +++ b/generators/server/templates/entity/src/main/java/package/common/patch_template.ejs @@ -31,7 +31,7 @@ _%> Optional<<%= instanceType %>> result = <%= entityInstance %>Service.partialUpdate(<%= instanceName %>); <%_ } _%> <%_ } else { %> -<%- returnPrefix %> <%= entityInstance %>Repository.findById(<%= instanceName %>.get<%= primaryKey.nameCapitalized %>()) +<%- returnPrefix %> <%= entityInstance %>Repository.findById(<%= primaryKey.composite && dtoMapstruct ? `${mapper}.toEntity(${instanceName})` : instanceName %>.get<%= primaryKey.nameCapitalized %>()) .map(existing<%= entityClass %> -> { <%_ if (dtoMapstruct) { _%> <%= mapper %>.partialUpdate(existing<%= entityClass %>, <%= instanceName %>); diff --git a/generators/server/templates/entity/src/main/java/package/domain/_PersistClass_.java.jhi.ejs b/generators/server/templates/entity/src/main/java/package/domain/_PersistClass_.java.jhi.ejs index 6b43cb79f981..304b3f7a9aa6 100644 --- a/generators/server/templates/entity/src/main/java/package/domain/_PersistClass_.java.jhi.ejs +++ b/generators/server/templates/entity/src/main/java/package/domain/_PersistClass_.java.jhi.ejs @@ -102,13 +102,13 @@ public class <%= persistClass %> <&- fragments.extendsSection() -&>implements Se private static final long serialVersionUID = 1L; <%_ if (!embedded && primaryKey.composite) { _%> - @Id + @EmbeddedId private <%= primaryKey.type %> <%= primaryKey.name %>; <%_ } _%> <&- fragments.classStaticFieldsSection() -&> <&- fragments.classFieldsSection() -&> -<%_ for (const field of fields.filter(field => !field.javaInherited && !field.transient && (embedded || !field.id || !primaryKey.composite))) { _%> +<%_ for (const field of fields.filter(field => !field.javaInherited && !field.transient && (embedded || !(field.id && primaryKey.composite && primaryKey.fields.length === 1)))) { _%> <&- fragments.field<%- field.fieldNameCapitalized %>CustomDeclarationSection() -&> <&_ if (!fragments.field<%- field.fieldNameCapitalized %>CustomDeclarationSection()) { -&> <%_ if (typeof field.javadoc !== 'undefined') { _%> @@ -176,7 +176,24 @@ for (relationship of relationships.filter(relationship => !relationship.embedded <%_ }; _%> <&- fragments.classAdditionalRelationshipsSection() -&> // jhipster-needle-entity-add-field - JHipster will add fields here -<%_ for (const field of fields.filter(field => !field.transient && (embedded || !field.id || !primaryKey.composite))) { _%> +<%_ if (!embedded && primaryKey.composite) { _%> + + public <%= primaryKey.type %> get<%= primaryKey.nameCapitalized %>() { + return this.<%= primaryKey.name %>; + } + <%_ if (fluentMethods) { _%> + + public <%= persistClass %> <%= primaryKey.name %>(<%= primaryKey.type %> <%= primaryKey.name %>) { + this.set<%= primaryKey.nameCapitalized %>(<%= primaryKey.name %>); + return this; + } + <%_ } _%> + + public void set<%= primaryKey.nameCapitalized %>(<%= primaryKey.type %> <%= primaryKey.name %>) { + this.<%= primaryKey.name %> = <%= primaryKey.name %>; + } +<%_ } _%> +<%_ for (const field of fields.filter(field => !field.transient && (embedded || !(field.id && primaryKey.composite && primaryKey.fields.length === 1)))) { _%> <&- fragments.field<%- field.fieldNameCapitalized %>CustomMethodsSection() -&> <&_ if (!fragments.field<%- field.fieldNameCapitalized %>CustomMethodsSection()) { -&> diff --git a/generators/server/templates/entity/src/main/java/package/domain/_PersistClass_Id.java.ejs b/generators/server/templates/entity/src/main/java/package/domain/_PersistClass_Id.java.ejs new file mode 100644 index 000000000000..6ec85ce380aa --- /dev/null +++ b/generators/server/templates/entity/src/main/java/package/domain/_PersistClass_Id.java.ejs @@ -0,0 +1,98 @@ +<%# + Copyright 2013-2022 the original author or authors from the JHipster project. + + This file is part of the JHipster project, see https://www.jhipster.tech/ + for more information. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +-%> +package <%=packageName%>.domain; +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import jakarta.persistence.metamodel.StaticMetamodel; +<%_ if (anyPropertyHasValidation) { _%> +import jakarta.validation.constraints.*; +<%_ } _%> +import java.util.Objects; +<%_ if (primaryKey.fields.some(field => field.fieldType === 'UUID')) { _%> +import java.util.UUID; +<%_ } _%> + +@Embeddable +@StaticMetamodel(<%= entityClass %>Id.class) +public class <%= entityClass %>Id implements java.io.Serializable { +<%_ +primaryKey.fields.forEach(field => { _%> + + <%_ if (field.isEnum) { _%> + @Enumerated(EnumType.STRING) + <%_ } + if (field.fieldValidateRules && field.fieldValidateRules.includes('required')) { + required = true; + } + const fieldValidateRules = field.fieldValidateRules; + _%> + <%_ if (fieldValidateRules && fieldValidateRules.length > 0) { _%> + <%- include('../common/field_validators'); -%> + <%_ } _%> + @Column(name = "<%= field.columnName %>"<% if (field.fieldValidate === true) { %><% if (field.fieldValidateRules.includes('maxlength')) { %>, length = <%= field.fieldValidateRulesMaxlength %><% } %><% if (field.required) { %>, nullable = false<% } %><% if (field.unique) { %>, unique = true<% } %><% } %>) + private <%= field.fieldType %> <%= field.fieldName %>; +<%_ }) _%> + + public <%= entityClass %>Id(){} + + public <%= entityClass %>Id(<%= primaryKey.fields.map(field => field.fieldType + ' ' + field.fieldName).join(', ') %>){ +<%_ primaryKey.fields.forEach(field => { _%> + this.<%= field.fieldName %> = <%= field.fieldName %>; +<%_ }) _%> + } +<%_ primaryKey.fields.forEach(field => { _%> + + public <%= field.fieldType %> get<%= field.fieldNameCapitalized %>(){ + return this.<%= field.fieldName %>; + } + + public void set<%= field.fieldNameCapitalized %>(<%= field.fieldType %> <%= field.fieldName %>){ + this.<%= field.fieldName %> = <%= field.fieldName %>; + } +<%_ }) _%> + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof <%= entityClass %>Id)) { + return false; + } + + <%= entityClass %>Id <%= entityInstance %>Id = (<%= entityClass %>Id) o; + return <%- primaryKey.fields.map(f => `Objects.equals(${f.fieldName}, ${entityInstance}Id.${f.fieldName})`).join('\n && ') %>; + } + + @Override + public int hashCode() { + return Objects.hash(<%= primaryKey.fields.map(f => f.fieldName).join(', ')%>); + } + + // prettier-ignore + @Override + public String toString() { + return "<%= entityClass %>Id{" + + <%_ primaryKey.fields.forEach(field => { + const isNumeric = ['integer', 'long', 'float', 'double', 'bigdecimal'].includes(field.fieldType.toLowerCase()); _%> + ", <%= field.fieldName %>=<% if (! isNumeric) {%>'<% } %>" + get<%= field.fieldNameCapitalized %>() <% if (! isNumeric) { %>+ "'" <% } %>+ + <%_ }) _%> + "}"; + } +} diff --git a/generators/server/templates/entity/src/main/java/package/domain/enumeration/Enum.java.ejs b/generators/server/templates/entity/src/main/java/package/domain/enumeration/Enum.java.ejs index 563c495690c4..0add48f08095 100644 --- a/generators/server/templates/entity/src/main/java/package/domain/enumeration/Enum.java.ejs +++ b/generators/server/templates/entity/src/main/java/package/domain/enumeration/Enum.java.ejs @@ -28,16 +28,16 @@ package <%= entityAbsolutePackage %>.domain.enumeration; public enum <%= enumName %> { <%_ if (withoutCustomValues) { _%> <%= enumValues.map(enumValue => `${enumValue.comment && `\n${enumValue.comment}\n` || ''} ${enumValue.name}`).join(', ') %> -<%_ } else { +<%_ } else { // The following code redefines the variable state to be 'without CustomValue' when name equals value. - withoutCustomValues = enumValues.every(({name, value}) => name === value); - withCustomValues = enumValues.every(({name, value}) => name !== value); + withoutCustomValues = enumValues.every(({name, value}) => name === value); + withCustomValues = enumValues.every(({name, value}) => name !== value); withSomeCustomValues = !withoutCustomValues && !withCustomValues; enumValues.forEach((enumWithCustomValue, index) => { if (enumWithCustomValue.comment){ _%> <%= enumWithCustomValue.comment %> - <%_ } + <%_ } if (enumWithCustomValue.name === enumWithCustomValue.value) { _%> <%= enumWithCustomValue.name %><% if (index < enumValues.length - 1) { %>,<% } else { %>;<% } %> <%_ } else { _%> @@ -58,6 +58,6 @@ public enum <%= enumName %> { public String getValue() { return value; } - <%_ } _%> + <%_ } _%> <%_ } _%> } diff --git a/generators/server/templates/entity/src/main/java/package/repository/_EntityClass_Repository.java.ejs b/generators/server/templates/entity/src/main/java/package/repository/_EntityClass_Repository.java.ejs index 22b280f89da3..2547f7f04f25 100644 --- a/generators/server/templates/entity/src/main/java/package/repository/_EntityClass_Repository.java.ejs +++ b/generators/server/templates/entity/src/main/java/package/repository/_EntityClass_Repository.java.ejs @@ -49,6 +49,9 @@ import java.util.List; import java.util.Optional; <%_ } _%> <%_ } _%> +<%_ if (primaryKey.composite) { _%> +import <%=packageName%>.domain.<%=primaryKey.type%>; +<%_ } _%> <%_ if (primaryKey.typeUUID) { _%> import java.util.UUID; diff --git a/generators/server/templates/entity/src/main/java/package/service/_EntityClass_QueryService.java.ejs b/generators/server/templates/entity/src/main/java/package/service/_EntityClass_QueryService.java.ejs index 61b3e5864654..9a75b5aec4f0 100644 --- a/generators/server/templates/entity/src/main/java/package/service/_EntityClass_QueryService.java.ejs +++ b/generators/server/templates/entity/src/main/java/package/service/_EntityClass_QueryService.java.ejs @@ -129,26 +129,26 @@ public class <%= serviceClassName %> extends QueryService<<%= persistClass %>> { if (criteria.getDistinct() != null) { specification = specification.and(distinct(criteria.getDistinct())); } - if (criteria.get<%= primaryKey.nameCapitalized %>() != null) { - specification = specification.and(<%= this.getSpecificationBuilder(primaryKey.type) %>(criteria.get<%= primaryKey.nameCapitalized %>(), <%= persistClass %>_.<%= primaryKey.name %>)); - } <%_ fields.forEach((field) => { - if (field.id || field.transient) return; if (field.filterableField) { _%> if (criteria.get<%= field.fieldInJavaBeanMethod %>() != null) { + <%_ if (field.id && primaryKey.composite) { _%> + specification = specification.and(buildSpecification(criteria.get<%= field.fieldInJavaBeanMethod %>(), root -> root.get(<%= persistClass %>_.id).get(<%= primaryKey.type %>_.<%= field.fieldName %>))); + <%_ } else { _%> specification = specification.and(<%= this.getSpecificationBuilder(field.fieldType) %>(criteria.get<%= field.fieldInJavaBeanMethod %>(), <%= persistClass %>_.<%= field.fieldName %>)); + <%_ } _%> } <%_ } }); -relationships.forEach((relationship) => { +relationships.forEach((relationship) => relationship.otherEntity.primaryKey.fields.forEach((field) => { const metamodelFieldName = (relationship.relationshipManyToMany || relationship.relationshipOneToMany) ? relationship.relationshipFieldNamePlural : relationship.relationshipFieldName; _%> -if (criteria.get<%= relationship.relationshipNameCapitalized %>Id() != null) { - specification = specification.and(buildSpecification(criteria.get<%= relationship.relationshipNameCapitalized %>Id(), - root -> root.join(<%= persistClass %>_.<%= metamodelFieldName %>, JoinType.LEFT).get(<%= relationship.otherEntity.persistClass %>_.<%= relationship.otherEntity.primaryKey.name %>))); +if (criteria.get<%= relationship.relationshipNameCapitalized %><%= field.fieldNameCapitalized %>() != null) { + specification = specification.and(buildSpecification(criteria.get<%= relationship.relationshipNameCapitalized %><%= field.fieldNameCapitalized %>(), + root -> root.join(<%= persistClass %>_.<%= metamodelFieldName %>, JoinType.LEFT)<%- relationship.otherEntity.primaryKey.composite ? `.get(${relationship.otherEntity.persistClass}_.id).get(${relationship.otherEntity.primaryKey.type}_.${field.fieldName})` : `.get(${relationship.otherEntity.persistClass}_.${field.fieldName})` %>)); } -<%_ }); /* forEach */ _%> +<%_ })); /* forEach */ _%> } return specification; } diff --git a/generators/server/templates/entity/src/main/java/package/service/_EntityClass_Service.java.ejs b/generators/server/templates/entity/src/main/java/package/service/_EntityClass_Service.java.ejs index f0e6dead8cba..3354bc313dfe 100644 --- a/generators/server/templates/entity/src/main/java/package/service/_EntityClass_Service.java.ejs +++ b/generators/server/templates/entity/src/main/java/package/service/_EntityClass_Service.java.ejs @@ -54,6 +54,9 @@ import java.util.Optional; <%_ if (primaryKey.typeUUID) { _%> import java.util.UUID; <%_ } _%> +<%_ if (primaryKey.composite) { _%> +import <%=packageName%>.domain.<%=primaryKey.type%>; +<%_ } _%> /** * Service Interface for managing {@link <% if (dtoMapstruct) { %><%= entityAbsolutePackage %>.domain.<% } %><%= persistClass %>}. diff --git a/generators/server/templates/entity/src/main/java/package/service/criteria/_EntityClass_Criteria.java.ejs b/generators/server/templates/entity/src/main/java/package/service/criteria/_EntityClass_Criteria.java.ejs index 274c2beea519..5c782690f26f 100644 --- a/generators/server/templates/entity/src/main/java/package/service/criteria/_EntityClass_Criteria.java.ejs +++ b/generators/server/templates/entity/src/main/java/package/service/criteria/_EntityClass_Criteria.java.ejs @@ -31,8 +31,8 @@ fields.filter(field => !field.transient).forEach((field) => { fieldInJavaBeanMethod: field.fieldInJavaBeanMethod }); } }); -effectiveRelationships.forEach((relationship) => { -const relationshipType = relationship.otherEntity.primaryKey.type; +effectiveRelationships.forEach((relationship) => { relationship.otherEntity.primaryKey.fields.forEach(field => { +const relationshipType = field.fieldType; const referenceFilterType = '' + relationshipType + 'Filter'; // user has a String PK when using OAuth, so change relationships accordingly let oauthAwareReferenceFilterType = referenceFilterType; @@ -40,10 +40,10 @@ if (relationship.otherEntityUser && authenticationTypeOauth2) { oauthAwareReferenceFilterType = 'StringFilter'; } filterVariables.push({ filterType : oauthAwareReferenceFilterType, - name: relationship.relationshipFieldName + 'Id', + name: relationship.relationshipFieldName + field.fieldNameCapitalized, type: relationshipType, - fieldInJavaBeanMethod: relationship.relationshipNameCapitalized + 'Id' }); -}); + fieldInJavaBeanMethod: relationship.relationshipNameCapitalized + field.fieldNameCapitalized }); +})}); _%> /** * Criteria class for the {@link <%= entityAbsolutePackage %>.domain.<%= persistClass %>} entity. This class is used diff --git a/generators/server/templates/entity/src/main/java/package/service/dto/_DtoClass_.java.ejs b/generators/server/templates/entity/src/main/java/package/service/dto/_DtoClass_.java.ejs index 5732a7e384a0..97d931ad4165 100644 --- a/generators/server/templates/entity/src/main/java/package/service/dto/_DtoClass_.java.ejs +++ b/generators/server/templates/entity/src/main/java/package/service/dto/_DtoClass_.java.ejs @@ -141,7 +141,7 @@ _%> <%_ } _%> <%_ } _%> -<%_ const idNames = primaryKey ? [...primaryKey.fields.map(f => f.fieldName)] : [] _%> +<%_ const idNames = primaryKey ? (primaryKey.composite ? Array.from(new Set(primaryKey.fields.map(f => f.path[0]))) : [primaryKey.name]) : [] _%> @Override public boolean equals(Object o) { if (this == o) { diff --git a/generators/server/templates/entity/src/main/java/package/service/impl/_EntityClass_ServiceImpl.java.ejs b/generators/server/templates/entity/src/main/java/package/service/impl/_EntityClass_ServiceImpl.java.ejs index 7b7434af7e4b..05a80ab0ce45 100644 --- a/generators/server/templates/entity/src/main/java/package/service/impl/_EntityClass_ServiceImpl.java.ejs +++ b/generators/server/templates/entity/src/main/java/package/service/impl/_EntityClass_ServiceImpl.java.ejs @@ -47,6 +47,9 @@ import <%= entityAbsolutePackage %>.repository.<%= mapsIdAssoc.otherEntityNameCa <%_ if (searchEngineElasticsearch) { _%> import <%= entityAbsolutePackage %>.repository.search.<%= entityClass %>SearchRepository; <%_ } _%> +<%_ if (primaryKey.composite) { _%> +import <%=packageName%>.domain.<%=primaryKey.type%>; +<%_ } _%> <%_ if (dtoMapstruct) { _%> import <%= entityAbsolutePackage %>.service.dto.<%= dtoClass %>; import <%= entityAbsolutePackage %>.service.mapper.<%= entityClass %>Mapper; diff --git a/generators/server/templates/entity/src/main/java/package/service/mapper/_EntityClass_Mapper.java.ejs b/generators/server/templates/entity/src/main/java/package/service/mapper/_EntityClass_Mapper.java.ejs index af655a936447..3446250c5cb4 100644 --- a/generators/server/templates/entity/src/main/java/package/service/mapper/_EntityClass_Mapper.java.ejs +++ b/generators/server/templates/entity/src/main/java/package/service/mapper/_EntityClass_Mapper.java.ejs @@ -19,7 +19,7 @@ package <%= entityAbsolutePackage %>.service.mapper; <%_ - const getOriginalField = field => field.originalField || field; + const getOriginalField = field => field?.originalField || field; const uuidMapMethod = dtoReferences.some(reference => reference.valueReference && reference.valueReference.field && reference.valueReference.field.fieldTypeUUID); const byteMapMethod = dtoReferences.some(reference => reference.valueReference && reference.valueReference.field && reference.valueReference.field.fieldTypeBytes); const dtoRelationships = dtoReferences.filter(reference => reference.relationship && !reference.relationship.otherEntity.embedded).map(reference => reference.relationship); @@ -27,7 +27,7 @@ package <%= entityAbsolutePackage %>.service.mapper; .filter(otherEntity => dtoRelationships.some(relationship => relationship.otherEntity === otherEntity)) .map(otherEntity => dtoRelationships - .filter(relationship => relationship.otherEntity == otherEntity) + .filter(relationship => relationship.otherEntity === otherEntity) .map(({relatedField, collection}) => ({otherEntity, relatedField, collection})) ) .flat(); @@ -67,7 +67,7 @@ public interface <%= entityClass %>Mapper extends EntityMapper<<%= dtoClass %>, <%_ for (relationship of dtoRelationships) { _%> <%_ renMapAnotEnt = true; - let qualifiedByName = relationship.otherEntity.entityInstance + this._.upperFirst(relationship.otherEntityField); + let qualifiedByName = relationship.otherEntity.entityInstance + this._.upperFirst(relationship.relatedField ? relationship.relatedField.propertyName : 'Id'); qualifiedByName = qualifiedByName + (relationship.collection ? 'Set' : ''); _%> @Mapping(target = "<%= relationship.propertyName %>", source = "<%= relationship.propertyName %>", qualifiedByName="<%= qualifiedByName %>") @@ -81,10 +81,16 @@ public interface <%= entityClass %>Mapper extends EntityMapper<<%= dtoClass %>, <%_ } _%> <%_ var renMapAnotDto = false; //Render Mapping Annotation during DTO to Entity conversion? _%> - <%_ if(primaryKey.ids.length > 1) { _%> + <%_ if(primaryKey.fields.length > 1) { _%> <%_ renMapAnotDto = true; _%> - <%_ for (const id of primaryKey.ids) { _%> - @Mapping(target = "id.<%= id.name %>", source = "<%= id.nameDotted %>") + <%_ for (const field of primaryKey.fields) { _%> + @Mapping(target = "id.<%= field.fieldName %>", source = "<%= field.fieldNameDotted %>") + <%_ } _%> + <%# I wouldn't expect to be needed the way @EmbeddedId works with "insertable = false, updatable = false" but it seems like it is so putting it here, this might not work for bigger depth, but for now I think its enough %> + <%_ for (const relationship of relationships.filter(r => r.id && !primaryKey.derived && r.otherEntity.primaryKey.fields.length > 1)) { _%> + <%_ for (const field of relationship.otherEntity.primaryKey.fields) { _%> + @Mapping(target = "<%= relationship.relationshipName %>.id.<%= field.fieldName %>", source = "<%= relationship.relationshipName %>.<%= field.fieldNameDotted %>") + <%_ } _%> <%_ } _%> <%_ } _%> <%_ for (relationship of dtoRelationships) { _%> @@ -101,21 +107,33 @@ public interface <%= entityClass %>Mapper extends EntityMapper<<%= dtoClass %>, <%= persistClass %> toEntity(<%= dtoClass %> <%= dtoInstance %>); <%_ } _%> <%_ for (const {otherEntity, relatedField, collection} of otherEntitiesFields) { _%> - <%_ const mapperName = otherEntity.entityInstance + this._.upperFirst(relatedField.propertyName); _%> + <%_ const mapperName = otherEntity.entityInstance + this._.upperFirst(relatedField ? relatedField.propertyName : 'Id'); _%> @Named("<%= mapperName %>") @BeanMapping(ignoreByDefault = true) - <%_ for (const field of otherEntity.primaryKey.fields) { _%> + <%_ if (otherEntity.primaryKey.composite) { _%> + <%_ for (const field of otherEntity.primaryKey.fields) { _%> + @Mapping(target = "<%= field.fieldNameDotted %>", source = "id.<%= field.fieldName %>") + <%_ if (field.relationshipsPath[0] && field.relationshipsPath.at(-1).relatedField) { + const relatedFieldNameDotted = `${field.relationshipsPath.map(r => r.relationshipName).join(".")}.${field.relationshipsPath.at(-1).relatedField.fieldName}` + if (relatedFieldNameDotted !== field.fieldNameDotted) { _%> + @Mapping(target = "<%= relatedFieldNameDotted %>", source = "<%= relatedFieldNameDotted %>") + <%_ } _%> + <%_ } _%> + <%_ } _%> + <%_ } else { _%> + <%_ for (const field of otherEntity.primaryKey.fields) { _%> @Mapping(target = "<%= field.propertyName %>", source = "<%= field.propertyName %>") + <%_ } _%> <%_ } _%> - <%_ if (!relatedField.id) { _%> + <%_ if (relatedField && !relatedField.id) { _%> <%_ if (relatedField.mapstructExpression) { _%> @Mapping(target = "<%= relatedField.propertyName %>", expression = "<%- relatedField.mapstructExpression %>") <%_ } else { _%> @Mapping(target = "<%= relatedField.propertyName %>", source = "<%= relatedField.propertyName %>") <%_ } _%> <%_ } _%> - <%_ if (relatedField.mapstructExpression) { _%> + <%_ if (relatedField && relatedField.mapstructExpression) { _%> <%- otherEntity.dtoClass %> toDto<%= this._.upperFirst(mapperName) %>(<%- otherEntity.persistClass %> s); <%_ } else { _%> <%- otherEntity.dtoClass %> toDto<%= this._.upperFirst(mapperName) %>(<%- otherEntity.persistClass %> <%= otherEntity.persistInstance %>); diff --git a/generators/server/templates/entity/src/main/java/package/web/rest/_EntityClass_Resource.java.ejs b/generators/server/templates/entity/src/main/java/package/web/rest/_EntityClass_Resource.java.ejs index 9166fde97c79..099dfa0f5ec3 100644 --- a/generators/server/templates/entity/src/main/java/package/web/rest/_EntityClass_Resource.java.ejs +++ b/generators/server/templates/entity/src/main/java/package/web/rest/_EntityClass_Resource.java.ejs @@ -24,6 +24,11 @@ _%> <%_ if (!dtoMapstruct || serviceNo) { _%> import <%= entityAbsolutePackage %>.domain.<%= persistClass %>; <%_ } _%> +<%_ if (primaryKey.fields.length > 1) { _%> +import <%=packageName%>.domain.<%=primaryKey.type%>; +import java.util.Map; +import com.fasterxml.jackson.databind.ObjectMapper; +<%_ } _%> import <%= entityAbsolutePackage %>.repository.<%= entityClass %>Repository; <%_ if (!serviceNo) { _%> import <%= entityAbsolutePackage %>.service.<%= entityClass %>Service; @@ -44,7 +49,7 @@ import <%= packageName %>.web.rest.errors.ElasticsearchExceptionMapper; <%_ } _%> <%_ if (dtoMapstruct) { _%> import <%= entityAbsolutePackage %>.service.dto.<%= dtoClass %>; - <%_ if (serviceNo) { _%> + <%_ if (serviceNo || primaryKey.composite) { _%> import <%= entityAbsolutePackage %>.service.mapper.<%= entityClass %>Mapper; <%_ } _%> <%_ } _%> @@ -141,6 +146,10 @@ import static org.springframework.data.elasticsearch.client.elc.QueryBuilders.*; public class <%= entityClass %>Resource { private final Logger log = LoggerFactory.getLogger(<%= entityClass %>Resource.class); + +<%_ if(primaryKey.fields.length > 1) { _%> + private final ObjectMapper mapper = new ObjectMapper(); +<%_ } _%> <%_ if (!readOnly) { _%> <%_ let entityName = entityInstance; @@ -155,6 +164,7 @@ public class <%= entityClass %>Resource { <%_ const instanceType = restClass; const instanceName = restInstance; + const apiUrlPath = (key) => primaryKey.fields.length === 1 ? `${key}.get${primaryKey.nameCapitalized}()` : primaryKey.fields.map(f => `"${f.fieldName}=" + ${key}.${f.path.map(n => `get${this._.upperFirst(n)}()`).join('.')}`).join(' + ";" + '); const mapper = entityInstance + 'Mapper'; const entityToDtoReference = mapper + '::' + 'toDto'; _%><%- include('../../common/inject_template', {viaService: viaService, constructorName: entityClass + 'Resource', queryService: jpaMetamodelFiltering, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: true, reactive: reactive}); -%> @@ -170,9 +180,27 @@ public class <%= entityClass %>Resource { @PostMapping("/<%= entityApiUrl %>") public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> create<%= entityClass %>(<% if (anyPropertyHasValidation) { %>@Valid <% } %>@RequestBody <%= instanceType %> <%= instanceName %>) throws URISyntaxException { log.debug("REST request to save <%= entityClass %> : {}", <%= instanceName %>); + <%_ if (primaryKey.fields.length === 1 && primaryKey.autoGenerate) { _%> if (<%= instanceName %>.get<%= primaryKey.nameCapitalized %>() != null) { throw new BadRequestAlertException("A new <%= entityInstance %> cannot already have an ID", ENTITY_NAME, "idexists"); } + <%_ } _%> +<%_ // TODO handle these cases when reactive (using switchIfEmpty flatMap... +if (!reactive) { _%> + <%_ if(primaryKey.fields.length === 1 && !primaryKey.autoGenerate) { _%> + if (<%= entityInstance %>Repository.existsById(<%= instanceName %>.get<%= primaryKey.nameCapitalized %>())) { + throw new BadRequestAlertException("This <%= entityInstance %> already exists", ENTITY_NAME, "idduplicate"); + } + <%_ } else if (primaryKey.composite) { _%> + <%= primaryKey.type %> id = <%= entityInstance %>Mapper.toEntity(<%= instanceName %>).getId(); + if (id == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + if (<%= entityInstance %>Service.findOne(id).isPresent()) { + throw new BadRequestAlertException("This <%= entityInstance %> already exists", ENTITY_NAME, "idduplicate"); + } + <%_ } _%> +<%_ } _%> <%_ if (saveUserSnapshot) { _%> <% for (const userRelationship of relationships.filter(rel => rel.otherEntity.builtInUser)) { %> <%_ if (userRelationship.collection) { _%> @@ -197,16 +225,16 @@ public class <%= entityClass %>Resource { <%_ if (reactive) { _%> .map(result -> { try { - return ResponseEntity.created(new URI("/api/<%= entityApiUrl %>/" + result.get<%= primaryKey.nameCapitalized %>())) - .headers(HeaderUtil.createEntityCreationAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>)) + return ResponseEntity.created(new URI("/api/<%= entityApiUrl %>/" + <%- apiUrlPath('result') %>)) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%- apiUrlPath('result') %><% if (!primaryKey.typeString) { %>.toString()<% } %>)) .body(result); } catch (URISyntaxException e) { throw new RuntimeException(e); } }); <%_ } else { _%> - return ResponseEntity.created(new URI("/api/<%= entityApiUrl %>/" + result.get<%= primaryKey.nameCapitalized %>())) - .headers(HeaderUtil.createEntityCreationAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>)) + return ResponseEntity.created(new URI("/api/<%= entityApiUrl %>/" + <%- apiUrlPath('result') %>)) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%- apiUrlPath('result') %><% if (!primaryKey.typeString) { %>.toString()<% } %>)) .body(result); <%_ } _%> } @@ -214,7 +242,11 @@ public class <%= entityClass %>Resource { /** * {@code PUT /<%= entityApiUrl %>/:<%= primaryKey.name %>} : Updates an existing <%= entityInstance %>. * +<%_ if(primaryKey.fields.length === 1) { _%> * @param <%= primaryKey.name %> the id of the <%= instanceName %> to save. +<%_ } else { _%> + * @param idMap a Map representation of the id of the <%= instanceName %> to save. +<%_ } _%> * @param <%= instanceName %> the <%= instanceName %> to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated <%= instanceName %>, * or with status {@code 400 (Bad Request)} if the <%= instanceName %> is not valid, @@ -223,14 +255,27 @@ public class <%= entityClass %>Resource { */ @PutMapping("/<%= entityApiUrl %>/{<%= primaryKey.name %>}") public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> update<%= entityClass %>( +<%_ if (primaryKey.fields.length === 1) { _%> @PathVariable(value = "<%= primaryKey.name %>", required = false) final <%= primaryKey.type %> <%= primaryKey.name %>, +<%_ } else { _%> + @MatrixVariable(pathVar = "id") Map idMap, +<%_ } _%> <% if (anyPropertyHasValidation) { %>@Valid <% } %>@RequestBody <%= instanceType %> <%= instanceName %> ) throws URISyntaxException { +<%_ if(primaryKey.fields.length > 1) { _%> + final <%= primaryKey.type %> id = mapper.convertValue(idMap, <%= primaryKey.type %>.class); +<%_ } _%> log.debug("REST request to update <%= entityClass %> : {}, {}", <%= primaryKey.name %>, <%= instanceName %>); +<%_ if(primaryKey.fields.length === 1) { _%> if (<%= instanceName %>.get<%= primaryKey.nameCapitalized %>() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } +<%_ } _%> +<%_ if(primaryKey.fields.length === 1) { _%> if (!Objects.equals(<%= primaryKey.name %>, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>())) { +<%_ } else {_%> + if (!Objects.equals(id, <%= entityInstance %>Mapper.toEntity(<%= instanceName %>).getId())) { +<%_ } _%> throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } @@ -264,13 +309,13 @@ public class <%= entityClass %>Resource { <%_ if (reactive) { _%> .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))) .map(result -> ResponseEntity.ok() - .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>)) + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%- apiUrlPath('result') %><% if (!primaryKey.typeString) { %>.toString()<% } %>)) .body(result) ); }); <%_ } else { _%> return ResponseEntity.ok() - .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (!primaryKey.typeString) { %>.toString()<% } %>)) + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%- apiUrlPath(instanceName) %><% if (!primaryKey.typeString) { %>.toString()<% } %>)) .body(result); <%_ } _%> } @@ -279,7 +324,11 @@ public class <%= entityClass %>Resource { /** * {@code PATCH /<%= entityApiUrl %>/:<%= primaryKey.name %>} : Partial updates given fields of an existing <%= entityInstance %>, field will ignore if it is null * +<%_ if(primaryKey.fields.length === 1) { _%> * @param <%= primaryKey.name %> the id of the <%= instanceName %> to save. +<%_ } else { _%> + * @param idMap a Map representation of the id of the <%= instanceName %> to save. +<%_ } _%> * @param <%= instanceName %> the <%= instanceName %> to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated <%= instanceName %>, * or with status {@code 400 (Bad Request)} if the <%= instanceName %> is not valid, @@ -289,13 +338,26 @@ public class <%= entityClass %>Resource { */ @PatchMapping(value = "/<%= entityApiUrl %>/{<%= primaryKey.name %>}", consumes = {"application/json", "application/merge-patch+json"}) public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> partialUpdate<%= entityClass %>( - @PathVariable(value = "<%= primaryKey.name %>", required = false) final <%= primaryKey.type %> <%= primaryKey.name %>, +<%_ if (primaryKey.fields.length === 1) { _%> + @PathVariable(value = "<%= primaryKey.name %>", required = false) final <%= primaryKey.type %> <%= primaryKey.name %>, +<%_ } else { _%> + @MatrixVariable(pathVar = "id") Map idMap, +<%_ } _%> <% if (anyPropertyHasValidation) { %>@NotNull <% } %>@RequestBody <%= instanceType %> <%= instanceName %>) throws URISyntaxException { +<%_ if (primaryKey.fields.length > 1) { _%> + final <%= primaryKey.type %> id = mapper.convertValue(idMap, <%= primaryKey.type %>.class); +<%_ } _%> log.debug("REST request to partial update <%= entityClass %> partially : {}, {}", <%= primaryKey.name %>, <%= instanceName %>); +<%_ if(primaryKey.fields.length === 1) { _%> if (<%= instanceName %>.get<%= primaryKey.nameCapitalized %>() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } +<%_ } _%> +<%_ if(primaryKey.fields.length === 1) { _%> if (!Objects.equals(<%= primaryKey.name %>, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>())) { +<%_ } else {_%> + if (!Objects.equals(id, <%= entityInstance %>Mapper.toEntity(<%= instanceName %>).getId())) { +<%_ } _%> throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } @@ -331,14 +393,14 @@ public class <%= entityClass %>Resource { return result .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))) .map(res -> ResponseEntity.ok() - .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, res.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)) + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%- apiUrlPath('res') %><% if (!primaryKey.typeString) { %>.toString()<% } %>)) .body(res) ); }); <%_ } else { _%> return ResponseUtil.wrapOrNotFound( result, - HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>) + HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%- apiUrlPath(instanceName) %><% if (!primaryKey.typeString) { %>.toString()<% } %>) ); <%_ } _%> } @@ -395,14 +457,21 @@ public class <%= entityClass %>Resource { /** * {@code GET /<%= entityApiUrl %>/:id} : get the "id" <%= entityInstance %>. * +<%_ if(primaryKey.fields.length === 1) { _%> * @param id the id of the <%= instanceName %> to retrieve. +<%_ } else { _%> + * @param idMap a Map representation of the id of the <%= instanceName %> to retrieve. +<%_ } _%> * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the <%= instanceName %>, or with status {@code 404 (Not Found)}. */ @GetMapping("/<%= entityApiUrl %>/{id}") <%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%> @Transactional(readOnly = true) <%_ } _%> - public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> get<%= entityClass %>(@PathVariable <%= primaryKey.type %> id) { + public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> get<%= entityClass %>(<% if (primaryKey.fields.length === 1) { %>@PathVariable <%= primaryKey.type %> id<% } else { %>@MatrixVariable(pathVar = "id") Map idMap<% } %>) { +<%_ if (primaryKey.fields.length > 1) { _%> + final <%= primaryKey.type %> id = mapper.convertValue(idMap, <%= primaryKey.type %>.class); +<%_ } _%> log.debug("REST request to get <%= entityClass %> : {}", id);<%- include('../../common/get_template', {viaService, returnDirectly:false, implementsEagerLoadApis}); -%> return ResponseUtil.wrapOrNotFound(<%= instanceName %>); } @@ -411,11 +480,18 @@ public class <%= entityClass %>Resource { /** * {@code DELETE /<%= entityApiUrl %>/:id} : delete the "id" <%= entityInstance %>. * +<%_ if(primaryKey.fields.length === 1) { _%> * @param id the id of the <%= instanceName %> to delete. +<%_ } else { _%> + * @param idMap a Map representation of the id of the <%= instanceName %> to delete. +<%_ } _%> * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/<%= entityApiUrl %>/{id}") - public <% if (reactive) { %>Mono<<% } %>ResponseEntity<% if (reactive) { %>><% } %> delete<%= entityClass %>(@PathVariable <%= primaryKey.type %> id) { + public <% if (reactive) { %>Mono<<% } %>ResponseEntity<% if (reactive) { %>><% } %> delete<%= entityClass %>(<% if (primaryKey.fields.length === 1) { %>@PathVariable <%= primaryKey.type %> id<% } else { %>@MatrixVariable(pathVar = "id") Map idMap<% } %>) { +<%_ if (primaryKey.fields.length > 1) { _%> + final <%= primaryKey.type %> id = mapper.convertValue(idMap, <%= primaryKey.type %>.class); +<%_ } _%> log.debug("REST request to delete <%= entityClass %> : {}", id); <%- include('../../common/delete_template', {viaService: viaService, fromResource: true}); -%> <%_ if (reactive) { _%> @@ -429,7 +505,7 @@ public class <%= entityClass %>Resource { ); <%_ } _%> <%_ } else { _%> - return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (!primaryKey.fields[0].fieldTypeString) { %>.toString()<% } %>)).build(); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)).build(); <%_ } _%> } <%_ } _%> diff --git a/generators/server/templates/entity/src/test/java/package/domain/_PersistClass_Test.java.ejs b/generators/server/templates/entity/src/test/java/package/domain/_PersistClass_Test.java.ejs index 116711331555..aefdab5c74c4 100644 --- a/generators/server/templates/entity/src/test/java/package/domain/_PersistClass_Test.java.ejs +++ b/generators/server/templates/entity/src/test/java/package/domain/_PersistClass_Test.java.ejs @@ -27,16 +27,25 @@ import java.util.UUID; class <%= persistClass %>Test { +<%_ +function computeValue(entityNbr = 1) { + if (primaryKey.composite) { + return `new ${primaryKey.type}(${primaryKey.fields.map(field => this.getPrimaryKeyValue(field.fieldType, databaseType, entityNbr)).join(', ')})`; + } else { + return this.getPrimaryKeyValue(primaryKey.fields[0].fieldType, databaseType, entityNbr) + } +} +_%> @Test void equalsVerifier() throws Exception { TestUtil.equalsVerifier(<%= persistClass %>.class); <%_if (!embedded) { _%> <%= persistClass %> <%= persistInstance %>1 = new <%= persistClass %>(); - <%= persistInstance %>1.set<%= primaryKey.nameCapitalized %>(<% if (primaryKey.typeLong) { %>1L<% } else if (primaryKey.typeString) { %>"id1"<% } else if (primaryKey.typeUUID) { %>UUID.randomUUID()<% } %>); + <%= persistInstance %>1.set<%= primaryKey.nameCapitalized %>(<%- computeValue.bind(this)(1) %>); <%= persistClass %> <%= persistInstance %>2 = new <%= persistClass %>(); <%= persistInstance %>2.set<%= primaryKey.nameCapitalized %>(<%= persistInstance %>1.get<%= primaryKey.nameCapitalized %>()); assertThat(<%= persistInstance %>1).isEqualTo(<%= persistInstance %>2); - <%= persistInstance %>2.set<%= primaryKey.nameCapitalized %>(<% if (primaryKey.typeLong) { %>2L<% } else if (primaryKey.typeString) { %>"id2"<% } else if (primaryKey.typeUUID) { %>UUID.randomUUID()<% } %>); + <%= persistInstance %>2.set<%= primaryKey.nameCapitalized %>(<%- computeValue.bind(this)(2) %>); assertThat(<%= persistInstance %>1).isNotEqualTo(<%= persistInstance %>2); <%= persistInstance %>1.set<%= primaryKey.nameCapitalized %>(null); assertThat(<%= persistInstance %>1).isNotEqualTo(<%= persistInstance %>2); diff --git a/generators/server/templates/entity/src/test/java/package/service/dto/_DtoClass_Test.java.ejs b/generators/server/templates/entity/src/test/java/package/service/dto/_DtoClass_Test.java.ejs index 731f0455f292..90484a798c2b 100644 --- a/generators/server/templates/entity/src/test/java/package/service/dto/_DtoClass_Test.java.ejs +++ b/generators/server/templates/entity/src/test/java/package/service/dto/_DtoClass_Test.java.ejs @@ -21,33 +21,49 @@ package <%= entityAbsolutePackage %>.service.dto; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import <%= packageName %>.web.rest.TestUtil; -<%_ -let id1; -let id2; -if (!embedded) { - id1 = this.getPrimaryKeyValue(primaryKey.type, databaseType, '1'); - id2 = this.getPrimaryKeyValue(primaryKey.type, databaseType, '2'); -} %> <%_ if (primaryKey && primaryKey.hasUUID) { _%> import java.util.UUID; <%_ } _%> +<%_ +const initDTO = (dtoEntity, entityNbr) => { +_%> + <%= dtoEntity.dtoClass %> <%= dtoEntity.dtoInstance %><%= entityNbr %> = new <%= dtoEntity.dtoClass %>(); + <%_ dtoEntity.fields.filter(f => f.id).forEach(f => { _%> + <%= dtoEntity.dtoInstance + entityNbr %>.set<%= f.fieldNameCapitalized %>(<%- this.getPrimaryKeyValue(f.fieldType, databaseType, entityNbr) %>); + <%_ }) _%> + <%_ dtoEntity.relationships.filter(r => r.id && !(r.relationshipType === 'one-to-one' && !dtoEntity.primaryKey.composite)).forEach(r => { _%> + <%- initDTO(r.otherEntity, entityNbr); _%> + <%= dtoEntity.dtoInstance + entityNbr %>.set<%= r.relationshipNameCapitalized %>(<%= r.otherEntity.dtoInstance + entityNbr %>); + <%_ }) +} +_%> class <%= dtoClass %>Test { @Test void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(<%= dtoClass %>.class); -<%_if (!embedded) { _%> - <%= dtoClass %> <%= dtoInstance %>1 = new <%= dtoClass %>(); - <%= dtoInstance %>1.set<%= primaryKey.nameCapitalized %>(<%- id1 %>); + <%_ if (!embedded) { _%> + <%- initDTO(entity, 1); _%> <%= dtoClass %> <%= dtoInstance %>2 = new <%= dtoClass %>(); assertThat(<%= dtoInstance %>1).isNotEqualTo(<%= dtoInstance %>2); - <%= dtoInstance %>2.set<%= primaryKey.nameCapitalized %>(<%= dtoInstance %>1.get<%= primaryKey.nameCapitalized %>()); +<%_ fields.filter(f => f.id).forEach(f => { _%> + <%= dtoInstance %>2.set<%= f.fieldNameCapitalized %>(<%= dtoInstance %>1.get<%= f.fieldNameCapitalized %>()); +<%_ }) _%> +<%_ relationships.filter(r => r.id && !(r.relationshipType === 'one-to-one' && !primaryKey.composite)).forEach(r => { _%> + <%= dtoInstance %>2.set<%= r.relationshipNameCapitalized %>(<%= r.otherEntity.dtoInstance %>1); +<%_ }) _%> assertThat(<%= dtoInstance %>1).isEqualTo(<%= dtoInstance %>2); - <%= dtoInstance %>2.set<%= primaryKey.nameCapitalized %>(<%- id2 %>); - assertThat(<%= dtoInstance %>1).isNotEqualTo(<%= dtoInstance %>2); - <%= dtoInstance %>1.set<%= primaryKey.nameCapitalized %>(null); - assertThat(<%= dtoInstance %>1).isNotEqualTo(<%= dtoInstance %>2); -<%_ } _%> + <%- initDTO(entity, 3); _%> + assertThat(<%= dtoInstance %>1).isNotEqualTo(<%= dtoInstance %>3); + <%= dtoClass %> <%= dtoInstance %>4 = new <%= dtoClass %>(); +<%_ fields.filter(f => f.id).forEach(f => { _%> + <%= dtoInstance %>4.set<%= f.fieldNameCapitalized %>(null); +<%_ }) _%> +<%_ relationships.filter(r => r.id && !(r.relationshipType === 'one-to-one' && !primaryKey.composite)).forEach(r => { _%> + <%= dtoInstance %>4.set<%= r.relationshipNameCapitalized %>(null); +<%_ }) _%> + assertThat(<%= dtoInstance %>1).isNotEqualTo(<%= dtoInstance %>4); + <%_ } _%> } } diff --git a/generators/server/templates/entity/src/test/java/package/web/rest/_EntityClass_ResourceIT.java.ejs b/generators/server/templates/entity/src/test/java/package/web/rest/_EntityClass_ResourceIT.java.ejs index c10af368ca5e..e6d7fc34d401 100644 --- a/generators/server/templates/entity/src/test/java/package/web/rest/_EntityClass_ResourceIT.java.ejs +++ b/generators/server/templates/entity/src/test/java/package/web/rest/_EntityClass_ResourceIT.java.ejs @@ -20,7 +20,7 @@ package <%= entityAbsolutePackage %>.web.rest; <%_ var filterTestableRelationships = reactive ? reactiveEagerRelations : relationships; -const fieldsToTest = fields.filter(field => !field.id && !field.autoGenerate && !field.transient); +const fieldsToTest = fields.filter(field => !field.autoGenerate && !field.transient); let mapsIdEntity; let mapsIdEntityInstance; let mapsIdRepoInstance; @@ -56,13 +56,24 @@ let transactionalAnnotation = ''; if (databaseTypeSql && !reactive) { transactionalAnnotation = '\n @Transactional'; } - +const persistInstanceUrlId = primaryKey.fields.length === 1 ? + `${persistInstance}.get${primaryKey.nameCapitalized}()` : + primaryKey.fields.map(field => `"${field.fieldName}=" + ${persistInstance}.getId().get${field.fieldNameCapitalized}()`).join(' + ";" + '); +let generatedUrlId; +if(primaryKey.fields.length === 1) { + generatedUrlId = this.getJavaValueGeneratorForType(primaryKey.type); +} else { + generatedUrlId = primaryKey.fields.map(field => `"${field.fieldName}=" + ${this.getJavaValueGeneratorForType(field.fieldType)}`).join(' + ";" + ') +} _%> <%_ if (entityAbsolutePackage !== packageName) { _%> import <%= packageName %>.web.rest.TestUtil; <% } %> import <%= packageName %>.IntegrationTest; import <%= entityAbsolutePackage %>.domain.<%= persistClass %>; +<%_ if (primaryKey.composite) { _%> +import <%= entityAbsolutePackage %>.domain.<%= primaryKey.type %>; +<%_ } _%> <%_ var imported = []; for (relationship of relationships) { // import entities in required relationships @@ -197,7 +208,7 @@ import java.util.stream.Stream; <%_ } _%> <%_ } _%> import java.util.List; -<%_ if (anyFieldIsUUID || primaryKey.typeString || otherEntityPrimaryKeyTypesIncludesUUID) { _%> +<%_ if (anyFieldIsUUID || primaryKey.typeString || primaryKey.fields.map(f => f.fieldType).some(t => ['String', 'UUID'].includes(t)) || otherEntityPrimaryKeyTypesIncludesUUID) { _%> import java.util.UUID; <%_ } _%> <%_ if (!embedded && primaryKey.hasLong) { _%> @@ -565,6 +576,11 @@ filterTestableRelationships.forEach((relationship) => { _%> <%_ } _%> <%_ alreadyGeneratedEntities.push(otherEntityName) _%> <%_ } _%> + <%_ } _%> + <%_ if (primaryKey.composite) { _%> + <%= persistInstance %>.setId(new <%= primaryKey.type %>( + <%- primaryKey.fields.map(field => [persistInstance, ...field.path.map(p => `get${this._.upperFirst(p)}()`)].join('.')).join(',') %> + )); <%_ } _%> return <%= persistInstance %>; } @@ -682,14 +698,14 @@ _%> <%_ if (isUsingMapsId) { _%> // Validate the id for MapsId, the ids must be same - assertThat(test<%= entityClass %>.get<%= primaryKey.nameCapitalized %>()).isEqualTo(<%_ if (dtoMapstruct) { _%><%= dtoInstance %><%_ } else { _%>test<%= entityClass %><%_ } _%>.get<%= mapsIdEntity %>().get<%= primaryKey.nameCapitalized %>()); + assertThat(test<%= entityClass %>.get<%= primaryKey.nameCapitalized %>()).isEqualTo(test<%= entityClass %>.get<%= mapsIdEntity %>().get<%= mapsIdAssoc.otherEntity.primaryKey.nameCapitalized %>()); <%_ } _%> } @Test<%= transactionalAnnotation %> void create<%= entityClass %>WithExistingId() throws Exception { // Create the <%= entityClass %> with an existing ID - <%_ if (primaryKey.typeUUID && databaseTypeSql) { _%> + <%_ if ((primaryKey.typeUUID && databaseTypeSql) || primaryKey.composite || !primaryKey.autoGenerate) { _%> <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>; <%_ } else { _%> <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<% if (primaryKey.typeUUID) { %>UUID.randomUUID()<% } else if (primaryKey.typeLong) { %>1L<% } else { %>"existing_id"<% } %>); @@ -729,7 +745,9 @@ _%> <%_ } _%> } - <%_ if (databaseTypeSql && isUsingMapsId) { _%> + <%# this is not doable with composite keys, without drastically chaging the logic, since we would need to read the id from url, + set it in entity instead of validating it, then using the relationnships to update the DB, and it might not work since we usable insertable/updatable false %> + <%_ if (databaseTypeSql && isUsingMapsId && primaryKey.fields.length === 1) { _%> @Test<%= transactionalAnnotation %> void update<%= entityClass %>MapsIdAssociationWithNewId() throws Exception { // Initialize the database @@ -779,7 +797,7 @@ _%> .exchange() .expectStatus().isOk(); <%_ } else { _%> - rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%_ if (dtoMapstruct) { _%>updated<%= dtoClass %> <%_ } else { _%> updated<%= persistClass %> <%_ } _%>.get<%= primaryKey.nameCapitalized %>())<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%> + rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%- persistInstanceUrlId %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%> .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(<%_ if (dtoMapstruct) { _%>updated<%= dtoClass %> <%_ } else { _%> updated<%= persistClass %> <%_ } _%>))) .andExpect(status().isOk()); @@ -857,7 +875,7 @@ _%> @Test<%= transactionalAnnotation %> void getAll<%= entityClassPlural %>AsStream() { // Initialize the database - <%_ if (!primaryKey.derived) { _%> + <%_ if (primaryKey.autoGenerate) { _%> <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%> <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>); <%_ } _%> @@ -899,7 +917,7 @@ _%> @Test<%= transactionalAnnotation %> void getAll<%= entityClassPlural %>() <% if (!reactive) { %>throws Exception <% } %>{ // Initialize the database -<%_ if (!primaryKey.derived) { _%> +<%_ if (primaryKey.autoGenerate) { _%> <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%> <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>); <%_ } _%> @@ -919,7 +937,7 @@ _%> .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) <%_ } _%> -<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) { _%> +<%_ if ((databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) && !primaryKey.composite) { _%> <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= idValue %>))<%= !reactive ? ')' : '' %><%_ } _%><% for (field of fieldsToTest) { %> <%_ if (field.fieldTypeBinary && !field.blobContentTypeText) { _%> <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= field.fieldName %>ContentType").value(hasItem(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE))<%= !reactive ? ')' : '' %> @@ -986,7 +1004,7 @@ _%> @Test<%= transactionalAnnotation %> void get<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{ // Initialize the database -<%_ if (!primaryKey.derived) { _%> +<%_ if (primaryKey.autoGenerate) { _%> <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%> <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>); <%_ } _%> @@ -1002,11 +1020,11 @@ _%> .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody() <%_ } else { _%> - rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())) + rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL_ID, <%- persistInstanceUrlId %>)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) <%_ } _%> -<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) { _%> +<%_ if ((databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) && !primaryKey.composite) { _%> <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.<%= primaryKey.name %>").value(<%= reactive ? 'is(' : '' %><%= idValue %>))<%_ } _%><% for (field of fieldsToTest) { %> <%_ if (field.fieldTypeBinary && !field.blobContentTypeText) { _%> <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.<%= field.fieldName %>ContentType").value(<%= reactive ? 'is(' : '' %><%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE)) @@ -1026,6 +1044,7 @@ _%> if (!field.fieldTypeString) { %>.toString()<% } %>))<%_ } _%>; } <%_ if (jpaMetamodelFiltering) { %> + <%_ if (primaryKey.fields.length === 1) { _%> @Test<%= transactionalAnnotation %> void get<%= entityClassPlural %>ByIdFiltering() <% if (!reactive) { %>throws Exception <% } %>{ @@ -1037,14 +1056,15 @@ _%> default<%= entityClass %>ShouldBeFound("<%= primaryKey.name %>.equals=" + id); default<%= entityClass %>ShouldNotBeFound("<%= primaryKey.name %>.notEquals=" + id); - <%_ if (primaryKey.typeLong) { _%> + <%_ if (primaryKey.typeLong) { _%> default<%= entityClass %>ShouldBeFound("<%= primaryKey.name %>.greaterThanOrEqual=" + id); default<%= entityClass %>ShouldNotBeFound("<%= primaryKey.name %>.greaterThan=" + id); default<%= entityClass %>ShouldBeFound("<%= primaryKey.name %>.lessThanOrEqual=" + id); default<%= entityClass %>ShouldNotBeFound("<%= primaryKey.name %>.lessThan=" + id); - <%_ } _%> + <%_ } _%> } + <%_ } _%> <%_ fieldsToTest.forEach((searchBy) => { /* we can't filter by all the fields. */_%> <%_ if (searchBy.filterableField) { _%> @@ -1182,14 +1202,17 @@ _%> @Test<%= transactionalAnnotation %> void getAll<%= entityClassPlural %>By<%= relationship.relationshipNameCapitalized %>IsEqualToSomething() <% if (!reactive) { %>throws Exception <% } %>{ + <% const differentEntity = relationship.otherEntityNameCapitalized !== name; %> <%_ if ((relationship.relationshipValidate && relationship.relationshipOneToOne) || relationship.id) { _%> // Get already existing entity <%= relationship.otherEntity.persistClass %> <%= relationship.relationshipFieldName %> = <%= persistInstance %>.get<%= relationship.relationshipNameCapitalized %>(); <%_ } else { _%> + // Initialize the database <%_ if (databaseTypeSql && !reactive) { _%> + <%# we persist first in case there is a relationship wth same entity %> + em.persist(<%= persistInstance %>); <%= relationship.otherEntity.persistClass %> <%= relationship.relationshipFieldName %>; if (TestUtil.findAll(em, <%= relationship.otherEntity.persistClass %>.class).isEmpty()) { - <%= entityInstance %>Repository.saveAndFlush(<%= persistInstance %>); <%= relationship.relationshipFieldName %> = <%= createEntityPrefix %><%= relationship.otherEntityNameCapitalized %>ResourceIT.createEntity(em); } else { <%= relationship.relationshipFieldName %> = TestUtil.findAll(em, <%= relationship.otherEntity.persistClass %>.class).get(0); @@ -1201,7 +1224,6 @@ _%> <%= relationship.otherEntity.persistInstance %>Repository.<%= saveMethod %>(<%= relationship.relationshipFieldName %>)<%= callBlock %>; <%_ } else { _%> em.persist(<%= relationship.relationshipFieldName %>); - em.flush(); <%_ } _%> <%_ if (!reactive && (relationship.relationshipManyToMany || relationship.relationshipOneToMany)) { _%> <%= persistInstance %>.add<%= relationship.relationshipNameCapitalized %>(<%= relationship.relationshipFieldName %>); @@ -1216,22 +1238,31 @@ _%> <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>; <%_ } _%> <%_ } _%> + <%_ const field = relationship.otherEntity.primaryKey.fields[0]; + const filterName = `${relationship.relationshipName}${field.fieldNameCapitalized}`; + let filterValue = relationship.relationshipName; + if (relationship.otherEntity.primaryKey.composite) { + filterValue += `.getId()`; + } + filterValue += `.get${field.fieldNameCapitalized}()`; + const filterType = field.fieldType; + _%> <%_ if(!reactive) { _%> <%= entityInstance %>Repository.saveAndFlush(<%= persistInstance %>); - <%= relationship.otherEntity.primaryKey.type %> <%= relationship.relationshipFieldName %>Id = <%= relationship.relationshipFieldName %>.get<%= relationship.otherEntity.primaryKey.nameCapitalized %>(); <%_ } _%> - // Get all the <%= entityInstance %>List where <%= relationship.relationshipFieldName %> equals to <%= relationship.relationshipFieldName %>Id - default<%= entityClass %>ShouldBeFound("<%= relationship.relationshipFieldName %>Id.equals=" + <%= relationship.relationshipFieldName %>Id); - - <%_ - const initInvalidPrimaryKey = { - 'String' : '"invalid-id"', - 'Long' : '(' + relationship.relationshipFieldName + 'Id + 1)', - 'UUID' : 'UUID.randomUUID()' - }[relationship.otherEntity.primaryKey.type]; - _%> - // Get all the <%= entityInstance %>List where <%= relationship.relationshipFieldName %> equals to <%- initInvalidPrimaryKey %> - default<%= entityClass %>ShouldNotBeFound("<%= relationship.relationshipFieldName %>Id.equals=" + <%- initInvalidPrimaryKey %>); + // Get all the <%= entityInstance %>List where <%= filterName %> equals to <%= filterValue %> + default<%= entityClass %>ShouldBeFound("<%= filterName %>.equals=" + <%= filterValue %>); + + <%_ + const initInvalidPrimaryKey = { + 'String' : '"invalid-id"', + 'Long' : '(' + filterValue + ' + 1)', + 'Integer' : '(' + filterValue + ' + 1)', + 'UUID' : 'UUID.randomUUID()' + }[filterType]; + _%> + // Get all the <%= entityInstance %>List where <%= filterName %> equals to <%- initInvalidPrimaryKey %> + default<%= entityClass %>ShouldNotBeFound("<%= filterName %>.equals=" + <%- initInvalidPrimaryKey %>); } <%_ }); _%> @@ -1246,7 +1277,7 @@ _%> .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody() - .jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= idValue %>))<% for (field of fieldsToTest) { %> + <%_ if (!primaryKey.composite) { _%>.jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= idValue %>))<%_ } _%><% for (field of fieldsToTest) { %> <%_ if (field.fieldTypeBinary && !field.blobContentTypeText) { _%> .jsonPath("$.[*].<%= field.fieldName %>ContentType").value(hasItem(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE)) <%_ } _%> @@ -1288,7 +1319,7 @@ _%> 'UUID' : '.toString()' }[primaryKey.type] || ''; _%> - .andExpect(jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()<%= primaryKeyConversion %>)))<% fieldsToTest.forEach((field) => { %> + <%_ if (!primaryKey.composite) { _%>.andExpect(jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()<%= primaryKeyConversion %>)))<%_ } _%><% fieldsToTest.forEach((field) => { %> <%_ if (field.fieldTypeBinary && !field.blobContentTypeText) { _%> .andExpect(jsonPath("$.[*].<%= field.fieldName %>ContentType").value(hasItem(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE))) <%_ } _%> @@ -1363,12 +1394,12 @@ _%> void getNonExisting<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{ // Get the <%= entityInstance %> <%_ if (reactive) { _%> - webTestClient.get().uri(ENTITY_API_URL_ID, <% if (primaryKey.typeLong || primaryKey.typeString) { %>Long.MAX_VALUE<% } else if (primaryKey.typeUUID) { %>UUID.randomUUID().toString()<% } %>) + webTestClient.get().uri(ENTITY_API_URL_ID, <% if (primaryKey.typeLong || primaryKey.typeString) { %>Long.MAX_VALUE<% } else if (primaryKey.typeUUID) { %>UUID.randomUUID().toString()<% } else { %><%- persistInstanceUrlId %><% } %>) .accept(MediaType.APPLICATION_PROBLEM_JSON) .exchange() .expectStatus().isNotFound(); <%_ } else { _%> - rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL_ID, <% if (primaryKey.typeLong || primaryKey.typeString) { %>Long.MAX_VALUE<% } else if (primaryKey.typeUUID) { %>UUID.randomUUID().toString()<% } %>)) + rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL_ID, <% if (primaryKey.typeLong || primaryKey.typeString) { %>Long.MAX_VALUE<% } else if (primaryKey.typeUUID) { %>UUID.randomUUID().toString()<% } else { %><%- persistInstanceUrlId %><% } %>)) .andExpect(status().isNotFound()); <%_ } _%> } @@ -1377,7 +1408,7 @@ _%> @Test<%= transactionalAnnotation %> void putExisting<%= entityClass %>() throws Exception { // Initialize the database - <%_ if (!primaryKey.derived) { _%> + <%_ if (primaryKey.autoGenerate) { _%> <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%> <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>); <%_ } _%> @@ -1397,11 +1428,11 @@ _%> em.detach(updated<%= persistClass %>); <%_ } _%> <%_ if (fluentMethods && fieldsToTest.length > 0) { _%> - updated<%= persistClass %><% for (field of fieldsToTest) { %> + updated<%= persistClass %><% for (field of fieldsToTest.filter(f => !f.id)) { %> .<%= field.fieldName %>(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>)<% if (field.fieldTypeBinary && !field.blobContentTypeText) { %> .<%= field.fieldName %>ContentType(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE)<% } %><% } %>; <%_ } else { _%> - <%_ for (field of fieldsToTest) { _%> + <%_ for (field of fieldsToTest.filter(f => !f.id)) { _%> updated<%= persistClass %>.set<%= field.fieldInJavaBeanMethod %>(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>); <%_ if (field.fieldTypeBinary && !field.blobContentTypeText) { _%> updated<%= persistClass %>.set<%= field.fieldInJavaBeanMethod %>ContentType(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE); @@ -1419,7 +1450,7 @@ _%> .exchange() .expectStatus().isOk(); <%_ } else { _%> - rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%= (dtoMapstruct ? dtoInstance : 'updated' + persistClass) %>.get<%= primaryKey.nameCapitalized %>())<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %> + rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%- persistInstanceUrlId %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %> .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? dtoInstance : 'updated' + persistClass) %>))) .andExpect(status().isOk()); @@ -1434,14 +1465,14 @@ _%> <%= persistClass %> test<%= entityClass %> = <%= entityInstance %>List.get(<%= entityInstance %>List.size() - 1); <%_ for (const field of fieldsToTest) { _%> <%_ if (field.fieldTypeZonedDateTime) { _%> - assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>); + assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= (field.id ? 'DEFAULT_' : 'UPDATED_') + field.fieldNameUnderscored.toUpperCase() %>); <%_ } else if (field.fieldTypeBinary && !field.blobContentTypeText) { _%> - assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>); - assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE); + assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= (field.id ? 'DEFAULT_' : 'UPDATED_') + field.fieldNameUnderscored.toUpperCase() %>); + assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= (field.id ? 'DEFAULT_' : 'UPDATED_') + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE); <%_ } else if (field.fieldTypeBigDecimal) { _%> - assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualByComparingTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>); + assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualByComparingTo(<%= (field.id ? 'DEFAULT_' : 'UPDATED_') + field.fieldNameUnderscored.toUpperCase() %>); <%_ } else { _%> - assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>); + assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= (field.id ? 'DEFAULT_' : 'UPDATED_') + field.fieldNameUnderscored.toUpperCase() %>); <%_ } _%> <%_ } _%> <%_ if (searchEngineElasticsearch) { _%> @@ -1452,14 +1483,14 @@ _%> <%= persistClass %> test<%= entityClass %>Search = <%= entityInstance %>SearchList.get(searchDatabaseSizeAfter - 1); <%_ for (const field of fieldsToTest) { _%> <%_ if (field.fieldTypeZonedDateTime) { _%> - assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>); + assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= (field.id ? 'DEFAULT_' : 'UPDATED_') + field.fieldNameUnderscored.toUpperCase() %>); <%_ } else if (field.fieldTypeBinary && !field.blobContentTypeText) { _%> - assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>); - assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE); + assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= (field.id ? 'DEFAULT_' : 'UPDATED_') + field.fieldNameUnderscored.toUpperCase() %>); + assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= (field.id ? 'DEFAULT_' : 'UPDATED_') + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE); <%_ } else if (field.fieldTypeBigDecimal) { _%> - assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualByComparingTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>); + assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualByComparingTo(<%= (field.id ? 'DEFAULT_' : 'UPDATED_') + field.fieldNameUnderscored.toUpperCase() %>); <%_ } else { _%> - assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>); + assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= (field.id ? 'DEFAULT_' : 'UPDATED_') + field.fieldNameUnderscored.toUpperCase() %>); <%_ } _%> <%_ } _%> }); @@ -1472,7 +1503,7 @@ _%> <%_ if (searchEngineElasticsearch) { _%> int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>); <%_ } _%> - <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>); + <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForPrimaryKey(primaryKey) %>); <%_ if (dtoMapstruct) { _%> // Create the <%= entityClass %> @@ -1487,7 +1518,7 @@ _%> .exchange() .expectStatus().isBadRequest(); <%_ } else { _%> - rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%= restInstance %>.get<%= primaryKey.nameCapitalized %>())<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%> + rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%- persistInstanceUrlId %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %> .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) .andExpect(status().isBadRequest()); @@ -1512,7 +1543,7 @@ _%> <%_ if (searchEngineElasticsearch) { _%> int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>); <%_ } _%> - <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>); + <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForPrimaryKey(primaryKey) %>); <%_ if (dtoMapstruct) { _%> // Create the <%= entityClass %> @@ -1521,13 +1552,13 @@ _%> <%_ } _%> // If url ID doesn't match entity ID, it will throw BadRequestAlertException <%_ if (reactive) { _%> - webTestClient.put().uri(ENTITY_API_URL_ID, <%- this.getJavaValueGeneratorForType(primaryKey.type) %>) + webTestClient.put().uri(ENTITY_API_URL_ID, <%- generatedUrlId %>) .contentType(MediaType.APPLICATION_JSON) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)) .exchange() .expectStatus().isBadRequest(); <%_ } else { _%> - rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%- this.getJavaValueGeneratorForType(primaryKey.type) %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %> + rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%- generatedUrlId %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %> .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) .andExpect(status().isBadRequest()); @@ -1551,7 +1582,7 @@ _%> <%_ if (searchEngineElasticsearch) { _%> int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>); <%_ } _%> - <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>); + <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForPrimaryKey(primaryKey) %>); <%_ if (dtoMapstruct) { _%> // Create the <%= entityClass %> @@ -1596,29 +1627,29 @@ _%> @Test<%= transactionalAnnotation %> void partialUpdate<%= entityClass %>WithPatch() throws Exception { // Initialize the database - <%_ if (!primaryKey.derived) { _%> + <%_ if (primaryKey.autoGenerate) { _%> <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%> <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>); <%_ } _%> <%_ } _%> <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>; - <%_ const fieldsToIncludeInPartialPatchTest = fieldsToTest.map(field => prepareFieldForPatchTest(field, () => faker.datatype.boolean())); _%> -<%- include('/partials/it_patch_update.partial.java.ejs', {fields: fieldsToIncludeInPartialPatchTest, saveMethod, callBlock, callListBlock}); -%> + <%_ const fieldsToIncludeInPartialPatchTest = fieldsToTest.map(field => prepareFieldForPatchTest(field, () => field.id ? false : faker.datatype.boolean())); _%> +<%- include('/partials/it_patch_update.partial.java.ejs', {fields: fieldsToIncludeInPartialPatchTest, saveMethod, callBlock, callListBlock, persistInstanceUrlId}); -%> } @Test<%= transactionalAnnotation %> void fullUpdate<%= entityClass %>WithPatch() throws Exception { // Initialize the database - <%_ if (!primaryKey.derived) { _%> + <%_ if (primaryKey.autoGenerate) { _%> <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%> <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>); <%_ } _%> <%_ } _%> <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>; - <% const fieldsToIncludeInFullPatchTest = fieldsToTest.map(field => prepareFieldForPatchTest(field, () => true)); %> -<%- include('/partials/it_patch_update.partial.java.ejs', {fields: fieldsToIncludeInFullPatchTest, saveMethod, callBlock, callListBlock}); -%> + <% const fieldsToIncludeInFullPatchTest = fieldsToTest.map(field => prepareFieldForPatchTest(field, () => !field.id)); %> +<%- include('/partials/it_patch_update.partial.java.ejs', {fields: fieldsToIncludeInFullPatchTest, saveMethod, callBlock, callListBlock, persistInstanceUrlId}); -%> } @Test<%= transactionalAnnotation %> @@ -1627,7 +1658,7 @@ _%> <%_ if (searchEngineElasticsearch) { _%> int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>); <%_ } _%> - <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>); + <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForPrimaryKey(primaryKey) %>); <%_ if (dtoMapstruct) { _%> // Create the <%= entityClass %> @@ -1642,7 +1673,7 @@ _%> .exchange() .expectStatus().isBadRequest(); <%_ } else { _%> - rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, <%= restInstance %>.get<%= primaryKey.nameCapitalized %>())<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%> + rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, <%- persistInstanceUrlId %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%> .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) .andExpect(status().isBadRequest()); @@ -1666,7 +1697,7 @@ _%> <%_ if (searchEngineElasticsearch) { _%> int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>); <%_ } _%> - <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>); + <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForPrimaryKey(primaryKey) %>); <%_ if (dtoMapstruct) { _%> // Create the <%= entityClass %> @@ -1675,13 +1706,13 @@ _%> <%_ } _%> // If url ID doesn't match entity ID, it will throw BadRequestAlertException <%_ if (reactive) { _%> - webTestClient.patch().uri(ENTITY_API_URL_ID, <%- this.getJavaValueGeneratorForType(primaryKey.type) %>) + webTestClient.patch().uri(ENTITY_API_URL_ID, <%- generatedUrlId %>) .contentType(MediaType.valueOf("application/merge-patch+json")) .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)) .exchange() .expectStatus().isBadRequest(); <%_ } else { _%> - rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, <%- this.getJavaValueGeneratorForType(primaryKey.type) %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %> + rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, <%- generatedUrlId %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %> .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))) .andExpect(status().isBadRequest()); @@ -1705,7 +1736,7 @@ _%> <%_ if (searchEngineElasticsearch) { _%> int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>); <%_ } _%> - <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>); + <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForPrimaryKey(primaryKey) %>); <%_ if (dtoMapstruct) { _%> // Create the <%= entityClass %> @@ -1742,7 +1773,7 @@ _%> @Test<%= transactionalAnnotation %> void delete<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{ // Initialize the database - <%_ if (!primaryKey.derived) { _%> + <%_ if (primaryKey.autoGenerate) { _%> <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%> <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>); <%_ } _%> @@ -1766,7 +1797,7 @@ _%> .exchange() .expectStatus().isNoContent(); <%_ } else { _%> - rest<%= entityClass %>MockMvc.perform(delete(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.typeUUID && databaseTypeSql) { %>.toString()<% } %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%> + rest<%= entityClass %>MockMvc.perform(delete(ENTITY_API_URL_ID, <%- persistInstanceUrlId %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %> .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); <%_ } _%> @@ -1792,7 +1823,7 @@ _%> @Test<%= transactionalAnnotation %> void search<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{ // Initialize the database - <%_ if (!primaryKey.derived) { _%> + <%_ if (primaryKey.autoGenerate) { _%> <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%> <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>); <%_ } _%> @@ -1817,7 +1848,7 @@ _%> .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) <%_ } _%> - <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) { _%> + <%_ if ((databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) && !primaryKey.composite) { _%> <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= idValue %>))<%= !reactive ? ')' : '' %><%_ } _%><% for (field of fieldsToTest) { %> <%_ if (field.fieldTypeBinary && !field.blobContentTypeText) { _%> <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= field.fieldName %>ContentType").value(hasItem(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE))<%= !reactive ? ')' : '' %> diff --git a/generators/server/templates/src/main/java/package/config/MatrixVariableConfiguration.java.ejs b/generators/server/templates/src/main/java/package/config/MatrixVariableConfiguration.java.ejs new file mode 100644 index 000000000000..c9eaa1a901c4 --- /dev/null +++ b/generators/server/templates/src/main/java/package/config/MatrixVariableConfiguration.java.ejs @@ -0,0 +1,47 @@ +<%# + Copyright 2013-2022 the original author or authors from the JHipster project. + + This file is part of the JHipster project, see https://www.jhipster.tech/ + for more information. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +-%> +package <%=packageName%>.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.web.firewall.StrictHttpFirewall; +import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.util.UrlPathHelper; + +/** + * Configure server to allow Matrix Variables + */ +@Configuration +public class MatrixVariableConfiguration implements WebMvcConfigurer { + + @Override + public void configurePathMatch(PathMatchConfigurer configurer) { + UrlPathHelper urlPathHelper = new UrlPathHelper(); + urlPathHelper.setRemoveSemicolonContent(false); + configurer.setUrlPathHelper(urlPathHelper); + } + + @Bean + public StrictHttpFirewall httpFirewall() { + StrictHttpFirewall firewall = new StrictHttpFirewall(); + firewall.setAllowSemicolon(true); + return firewall; + } +} diff --git a/generators/server/templates/src/main/java/package/config/SecurityConfiguration_imperative.java.ejs b/generators/server/templates/src/main/java/package/config/SecurityConfiguration_imperative.java.ejs index cb28bb04bba0..a2c2ef1f9870 100644 --- a/generators/server/templates/src/main/java/package/config/SecurityConfiguration_imperative.java.ejs +++ b/generators/server/templates/src/main/java/package/config/SecurityConfiguration_imperative.java.ejs @@ -31,7 +31,6 @@ import org.springframework.http.HttpMethod; <%_ } _%> import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; <%_ if (!skipClient) { _%> import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig; <%_ } _%> @@ -84,7 +83,6 @@ import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler; <%_ } _%> <%_ if (authenticationTypeOauth2) { _%> import <%= packageName %>.security.oauth2.JwtGrantedAuthorityConverter; -import static org.springframework.security.config.Customizer.withDefaults; <%_ } _%> <%_ if (authenticationTypeJwt) { _%> import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint; @@ -99,8 +97,11 @@ import <%= packageName %>.security.oauth2.CustomClaimConverter; import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; <%_ } _%> +<%_ if (authenticationTypeOauth2 || !applicationTypeMicroservice) { _%> +import static org.springframework.security.config.Customizer.withDefaults; +<%_ } _%> + @Configuration -@EnableWebSecurity @EnableMethodSecurity(securedEnabled = true) public class SecurityConfiguration { @@ -132,6 +133,9 @@ public class SecurityConfiguration { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http +<%_ if (!applicationTypeMicroservice) { _%> + .cors(withDefaults()) +<%_ } _%> .csrf(csrf -> csrf <%_ if (devDatabaseTypeH2Any) { _%> .ignoringRequestMatchers("/h2-console/**") diff --git a/generators/server/templates/src/main/resources/logback-spring.xml.ejs b/generators/server/templates/src/main/resources/logback-spring.xml.ejs index 937c22601881..34e313506bb8 100644 --- a/generators/server/templates/src/main/resources/logback-spring.xml.ejs +++ b/generators/server/templates/src/main/resources/logback-spring.xml.ejs @@ -45,6 +45,7 @@ --> + @@ -84,6 +85,9 @@ <%_ } _%> <%_ if (databaseTypeSql && reactive) { _%> + <%_ if (prodDatabaseTypeMysql) { _%> + + <%_ } _%> <%_ } _%> <%_ if (!reactive) { _%> diff --git a/generators/server/templates/src/test/java/package/web/rest/TestUtil.java.ejs b/generators/server/templates/src/test/java/package/web/rest/TestUtil.java.ejs index 757aa530b575..011ae3013e63 100644 --- a/generators/server/templates/src/test/java/package/web/rest/TestUtil.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/TestUtil.java.ejs @@ -19,8 +19,10 @@ package <%= packageName %>.web.rest; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; @@ -67,11 +69,12 @@ public final class TestUtil { private static final ObjectMapper mapper = createObjectMapper(); private static ObjectMapper createObjectMapper() { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false); - mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); - mapper.registerModule(new JavaTimeModule()); - return mapper; + return JsonMapper.builder() + .configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false) + .configure(MapperFeature.USE_ANNOTATIONS, false) + .serializationInclusion(JsonInclude.Include.NON_EMPTY) + .addModule(new JavaTimeModule()) + .build(); } /** diff --git a/generators/spring-data-cassandra/__snapshots__/generator.spec.mts.snap b/generators/spring-data-cassandra/__snapshots__/generator.spec.mts.snap index 13eb9874f17f..ddd278c6cb30 100644 --- a/generators/spring-data-cassandra/__snapshots__/generator.spec.mts.snap +++ b/generators/spring-data-cassandra/__snapshots__/generator.spec.mts.snap @@ -963,6 +963,9 @@ exports[`generator - cassandra microservice-jwt-reactive(false)-maven-enableTran "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -1642,6 +1645,9 @@ exports[`generator - cassandra microservice-oauth2-reactive(false)-maven-enableT "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -2372,6 +2378,9 @@ exports[`generator - cassandra monolith-jwt-reactive(false)-maven-enableTranslat "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -3201,6 +3210,9 @@ exports[`generator - cassandra monolith-oauth2-reactive(false)-maven-enableTrans "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/OAuth2Configuration.java": { "stateCleared": "modified", }, @@ -4012,6 +4024,9 @@ exports[`generator - cassandra monolith-session-reactive(false)-maven-enableTran "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, diff --git a/generators/spring-data-couchbase/__snapshots__/generator.spec.mts.snap b/generators/spring-data-couchbase/__snapshots__/generator.spec.mts.snap index fef4aaa118ef..0f02002ffcab 100644 --- a/generators/spring-data-couchbase/__snapshots__/generator.spec.mts.snap +++ b/generators/spring-data-couchbase/__snapshots__/generator.spec.mts.snap @@ -1002,6 +1002,9 @@ exports[`generator - couchbase microservice-jwt-reactive(false)-maven-enableTran "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -1681,6 +1684,9 @@ exports[`generator - couchbase microservice-oauth2-reactive(false)-maven-enableT "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -2456,6 +2462,9 @@ exports[`generator - couchbase monolith-jwt-reactive(false)-maven-enableTranslat "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -3309,6 +3318,9 @@ exports[`generator - couchbase monolith-oauth2-reactive(false)-maven-enableTrans "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/OAuth2Configuration.java": { "stateCleared": "modified", }, @@ -4159,6 +4171,9 @@ exports[`generator - couchbase monolith-session-reactive(false)-maven-enableTran "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, diff --git a/generators/spring-data-elasticsearch/__snapshots__/generator.spec.mts.snap b/generators/spring-data-elasticsearch/__snapshots__/generator.spec.mts.snap index 95e145acb806..a68fe5bf3ebb 100644 --- a/generators/spring-data-elasticsearch/__snapshots__/generator.spec.mts.snap +++ b/generators/spring-data-elasticsearch/__snapshots__/generator.spec.mts.snap @@ -1050,6 +1050,9 @@ exports[`generator - elasticsearch microservice-jwt-reactive(false)-maven-enable "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -1837,6 +1840,9 @@ exports[`generator - elasticsearch microservice-oauth2-reactive(false)-maven-ena "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -2663,6 +2669,9 @@ exports[`generator - elasticsearch monolith-jwt-reactive(false)-maven-enableTran "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -3600,6 +3609,9 @@ exports[`generator - elasticsearch monolith-oauth2-reactive(false)-maven-enableT "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/OAuth2Configuration.java": { "stateCleared": "modified", }, @@ -4567,6 +4579,9 @@ exports[`generator - elasticsearch monolith-session-reactive(false)-maven-enable "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, diff --git a/generators/spring-data-mongodb/__snapshots__/generator.spec.mts.snap b/generators/spring-data-mongodb/__snapshots__/generator.spec.mts.snap index 29b5daba20cb..bc8da40b2541 100644 --- a/generators/spring-data-mongodb/__snapshots__/generator.spec.mts.snap +++ b/generators/spring-data-mongodb/__snapshots__/generator.spec.mts.snap @@ -948,6 +948,9 @@ exports[`generator - mongodb microservice-jwt-reactive(false)-maven-enableTransl "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -1603,6 +1606,9 @@ exports[`generator - mongodb microservice-oauth2-reactive(false)-maven-enableTra "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -2330,6 +2336,9 @@ exports[`generator - mongodb monolith-jwt-reactive(false)-maven-enableTranslatio "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -3141,6 +3150,9 @@ exports[`generator - mongodb monolith-oauth2-reactive(false)-maven-enableTransla "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/OAuth2Configuration.java": { "stateCleared": "modified", }, @@ -3937,6 +3949,9 @@ exports[`generator - mongodb monolith-session-reactive(false)-maven-enableTransl "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, diff --git a/generators/spring-data-neo4j/__snapshots__/generator.spec.mts.snap b/generators/spring-data-neo4j/__snapshots__/generator.spec.mts.snap index 5d752534e034..485286e1d26a 100644 --- a/generators/spring-data-neo4j/__snapshots__/generator.spec.mts.snap +++ b/generators/spring-data-neo4j/__snapshots__/generator.spec.mts.snap @@ -957,6 +957,9 @@ exports[`generator - neo4j microservice-jwt-reactive(false)-maven-enableTranslat "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -1606,6 +1609,9 @@ exports[`generator - neo4j microservice-oauth2-reactive(false)-maven-enableTrans "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -2342,6 +2348,9 @@ exports[`generator - neo4j monolith-jwt-reactive(false)-maven-enableTranslation( "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -3153,6 +3162,9 @@ exports[`generator - neo4j monolith-oauth2-reactive(false)-maven-enableTranslati "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/OAuth2Configuration.java": { "stateCleared": "modified", }, @@ -3958,6 +3970,9 @@ exports[`generator - neo4j monolith-session-reactive(false)-maven-enableTranslat "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, diff --git a/generators/spring-data-relational/__snapshots__/generator.spec.mts.snap b/generators/spring-data-relational/__snapshots__/generator.spec.mts.snap index 0784bf827e41..95b229a26688 100644 --- a/generators/spring-data-relational/__snapshots__/generator.spec.mts.snap +++ b/generators/spring-data-relational/__snapshots__/generator.spec.mts.snap @@ -3802,6 +3802,9 @@ exports[`generator - sql microservice-jwt-mariadb-reactive(false)-maven-enableTr "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -4334,6 +4337,9 @@ exports[`generator - sql microservice-jwt-mssql-reactive(false)-maven-enableTran "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -4872,6 +4878,9 @@ exports[`generator - sql microservice-jwt-mysql-reactive(false)-maven-enableTran "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -5413,6 +5422,9 @@ exports[`generator - sql microservice-jwt-oracle-reactive(false)-maven-enableTra "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -5939,6 +5951,9 @@ exports[`generator - sql microservice-jwt-postgresql-reactive(false)-maven-enabl "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -6483,6 +6498,9 @@ exports[`generator - sql microservice-oauth2-mariadb-reactive(false)-maven-enabl "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -7132,6 +7150,9 @@ exports[`generator - sql microservice-oauth2-mssql-reactive(false)-maven-enableT "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -7772,6 +7793,9 @@ exports[`generator - sql microservice-oauth2-mysql-reactive(false)-maven-enableT "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -8418,6 +8442,9 @@ exports[`generator - sql microservice-oauth2-oracle-reactive(false)-maven-enable "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -9061,6 +9088,9 @@ exports[`generator - sql microservice-oauth2-postgresql-reactive(false)-maven-en "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -9692,6 +9722,9 @@ exports[`generator - sql monolith-jwt-mariadb-reactive(false)-maven-enableTransl "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -10410,6 +10443,9 @@ exports[`generator - sql monolith-jwt-mssql-reactive(false)-maven-enableTranslat "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -11131,6 +11167,9 @@ exports[`generator - sql monolith-jwt-mysql-reactive(false)-maven-enableTranslat "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -11843,6 +11882,9 @@ exports[`generator - sql monolith-jwt-oracle-reactive(false)-maven-enableTransla "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -12555,6 +12597,9 @@ exports[`generator - sql monolith-jwt-postgresql-reactive(false)-maven-enableTra "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -13276,6 +13321,9 @@ exports[`generator - sql monolith-oauth2-mariadb-reactive(false)-maven-enableTra "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/OAuth2Configuration.java": { "stateCleared": "modified", }, @@ -13982,6 +14030,9 @@ exports[`generator - sql monolith-oauth2-mssql-reactive(false)-maven-enableTrans "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/OAuth2Configuration.java": { "stateCleared": "modified", }, @@ -14694,6 +14745,9 @@ exports[`generator - sql monolith-oauth2-mysql-reactive(false)-maven-enableTrans "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/OAuth2Configuration.java": { "stateCleared": "modified", }, @@ -15409,6 +15463,9 @@ exports[`generator - sql monolith-oauth2-oracle-reactive(false)-maven-enableTran "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/OAuth2Configuration.java": { "stateCleared": "modified", }, @@ -16109,6 +16166,9 @@ exports[`generator - sql monolith-oauth2-postgresql-reactive(false)-maven-enable "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/OAuth2Configuration.java": { "stateCleared": "modified", }, @@ -16818,6 +16878,9 @@ exports[`generator - sql monolith-session-mariadb-reactive(false)-maven-enableTr "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -17473,6 +17536,9 @@ exports[`generator - sql monolith-session-mssql-reactive(false)-maven-enableTran "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -18128,6 +18194,9 @@ exports[`generator - sql monolith-session-mysql-reactive(false)-maven-enableTran "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -18783,6 +18852,9 @@ exports[`generator - sql monolith-session-oracle-reactive(false)-maven-enableTra "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, @@ -19432,6 +19504,9 @@ exports[`generator - sql monolith-session-postgresql-reactive(false)-maven-enabl "src/main/java/tech/jhipster/config/LoggingConfiguration.java": { "stateCleared": "modified", }, + "src/main/java/tech/jhipster/config/MatrixVariableConfiguration.java": { + "stateCleared": "modified", + }, "src/main/java/tech/jhipster/config/SecurityConfiguration.java": { "stateCleared": "modified", }, diff --git a/generators/spring-data-relational/templates/src/main/java/package/domain/_PersistClass_.java.jhi.jakarta_persistence.ejs b/generators/spring-data-relational/templates/src/main/java/package/domain/_PersistClass_.java.jhi.jakarta_persistence.ejs index 465136cb078d..433f4bb44621 100644 --- a/generators/spring-data-relational/templates/src/main/java/package/domain/_PersistClass_.java.jhi.jakarta_persistence.ejs +++ b/generators/spring-data-relational/templates/src/main/java/package/domain/_PersistClass_.java.jhi.jakarta_persistence.ejs @@ -22,7 +22,7 @@ -%> <&_ if (fragment.importSection) { -&> import jakarta.persistence.*; -<%_ if ((databaseTypePostgres && anyFieldHasTextContentType) || (anyFieldIsUUID && (databaseTypeMysql || databaseTypeMariadb))) { _%> +<%_ if (anyFieldIsUUID && (databaseTypeMysql || databaseTypeMariadb)) { _%> import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.type.SqlTypes; <%_ } _%> @@ -36,14 +36,16 @@ import org.hibernate.type.SqlTypes; <%_ for (const field of fields) { -%> <&_ if (fragment.field<%- field.fieldNameCapitalized %>AnnotationSection) { -&> <%_ if (field.id) { _%> + <%_ if (primaryKey.fields.length === 1) { _%> @Id - <%_ if (field.jpaGeneratedValue === 'identity') { _%> + <%_ if (field.jpaGeneratedValue === 'identity') { _%> @GeneratedValue(strategy = GenerationType.IDENTITY) - <%_ } else if (field.jpaGeneratedValue === 'sequence') { _%> + <%_ } else if (field.jpaGeneratedValue === 'sequence') { _%> @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") - <%_ } else if (field.jpaGeneratedValue) { _%> + <%_ } else if (field.jpaGeneratedValue) { _%> @GeneratedValue + <%_ } _%> <%_ } _%> <%_ } _%> <%_ if (field.fieldIsEnum) { _%> @@ -60,7 +62,7 @@ import org.hibernate.type.SqlTypes; @JdbcTypeCode(SqlTypes.VARCHAR) @Column(name = "<%- field.fieldNameAsDatabaseColumn %>", length = 36<% if (field.fieldValidationRequired) { %>, nullable = false<% } %><% if (field.fieldValidationUnique) { %>, unique = true<% } %>) <%_ } else { _%> - @Column(name = "<%- field.fieldNameAsDatabaseColumn %>"<% if (field.fieldValidate === true) { %><% if (field.fieldValidationMaxLength) { %>, length = <%= field.fieldValidateRulesMaxlength %><% } %><% if (field.fieldValidationRequired) { %>, nullable = false<% } %><% if (field.fieldValidationUnique) { %>, unique = true<% } %><% } %>) + @Column(name = "<%- field.fieldNameAsDatabaseColumn %>"<% if (field.fieldValidate === true) { %><% if (field.fieldValidationMaxLength) { %>, length = <%= field.fieldValidateRulesMaxlength %><% } %><% if (field.fieldValidationRequired) { %>, nullable = false<% } %><% if (field.fieldValidationUnique) { %>, unique = true<% } %><% } %><%if (field.id && primaryKey.fields.length > 1) { %>, insertable = false, updatable = false<% } %>) <%_ } _%> <&_ } -&> <%_ } -%> @@ -83,6 +85,13 @@ import org.hibernate.type.SqlTypes; <%_ if (relationship.relationshipValidate && relationship.relationshipRequired) { _%> @NotNull <%_ } _%> + <%_ if (relationship.id && !reactive) { _%> + <%_ if (relationship.otherEntity.primaryKey.fields.length === 1) { _%> + @JoinColumn(insertable = false, updatable = false) + <%_ } else { _%> + @JoinColumns({<%- relationship.otherEntity.primaryKey.fields.map(field => '@JoinColumn(name = "' + relationship.columnNamePrefix + field.columnName + '", referencedColumnName = "' + field.columnName + '", insertable = false, updatable = false)').join(', ') %>}) + <%_ } _%> + <%_ } _%> <%_ } else if (relationship.relationshipManyToMany) { -%> @ManyToMany(fetch = FetchType.LAZY<% if (!relationship.ownerSide) { %>, mappedBy = "<%= relationship.otherEntityRelationshipNamePlural %>"<% } %>) <%_ if (relationship.ownerSide) { _%> @@ -92,12 +101,12 @@ import org.hibernate.type.SqlTypes; @JoinTable(name = "<%= relationship.joinTable.name %>", joinColumns = <%= primaryKey.fields.length > 1 ? '{' : '' %> <%_ primaryKey.fields.forEach((field, idx) => { _%> - <%= idx === 0 ? '' : ',' %>@JoinColumn(name = "<%= `${entityTableName}_${field.columnName}` %>") + <%= idx === 0 ? '' : ',' %>@JoinColumn(name = "<%= `${entityTableName}_${field.columnName}` %>", referencedColumnName = "<%= field.columnName %>") <%_ }); _%> <%= primaryKey.fields.length > 1 ? '}' : '' %>, inverseJoinColumns = <%= relationship.otherEntity.primaryKey.fields.length > 1 ? '{' : '' %> <%_ relationship.otherEntity.primaryKey.fields.forEach((field, idx) => { _%> - <%= idx === 0 ? '' : ',' %>@JoinColumn(name = "<%= `${relationship.columnName}_${field.columnName}` %>")) + <%= idx === 0 ? '' : ',' %>@JoinColumn(name = "<%= `${relationship.columnName}_${field.columnName}` %>", referencedColumnName = "<%= field.columnName %>")) <%_ }); _%> <%= relationship.otherEntity.primaryKey.fields.length > 1 ? '}' : '' %> <%_ } _%> @@ -116,7 +125,10 @@ import org.hibernate.type.SqlTypes; <%_ } _%> <%_ if (relationship.id) { %> @MapsId - @JoinColumn(name = "<%= relationship.otherEntity.primaryKey.fields[0].columnName %>") + <% if (relationship.otherEntity.primaryKey.composite) { %>@JoinColumns({<% } %> + <%- relationship.otherEntity.primaryKey.fields.map(field => '@JoinColumn(name = "' + relationship.columnNamePrefix + field.columnName + '", referencedColumnName = "' + field.columnName + '"' + (relationship.otherEntity.primaryKey.composite ? '' : ', insertable = false, updatable = false') + ")").join(', ') %> + <% if (relationship.otherEntity.primaryKey.composite) { %>})<% } else { %> + <%_ } _%> <%_ } else { _%> @JoinColumn(unique = true) <%_ } _%> diff --git a/jdl/jhipster/reserved-keywords/postgresql.ts b/jdl/jhipster/reserved-keywords/postgresql.ts index 148d37965a5d..6c8c7419b419 100644 --- a/jdl/jhipster/reserved-keywords/postgresql.ts +++ b/jdl/jhipster/reserved-keywords/postgresql.ts @@ -116,4 +116,5 @@ export default [ 'WHERE', 'WINDOW', 'WITH', + 'VALUE', ];