From 337690f2402d8c574dae570fe1cf8f9baa806777 Mon Sep 17 00:00:00 2001 From: Charlie Mordant Date: Sun, 18 Apr 2021 13:39:27 +0200 Subject: [PATCH 1/5] use constants in entity-server --- .../repository/EntityRepository.java.ejs | 81 +++---- ...tyRepositoryInternalImpl_reactive.java.ejs | 56 ++--- .../EntityRepository_reactive.java.ejs | 88 ++++---- .../rowmapper/EntityRowMapper.java.ejs | 32 +-- .../search/EntitySearchRepository.java.ejs | 14 +- .../service/EntityQueryService.java.ejs | 55 ++--- .../package/service/EntityService.java.ejs | 45 ++-- .../service/criteria/EntityCriteria.java.ejs | 50 ++--- .../package/service/dto/EntityDTO.java.ejs | 94 ++++---- .../service/impl/EntityServiceImpl.java.ejs | 158 +++++++------- .../service/mapper/EntityMapper.java.ejs | 122 +++++------ .../package/web/rest/EntityResource.java.ejs | 206 +++++++++--------- .../config/cql/changelog/added_entity.cql.ejs | 38 ++-- generators/entity/index.js | 5 + utils/entity.js | 16 +- utils/field.js | 2 +- 16 files changed, 544 insertions(+), 518 deletions(-) diff --git a/generators/entity-server/templates/src/main/java/package/repository/EntityRepository.java.ejs b/generators/entity-server/templates/src/main/java/package/repository/EntityRepository.java.ejs index 98be081da92..5db05b22711 100644 --- a/generators/entity-server/templates/src/main/java/package/repository/EntityRepository.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/repository/EntityRepository.java.ejs @@ -24,46 +24,46 @@ import <%= packageName %>.domain.<%= persistClass %>; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; <%_ } _%> -<%_ if (databaseType === 'sql') { _%> +<%_ if (databaseTypeSql) { _%> import org.springframework.data.jpa.repository.*; - <%_ if (relationshipsContainEagerLoad) { _%> + <%_ if (relationshipsContainEagerLoad) { _%> import org.springframework.data.repository.query.Param; - <%_ } _%> + <%_ } _%> <%_ } _%> -<%_ if (databaseType === 'mongodb') { _%> +<%_ if (databaseTypeMongodb) { _%> import org.springframework.data.mongodb.repository.Query; import org.springframework.data.mongodb.repository.MongoRepository; <%_ } _%> -<%_ if (databaseType === 'neo4j') { _%> +<%_ if (databaseTypeNeo4j) { _%> import org.springframework.data.neo4j.repository.Neo4jRepository; <%_ } _%> -<%_ if (searchEngine === 'couchbase') { _%> +<%_ if (databaseTypeCouchbase) { _%> import <%= packageName %>.repository.search.SearchCouchbaseRepository; -<%_ } _%> -<%_ if (databaseType === 'couchbase' && relationshipsContainEagerLoad === true) { _%> + <%_ if (relationshipsContainEagerLoad) { _%> import org.springframework.data.couchbase.core.query.Query; + <%_ } _%> <%_ } _%> -<%_ if (databaseType === 'cassandra') { _%> +<%_ if (databaseTypeCassandra) { _%> import org.springframework.data.cassandra.repository.CassandraRepository; <%_ } _%> import org.springframework.stereotype.Repository; <%_ -if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'couchbase') { - let importList = fieldsContainOwnerManyToMany; - for (r of relationships) { - if (r.relationshipType === 'many-to-one' && r.otherEntityName === 'user') { - importList = true; - } +if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase) { + let importList = fieldsContainOwnerManyToMany; + for (r of relationships) { + if (r.relationshipManyToOne && r.otherEntityUser) { + importList = true; } + } _%> - <%_ if (importList) { _%> + <%_ if (importList) { _%> import java.util.List; - <%_ } _%> - <%_ if (relationshipsContainEagerLoad) { _%> + <%_ } _%> + <%_ if (relationshipsContainEagerLoad) { _%> import java.util.Optional; - <%_ } _%> + <%_ } _%> <%_ } _%> -<%_ if (primaryKey.type === 'UUID') { _%> +<%_ if (primaryKey.hasUUID) { _%> import java.util.UUID; <%_ } _%> @@ -75,46 +75,49 @@ import java.util.UUID; @SuppressWarnings("unused") <%_ } _%> @Repository -public interface <%= entityClass %>Repository extends <% if (databaseType === 'sql') { %>JpaRepository<% } %><% if (databaseType === 'mongodb') { %>MongoRepository<% } %><% if (databaseType === 'neo4j') { %>Neo4jRepository<% } %><% if (databaseType === 'cassandra') { %>CassandraRepository<% } %><% if (databaseType === 'couchbase') { %>N1qlCouchbaseRepository<% } %><<%= persistClass %>, <%= primaryKey.type %>><% if (jpaMetamodelFiltering) { %>, JpaSpecificationExecutor<<%= persistClass %>><% } %><% if (searchEngine === 'couchbase') { %>, SearchCouchbaseRepository<<%= persistClass %>, <%= primaryKey.type %>><% } %> { - <%_ for (const relationship of relationships) { - if (relationship.relationshipType === 'many-to-one' && relationship.otherEntityName === 'user' && databaseType === 'sql') { _%> +public interface <%= entityClass %>Repository extends <% if (databaseTypeSql) { %>JpaRepository<% } %><% if (databaseTypeMongodb) { %>MongoRepository<% } %><% if (databaseTypeNeo4j) { %>Neo4jRepository<% } %><% if (databaseTypeCassandra) { %>CassandraRepository<% } %><% if (databaseTypeCouchbase) { %>N1qlCouchbaseRepository<% } %><<%= persistClass %>, <%= primaryKey.type %>><% if (jpaMetamodelFiltering) { %>, JpaSpecificationExecutor<<%= persistClass %>><% } %><% if (searchEngineCouchbase) { %>, SearchCouchbaseRepository<<%= persistClass %>, <%= primaryKey.type %>><% } %> { + <%_ + for (const relationship of relationships) { + if (relationship.relationshipManyToOne && relationship.otherEntityUser && databaseTypeSql) { _%> - @Query("select <%= entityInstanceDbSafe %> from <%= persistClass %> <%= entityInstanceDbSafe %> where <%= entityInstanceDbSafe %>.<%= relationship.relationshipFieldName %>.login = ?#{principal.<% if (authenticationType === 'oauth2') { %>preferredUsername<% } else { %>username<% } %>}") + @Query("select <%= entityInstanceDbSafe %> from <%= persistClass %> <%= entityInstanceDbSafe %> where <%= entityInstanceDbSafe %>.<%= relationship.relationshipFieldName %>.login = ?#{principal.<% if (authenticationTypeOauth2) { %>preferredUsername<% } else { %>username<% } %>}") List<<%= persistClass %>> findBy<%= relationship.relationshipNameCapitalized %>IsCurrentUser(); - <%_ } } _%> - <%_ if (relationshipsContainEagerLoad) { - if (databaseType === 'sql') { _%> + <%_ } _%> + <%_ } _%> + <%_ + if (relationshipsContainEagerLoad) { + if (databaseTypeSql) { _%> @Query(value = "select distinct <%= entityInstanceDbSafe %> from <%= persistClass %> <%= entityInstanceDbSafe %><% - for (const relationship of relationships) { + for (const relationship of relationships) { if (relationship.relationshipEagerLoad) { %> left join fetch <%= entityInstanceDbSafe %>.<%= relationship.reference.name %><% } -  } %>", + } %>", countQuery = "select count(distinct <%= entityInstanceDbSafe %>) from <%= persistClass %> <%= entityInstanceDbSafe %>") Page<<%= persistClass %>> findAllWithEagerRelationships(Pageable pageable); @Query("select distinct <%= entityInstanceDbSafe %> from <%= persistClass %> <%= entityInstanceDbSafe %><% - for (const relationship of relationships) { + for (const relationship of relationships) { if (relationship.relationshipEagerLoad) { %> left join fetch <%= entityInstanceDbSafe %>.<%= relationship.reference.name %><% } -  } %>") + } %>") List<<%= persistClass %>> findAllWithEagerRelationships(); @Query("select <%= entityInstanceDbSafe %> from <%= persistClass %> <%= entityInstanceDbSafe %><% - for (const relationship of relationships) { + for (const relationship of relationships) { if (relationship.relationshipEagerLoad) { %> left join fetch <%= entityInstanceDbSafe %>.<%= relationship.reference.name %><% } -  } %> where <%= entityInstanceDbSafe %>.id =:id") + } %> where <%= entityInstanceDbSafe %>.id =:id") Optional<<%= persistClass %>> findOneWithEagerRelationships(@Param("id") <%= primaryKey.type %> id); <%_ - } else if (databaseType === 'mongodb' || databaseType === 'couchbase') { _%> + } else if (databaseTypeMongodb || databaseTypeCouchbase) { _%> - @Query("<%= (databaseType === 'mongodb') ? '{}' : '#{#n1ql.selectEntity} WHERE #{#n1ql.filter}' %>") + @Query("<%= (databaseTypeMongodb) ? '{}' : '#{#n1ql.selectEntity} WHERE #{#n1ql.filter}' %>") Page<<%= persistClass %>> findAllWithEagerRelationships(Pageable pageable); - @Query("<%= (databaseType === 'mongodb') ? '{}' : '#{#n1ql.selectEntity} WHERE #{#n1ql.filter}' %>") + @Query("<%= (databaseTypeMongodb) ? '{}' : '#{#n1ql.selectEntity} WHERE #{#n1ql.filter}' %>") List<<%= persistClass %>> findAllWithEagerRelationships(); - @Query("<%- (databaseType === 'mongodb') ? "{'id': ?0}" : "#{#n1ql.selectEntity} USE KEYS $1 WHERE #{#n1ql.filter}" %>") + @Query("<%- (databaseTypeMongodb) ? "{'id': ?0}" : "#{#n1ql.selectEntity} USE KEYS $1 WHERE #{#n1ql.filter}" %>") Optional<<%= persistClass %>> findOneWithEagerRelationships(<%= primaryKey.type %> id); <%_ - } - } _%> + } + } _%> } diff --git a/generators/entity-server/templates/src/main/java/package/repository/EntityRepositoryInternalImpl_reactive.java.ejs b/generators/entity-server/templates/src/main/java/package/repository/EntityRepositoryInternalImpl_reactive.java.ejs index ec5dcd1115e..8e79d571d23 100644 --- a/generators/entity-server/templates/src/main/java/package/repository/EntityRepositoryInternalImpl_reactive.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/repository/EntityRepositoryInternalImpl_reactive.java.ejs @@ -19,17 +19,17 @@ package <%= packageName %>.repository; import java.util.function.BiFunction; -<%_ if (fieldsContainBigDecimal === true) { _%> +<%_ if (fieldsContainBigDecimal) { _%> import java.math.BigDecimal; -<%_} if (fieldsContainInstant === true) { _%> +<%_} if (fieldsContainInstant) { _%> import java.time.Instant; -<%_ } if (fieldsContainLocalDate === true) { _%> +<%_ } if (fieldsContainLocalDate) { _%> import java.time.LocalDate; -<%_ } if (fieldsContainZonedDateTime === true) { _%> +<%_ } if (fieldsContainZonedDateTime) { _%> import java.time.ZonedDateTime; -<%_ } if (fieldsContainDuration === true) { _%> +<%_ } if (fieldsContainDuration) { _%> import java.time.Duration; -<%_ } if (fieldsContainUUID === true) { _%> +<%_ } if (fieldsContainUUID) { _%> import java.util.UUID; <%_ } _%> import java.util.ArrayList; @@ -38,7 +38,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import org.springframework.data.domain.Pageable; -<%_ if (databaseType === 'sql') { _%> +<%_ if (databaseTypeSql) { _%> import io.r2dbc.spi.Row; import io.r2dbc.spi.RowMetadata; @@ -58,10 +58,10 @@ import org.springframework.r2dbc.core.RowsFetchSpec; import <%= packageName %>.domain.<%= persistClass %>; <% relationships.forEach(function(rel) { - if (rel.relationshipType === 'many-to-many' && rel.ownerSide) { _%> + if (rel.relationshipManyToMany && rel.ownerSide) { _%> import <%= packageName %>.domain.<%= asEntity(rel.otherEntityNameCapitalized) %>; - <%_ } _%> -<%_ } ); _%> + <%_ } _%> +<%_ }); _%> <%_ Object.keys(uniqueEnums).forEach(function(element) { _%> import <%= packageName %>.domain.enumeration.<%= element %>; @@ -97,7 +97,7 @@ class <%= entityClass %>RepositoryInternalImpl implements <%= entityClass %>Repo <%_ }); _%> <%_ relationships.forEach(function(rel) { - if (rel.shouldWriteJoinTable) { + if (rel.shouldWriteJoinTable) { _%> private final static EntityManager.LinkTable <%= rel.relationshipName %>Link = new LinkTable("<%= rel.joinTable.name %>", "<%= getColumnName(name) %>_id", "<%= getColumnName(rel.relationshipName) %>_id"); <%_ } @@ -133,13 +133,13 @@ _%> .leftOuterJoin(<%= rel.relationshipName %>Table).on(Column.create("<%= colName %>", entityTable)).equals(Column.create("id", <%= rel.relationshipName %>Table ))<%_ }); _%>; String select = entityManager.createSelect(selectFrom, <%= persistClass %>.class, pageable, criteria); -<%_ if (databaseType === 'sql') { _%> +<%_ if (databaseTypeSql) { _%> String alias = entityTable.getReferenceName().getReference(); String selectWhere = Optional.ofNullable(criteria).map(crit -> new StringBuilder(select).append(" ").append("WHERE").append(" ").append(alias).append(".").append(crit.toString()).toString()).orElse(select); // TODO remove once https://github.com/spring-projects/spring-data-jdbc/issues/907 will be fixed <%_ } _%> - return db.sql(select<% if (databaseType === 'sql') { %>Where<% } %>).map(this::process); + return db.sql(select<% if (databaseTypeSql) { %>Where<% } %>).map(this::process); } @Override @@ -172,9 +172,9 @@ _%> <%_ } _%> private <%= persistClass %> process(Row row, RowMetadata metadata) { <%= persistClass %> entity = <%= entityClass.toLowerCase() %>Mapper.apply(row, "e"); - <%_ reactiveEagerRelations.forEach(function(rel) { _%> +<%_ reactiveEagerRelations.forEach(function(rel) { _%> entity.set<%= rel.relationshipNameCapitalized %>(<%= rel.otherEntityNameCapitalized.toLowerCase() %>Mapper.apply(row, "<%= rel.relationshipName %>")); - <%_ }); _%> +<%_ }); _%> return entity; } @@ -222,27 +222,27 @@ _%> protected > Mono updateRelations(S entity) { <%_ relationships.filter(function(rel) { - return (rel.relationshipType === 'many-to-many' && rel.ownerSide); - }).forEach(function(rel, idx) { - if (idx === 0) { _%> + return (rel.relationshipManyToMany && rel.ownerSide); + }).forEach(function(rel, idx) { + if (idx === 0) { _%> Mono result = entityManager.updateLinkTable(<%= rel.relationshipName %>Link, entity.get<%= primaryKey.nameCapitalized %>(), entity.get<%= rel.relationshipNameCapitalizedPlural %>().stream().map(<%= asEntity(rel.otherEntityNameCapitalized) %>::getId)).then(); - <%_ } else { _%> + <%_ } else { _%> result = result.and(entityManager.updateLinkTable(<%= rel.relationshipName %>Link, entity.get<%= primaryKey.nameCapitalized %>(), entity.get<%= rel.relationshipNameCapitalizedPlural %>().stream().map(<%= asEntity(rel.otherEntityNameCapitalized) %>::getId))); - <%_ - } - }); _%> + <%_ + } + }); _%> return result.thenReturn(entity); } protected Mono deleteRelations(Long entityId) { <%_ relationships.filter(function(rel) { - return (rel.relationshipType === 'many-to-many' && rel.ownerSide); - }).forEach(function(rel, idx) { - if (idx === 0) { _%> + return (rel.relationshipManyToMany && rel.ownerSide); + }).forEach(function(rel, idx) { + if (idx === 0) { _%> return entityManager.deleteFromLinkTable(<%= rel.relationshipName %>Link, entityId)<% - } else { %> + } else { %> .and(entityManager.deleteFromLinkTable(<%= rel.relationshipName %>Link, entityId))<% } - }); %>; + }); %>; } <%_ } _%> @@ -255,7 +255,7 @@ class <%= entityClass %>SqlHelper { let col = field.fieldNameAsDatabaseColumn; _%> columns.add(Column.aliased("<%= col %>", table, columnPrefix + "_<%= col %>")); - <%_ if ((field.fieldType === 'byte[]' || field.fieldType === 'ByteBuffer') && field.fieldTypeBlobContent !== 'text') { _%> + <%_ if ((field.fieldTypeBinary) && !field.blobContentTypeText) { _%> columns.add(Column.aliased("<%= col %>_content_type", table, columnPrefix + "_<%= col %>_content_type")); <%_ } _%> <%_ }); _%> diff --git a/generators/entity-server/templates/src/main/java/package/repository/EntityRepository_reactive.java.ejs b/generators/entity-server/templates/src/main/java/package/repository/EntityRepository_reactive.java.ejs index 60afd99789b..da9d469390d 100644 --- a/generators/entity-server/templates/src/main/java/package/repository/EntityRepository_reactive.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/repository/EntityRepository_reactive.java.ejs @@ -19,42 +19,42 @@ package <%= packageName %>.repository; import <%= packageName %>.domain.<%= persistClass %>; -<%_ if (databaseType === 'cassandra') { _%> +<%_ if (databaseTypeCassandra) { _%> import org.springframework.data.cassandra.repository.ReactiveCassandraRepository; <%_ } _%> -<%_ if (searchEngine === 'couchbase') { _%> +<%_ if (databaseTypeCouchbase) { _%> import <%= packageName %>.repository.search.SearchCouchbaseRepository; <%_ } _%> -<%_ if (databaseType === 'couchbase') { _%> +<%_ if (databaseTypeCouchbase) { _%> import org.springframework.data.couchbase.core.query.Query; import org.springframework.data.couchbase.repository.ReactiveCouchbaseSortingRepository; <%_ } _%> -<%_ if (databaseType === 'neo4j') { _%> +<%_ if (databaseTypeNeo4j) { _%> import org.springframework.data.neo4j.repository.ReactiveNeo4jRepository; import org.springframework.data.neo4j.repository.query.Query; <%_ } _%> -<%_ if (pagination !== 'no' || relationshipsContainEagerLoad || databaseType ==='sql') { _%> +<%_ if (!paginationNo || relationshipsContainEagerLoad || databaseTypeSql) { _%> import org.springframework.data.domain.Pageable; <%_ } _%> -<%_ if (databaseType === 'sql') { _%> +<%_ if (databaseTypeSql) { _%> import org.springframework.data.r2dbc.repository.Query; import org.springframework.data.r2dbc.repository.R2dbcRepository; import org.springframework.data.relational.core.query.Criteria; <%_ } _%> -<%_ if (databaseType === 'mongodb') { _%> - <%_ if (relationshipsContainEagerLoad) { _%> +<%_ if (databaseTypeMongodb) { _%> + <%_ if (relationshipsContainEagerLoad) { _%> import org.springframework.data.mongodb.repository.Query; - <%_ } _%> + <%_ } _%> import org.springframework.data.mongodb.repository.ReactiveMongoRepository; <%_ } _%> import org.springframework.stereotype.Repository; -<%_ if (['couchbase', 'sql'].includes(databaseType) || pagination !== 'no' || relationshipsContainEagerLoad) { _%> +<%_ if (databaseTypeCouchbase || databaseTypeSql || !paginationNo || relationshipsContainEagerLoad) { _%> import reactor.core.publisher.Flux; <%_ } _%> -<%_ if (relationshipsContainEagerLoad || databaseType === 'sql') { _%> +<%_ if (relationshipsContainEagerLoad || databaseTypeSql) { _%> import reactor.core.publisher.Mono; <%_ } _%> -<%_ if (primaryKey.type === 'UUID') { _%> +<%_ if (primaryKey.hasUUID) { _%> import java.util.UUID; <%_ } _%> @@ -64,25 +64,25 @@ import java.util.UUID; */ @SuppressWarnings("unused") @Repository -public interface <%= entityClass %>Repository extends <% if (databaseType === 'sql') { %>R2dbc<% } if (databaseType === 'mongodb') { %>ReactiveMongo<% } if (databaseType === 'couchbase') { %>ReactiveN1qlCouchbase<% } if (databaseType === 'neo4j') { %>ReactiveNeo4j<% } if (databaseType === 'cassandra') { %>ReactiveCassandra<% } %>Repository<<%= persistClass %>, <%= primaryKey.type %>><% if (searchEngine === 'couchbase') { %>, SearchCouchbaseRepository<<%= persistClass %>, <%= primaryKey.type %>><% } %><% if (databaseType === 'sql') { %>, <%= entityClass %>RepositoryInternal<% } %> { +public interface <%= entityClass %>Repository extends <% if (databaseTypeSql) { %>R2dbc<% } if (databaseTypeMongodb) { %>ReactiveMongo<% } if (databaseTypeCouchbase) { %>ReactiveN1qlCouchbase<% } if (databaseTypeNeo4j) { %>ReactiveNeo4j<% } if (databaseTypeCassandra) { %>ReactiveCassandra<% } %>Repository<<%= persistClass %>, <%= primaryKey.type %>><% if (searchEngineCouchbase) { %>, SearchCouchbaseRepository<<%= persistClass %>, <%= primaryKey.type %>><% } %><% if (databaseTypeSql) { %>, <%= entityClass %>RepositoryInternal<% } %> { - <%_ if (pagination !== 'no') { _%> +<%_ if (!paginationNo) { _%> Flux<<%= persistClass %>> findAllBy(Pageable pageable); - <%_ } _%> - <%_ if (relationshipsContainEagerLoad) { _%> - <%_ if (['couchbase', 'mongodb'].includes(databaseType)) { _%> +<%_ } _%> +<%_ if (relationshipsContainEagerLoad) { _%> + <%_ if (databaseTypeCouchbase || databaseTypeMongodb) { _%> - @Query("<%= (databaseType === 'mongodb') ? '{}' : '#{#n1ql.selectEntity} WHERE #{#n1ql.filter}' %>") + @Query("<%= (databaseTypeMongodb) ? '{}' : '#{#n1ql.selectEntity} WHERE #{#n1ql.filter}' %>") Flux<<%= persistClass %>> findAllWithEagerRelationships(Pageable pageable); - @Query("<%= (databaseType === 'mongodb') ? '{}' : '#{#n1ql.selectEntity} WHERE #{#n1ql.filter}' %>") + @Query("<%= (databaseTypeMongodb) ? '{}' : '#{#n1ql.selectEntity} WHERE #{#n1ql.filter}' %>") Flux<<%= persistClass %>> findAllWithEagerRelationships(); - @Query("<%- (databaseType === 'mongodb') ? "{'id': ?0}" : "#{#n1ql.selectEntity} USE KEYS $1 WHERE #{#n1ql.filter}" %>") + @Query("<%- (databaseTypeMongodb) ? "{'id': ?0}" : "#{#n1ql.selectEntity} USE KEYS $1 WHERE #{#n1ql.filter}" %>") Mono<<%= persistClass %>> findOneWithEagerRelationships(<%= primaryKey.type %> id); - <%_ } _%> - <%_ if (databaseType === 'neo4j') { _%> + <%_ } _%> + <%_ if (databaseTypeNeo4j) { _%> @Query("MATCH (n:<%= persistClass %>)<-[]-(m) RETURN n,m") Flux<<%= persistClass %>> findAllWithEagerRelationships(Pageable pageable); @@ -91,10 +91,11 @@ public interface <%= entityClass %>Repository extends <% if (databaseType === 's @Query("MATCH (e:<%= persistClass %> {id: $id}) RETURN e") Mono<<%= persistClass %>> findOneWithEagerRelationships(<%= primaryKey.type %> id); - <%_ } _%> - <%_ } _%> - <%_ if (databaseType === 'sql') { - if (fieldsContainOwnerManyToMany) { _%> + <%_ } _%> +<%_ } _%> +<%_ +if (databaseTypeSql) { + if (fieldsContainOwnerManyToMany) { _%> @Override Mono<<%= persistClass %>> findOneWithEagerRelationships(<%= primaryKey.type %> id); @@ -108,33 +109,32 @@ public interface <%= entityClass %>Repository extends <% if (databaseType === 's @Override Mono deleteById(Long id); - <%_ } _%> + <%_ } _%> - <%_ for (const relationship of relationships) { - let relationshipType = relationship.relationshipType; - let relationshipName = relationship.relationshipName; - let ownerSide = relationship.ownerSide; - if (relationshipType === 'many-to-one' || (relationshipType === 'one-to-one' && ownerSide === true)) { _%> + <%_ + for (const relationship of relationships) { + let relationshipName = relationship.relationshipName; + let ownerSide = relationship.ownerSide; + if (relationship.relationshipManyToOne || (relationship.relationshipOneToOne && ownerSide)) { _%> @Query("SELECT * FROM <%= entityTableName %> entity WHERE entity.<%= getColumnName(relationshipName) %>_id = :id") Flux<<%= persistClass %>> findBy<%= relationship.relationshipNameCapitalized %>(<%= primaryKey.type %> id); @Query("SELECT * FROM <%= entityTableName %> entity WHERE entity.<%= getColumnName(relationshipName) %>_id IS NULL") Flux<<%= persistClass %>> findAllWhere<%= relationship.relationshipNameCapitalized %>IsNull(); - <%_ } else if (relationship.shouldWriteJoinTable) { - _%> + <%_ } else if (relationship.shouldWriteJoinTable) { _%> @Query("SELECT entity.* FROM <%= entityTableName %> entity JOIN <%= relationship.joinTable.name %> joinTable ON entity.id = joinTable.<%= getColumnName(name) %>_id WHERE joinTable.<%= getColumnName(relationshipName) %>_id = :id") Flux<<%= persistClass %>> findBy<%= relationship.relationshipNameCapitalized %>(<%= primaryKey.type %> id); - <%_ } else if (relationshipType === 'one-to-one' && ownerSide === false) { - let otherEntityRelationshipName = relationship.otherEntityRelationshipName; - let otherEntityTableName = relationship.otherEntityTableName; - _%> + <%_ } else if (relationship.relationshipOneToOne && !ownerSide) { + let otherEntityRelationshipName = relationship.otherEntityRelationshipName; + let otherEntityTableName = relationship.otherEntityTableName; + _%> @Query("SELECT * FROM <%= entityTableName %> entity WHERE entity.id not in (select <%= getColumnName(otherEntityRelationshipName) %>_id from <%= otherEntityTableName %>)") Flux<<%= persistClass %>> findAllWhere<%= relationship.relationshipNameCapitalized %>IsNull(); - <%_ } _%> - <%_ } _%> + <%_ } _%> + <%_ } _%> // just to avoid having unambigous methods @Override @@ -146,10 +146,10 @@ public interface <%= entityClass %>Repository extends <% if (databaseType === 's @Override > Mono save(S entity); - <%_ } _%> +<%_ } _%> } -<%_ if (databaseType === 'sql') { _%> +<%_ if (databaseTypeSql) { _%> interface <%= entityClass %>RepositoryInternal { > Mono insert(S entity); > Mono save(S entity); @@ -160,7 +160,7 @@ interface <%= entityClass %>RepositoryInternal { Flux<<%= persistClass %>> findAllBy(Pageable pageable); Flux<<%= persistClass %>> findAllBy(Pageable pageable, Criteria criteria); - <%_ if (fieldsContainOwnerManyToMany) { _%> + <%_ if (fieldsContainOwnerManyToMany) { _%> Mono<<%= persistClass %>> findOneWithEagerRelationships(<%= primaryKey.type %> id); @@ -169,7 +169,7 @@ interface <%= entityClass %>RepositoryInternal { Flux<<%= persistClass %>> findAllWithEagerRelationships(Pageable page); Mono deleteById(Long id); - <%_ } _%> + <%_ } _%> } <%_ } _%> diff --git a/generators/entity-server/templates/src/main/java/package/repository/rowmapper/EntityRowMapper.java.ejs b/generators/entity-server/templates/src/main/java/package/repository/rowmapper/EntityRowMapper.java.ejs index 3ea27ee5c33..6d6c5c5c02f 100644 --- a/generators/entity-server/templates/src/main/java/package/repository/rowmapper/EntityRowMapper.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/repository/rowmapper/EntityRowMapper.java.ejs @@ -18,17 +18,17 @@ -%> package <%= packageName %>.repository.rowmapper; -<%_ if (fieldsContainBigDecimal === true) { _%> +<%_ if (fieldsContainBigDecimal) { _%> import java.math.BigDecimal; -<%_} if (fieldsContainInstant === true) { _%> +<%_} if (fieldsContainInstant) { _%> import java.time.Instant; -<%_ } if (fieldsContainLocalDate === true) { _%> +<%_ } if (fieldsContainLocalDate) { _%> import java.time.LocalDate; -<%_ } if (fieldsContainZonedDateTime === true) { _%> +<%_ } if (fieldsContainZonedDateTime) { _%> import java.time.ZonedDateTime; -<%_ } if (fieldsContainDuration === true) { _%> +<%_ } if (fieldsContainDuration) { _%> import java.time.Duration; -<%_ } if (fieldsContainUUID === true) { _%> +<%_ } if (fieldsContainUUID) { _%> import java.util.UUID; <%_ } _%> import java.util.function.BiFunction; @@ -60,19 +60,19 @@ public class <%= entityClass %>RowMapper implements BiFunction apply(Row row, String prefix) { <%= persistClass %> entity = new <%= persistClass %>(); - <%_ fields.forEach(function(field) { - let fieldType = field.fieldType; - if (field.fieldTypeBlobContent === 'text') { - fieldType = 'String'; - } - if (field.fieldType === 'byte[]' && field.fieldTypeBlobContent !== 'text') { _%> +<%_ fields.forEach(function(field) { + let fieldType = field.fieldType; + if (field.blobContentTypeText) { + fieldType = 'String'; + } + if (field.fieldTypeBytes && !field.blobContentTypeText) { _%> entity.set<%= field.fieldInJavaBeanMethod %>ContentType(converter.fromRow(row, prefix + "_<%= field.fieldNameAsDatabaseColumn %>_content_type", String.class)); - <%_ } _%> + <%_ } _%> entity.set<%= field.fieldInJavaBeanMethod %>(converter.fromRow(row, prefix + "_<%= field.fieldNameAsDatabaseColumn %>", <%= fieldType %>.class)); - <%_ }); _%> - <%_ reactiveRegularEagerRelations.forEach(function(rel) { _%> +<%_ }); _%> +<%_ reactiveRegularEagerRelations.forEach(function(rel) { _%> entity.set<%= rel.relationshipNameCapitalized %>Id(converter.fromRow(row, prefix + "_<%= getColumnName(rel.relationshipName) %>_id", <%= rel.otherEntity.primaryKey.type %>.class)); - <%_ }); _%> +<%_ }); _%> return entity; } diff --git a/generators/entity-server/templates/src/main/java/package/repository/search/EntitySearchRepository.java.ejs b/generators/entity-server/templates/src/main/java/package/repository/search/EntitySearchRepository.java.ejs index 370df229d4e..7a9bfde82f9 100644 --- a/generators/entity-server/templates/src/main/java/package/repository/search/EntitySearchRepository.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/repository/search/EntitySearchRepository.java.ejs @@ -20,9 +20,9 @@ package <%= packageName %>.repository.search; import <%= packageName %>.domain.<%= persistClass %>; <%_ if (reactive) { _%> - <%_ if (pagination !== 'no') { _%> + <%_ if (!paginationNo) { _%> import org.springframework.data.domain.Pageable; - <%_ } _%> + <%_ } _%> import org.springframework.data.elasticsearch.core.ReactiveElasticsearchTemplate; import org.springframework.data.elasticsearch.core.SearchHit; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; @@ -31,7 +31,7 @@ import org.springframework.data.elasticsearch.repository.<% if (reactive) {%>Rea <%_ if (reactive) { _%> import reactor.core.publisher.Flux; <%_ } _%> -<%_ if (primaryKey.type === 'UUID') { _%> +<%_ if (primaryKey.hasUUID) { _%> import java.util.UUID; <% } %> @@ -48,7 +48,7 @@ public interface <%= entityClass %>SearchRepository extends <% if (reactive) {%> <%_ if (reactive) { _%> interface <%= entityClass %>SearchRepositoryInternal { - Flux<<%= entityClass %>> search(String query<% if (pagination !== 'no') { %>, Pageable pageable<% } %>); + Flux<<%= entityClass %>> search(String query<% if (!paginationNo) { %>, Pageable pageable<% } %>); } class <%= entityClass %>SearchRepositoryInternalImpl implements <%= entityClass %>SearchRepositoryInternal { @@ -60,11 +60,11 @@ class <%= entityClass %>SearchRepositoryInternalImpl implements <%= entityClass } @Override - public Flux<<%= entityClass %>> search(String query<% if (pagination !== 'no') { %>, Pageable pageable<% } %>) { + public Flux<<%= entityClass %>> search(String query<% if (!paginationNo) { %>, Pageable pageable<% } %>) { NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(queryStringQuery(query)); - <%_ if (pagination !== 'no') { _%> + <%_ if (!paginationNo) { _%> nativeSearchQuery.setPageable(pageable); - <%_ } _%> + <%_ } _%> return reactiveElasticsearchTemplate .search(nativeSearchQuery, <%= entityClass %>.class) .map(SearchHit::getContent); diff --git a/generators/entity-server/templates/src/main/java/package/service/EntityQueryService.java.ejs b/generators/entity-server/templates/src/main/java/package/service/EntityQueryService.java.ejs index 52e8e52e6c8..1b1c3075384 100644 --- a/generators/entity-server/templates/src/main/java/package/service/EntityQueryService.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/EntityQueryService.java.ejs @@ -46,10 +46,12 @@ import tech.jhipster.service.QueryService; import <%= packageName %>.domain.<%= persistClass %>; import <%= packageName %>.domain.*; // for static metamodels -import <%= packageName %>.repository.<%= entityClass %>Repository;<% if (searchEngine === 'elasticsearch') { %> -import <%= packageName %>.repository.search.<%= entityClass %>SearchRepository;<% } %> +import <%= packageName %>.repository.<%= entityClass %>Repository; +<%_ if (searchEngineElasticsearch) { _%> +import <%= packageName %>.repository.search.<%= entityClass %>SearchRepository; +<%_ } _%> import <%= packageName %>.service.criteria.<%= entityClass %>Criteria; -<%_ if (dto === 'mapstruct') { _%> +<%_ if (dtoMapstruct) { _%> import <%= packageName %>.service.dto.<%= dtoClass %>; import <%= packageName %>.service.mapper.<%= entityClass %>Mapper; <%_ } _%> @@ -60,8 +62,10 @@ import <%= packageName %>.service.mapper.<%= entityClass %>Mapper; * in a way that all the filters must apply. * It returns a {@link List} of {@link <%= instanceType %>} or a {@link Page} of {@link <%= instanceType %>} which fulfills the criteria. */ -@Service<% if (databaseType === 'sql') { %> -@Transactional(readOnly = true)<% } %> +@Service +<%_ if (databaseTypeSql) { _%> +@Transactional(readOnly = true) +<%_ } _%> public class <%= serviceClassName %> extends QueryService<<%= persistClass %>> { private final Logger log = LoggerFactory.getLogger(<%= serviceClassName %>.class); @@ -76,11 +80,11 @@ public class <%= serviceClassName %> extends QueryService<<%= persistClass %>> { public List<<%= instanceType %>> findByCriteria(<%= criteria %> criteria) { log.debug("find by criteria : {}", criteria); final Specification<<%= persistClass %>> specification = createSpecification(criteria); - <%_ if (dto === 'mapstruct') { _%> +<%_ if (dtoMapstruct) { _%> return <%= entityListToDto %>(<%= repository %>.findAll(specification)); - <%_ } else { _%> +<%_ } else { _%> return <%= repository %>.findAll(specification); - <%_ } _%> +<%_ } _%> } /** @@ -93,12 +97,12 @@ public class <%= serviceClassName %> extends QueryService<<%= persistClass %>> { public Page<<%= instanceType %>> findByCriteria(<%= criteria %> criteria, Pageable page) { log.debug("find by criteria : {}, page: {}", criteria, page); final Specification<<%= persistClass %>> specification = createSpecification(criteria); - <%_ if (dto === 'mapstruct') { _%> +<%_ if (dtoMapstruct) { _%> return <%= repository %>.findAll(specification, page) .map(<%= entityToDtoReference %>); - <%_ } else { _%> +<%_ } else { _%> return <%= repository %>.findAll(specification, page); - <%_ } _%> +<%_ } _%> } /** @@ -124,24 +128,23 @@ public class <%= serviceClassName %> extends QueryService<<%= persistClass %>> { if (criteria.get<%= primaryKey.nameCapitalized %>() != null) { specification = specification.and(<%= getSpecificationBuilder(primaryKey.type) %>(criteria.get<%= primaryKey.nameCapitalized %>(), <%= persistClass %>_.<%= primaryKey.name %>)); } - <%_ - fields.forEach((field) => { - if (field.id) return; - if (isFilterableType(field.fieldType)) { _%> +<%_ +fields.forEach((field) => { + if (field.id) return; + if (isFilterableType(field.fieldType)) { _%> if (criteria.get<%= field.fieldInJavaBeanMethod %>() != null) { specification = specification.and(<%= getSpecificationBuilder(field.fieldType) %>(criteria.get<%= field.fieldInJavaBeanMethod %>(), <%= persistClass %>_.<%= field.fieldName %>)); } - <%_ } - }); - - relationships.forEach((relationship) => { - const metamodelFieldName = (relationship.relationshipType === 'many-to-many' || relationship.relationshipType === 'one-to-many') ? 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(<%= asEntity(relationship.otherEntityNameCapitalized) %>_.<%= relationship.otherEntity.primaryKey.name %>))); - } - <%_ }); // forEach - _%> + <%_ } +}); + +relationships.forEach((relationship) => { + 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(<%= asEntity(relationship.otherEntityNameCapitalized) %>_.<%= relationship.otherEntity.primaryKey.name %>))); +} +<%_ }); /* forEach */ _%> } return specification; } diff --git a/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs b/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs index 88e321c7d8f..b3277d71d55 100644 --- a/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs @@ -21,20 +21,20 @@ package <%= packageName %>.service; <%_ const instanceType = restClass; const instanceName = restInstance; -const optionalOrMono = (reactive === true) ? 'Mono' : 'Optional'; -const listOrFlux = (reactive === true) ? 'Flux' : 'List'; -const pageOrFlux = (reactive === true) ? 'Flux' : 'Page'; +const optionalOrMono = (reactive) ? 'Mono' : 'Optional'; +const listOrFlux = (reactive) ? 'Flux' : 'List'; +const pageOrFlux = (reactive) ? 'Flux' : 'Page'; _%> -<%_ if (dto === 'mapstruct') { _%> +<%_ if (dtoMapstruct) { _%> import <%= packageName %>.service.dto.<%= dtoClass %>; <%_ } else { _%> import <%= packageName %>.domain.<%= persistClass %>; <%_ } _%> -<%_ if (pagination !== 'no' || relationshipsContainEagerLoad) { _%> +<%_ if (!paginationNo || relationshipsContainEagerLoad) { _%> - <%_ if (!reactive) { _%> + <%_ if (!reactive) { _%> import org.springframework.data.domain.Page; - <%_ } _%> + <%_ } _%> import org.springframework.data.domain.Pageable; <%_ } _%> <%_ if (reactive) { _%> @@ -42,18 +42,18 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; <%_ } _%> -<%_ if (pagination === 'no' || fieldsContainNoOwnerOneToOne === true) { _%> +<%_ if (paginationNo || fieldsContainNoOwnerOneToOne) { _%> import java.util.List; <%_ } _%> <%_ if (!reactive) { _%> import java.util.Optional; <%_ } _%> -<%_ if (primaryKey.type === 'UUID') { _%> +<%_ if (primaryKey.hasUUID) { _%> import java.util.UUID; <%_ } _%> /** - * Service Interface for managing {@link <% if (dto === 'mapstruct') { %><%= packageName %>.domain.<% } %><%= persistClass %>}. + * Service Interface for managing {@link <% if (dtoMapstruct) { %><%= packageName %>.domain.<% } %><%= persistClass %>}. */ public interface <%= entityClass %>Service { @@ -75,12 +75,13 @@ public interface <%= entityClass %>Service { /** * Get all the <%= entityInstancePlural %>. - *<% if (pagination !== 'no') { %> + *<% if (!paginationNo) { %> * @param pageable the pagination information.<% } %> * @return the list of entities. */ - <% if (pagination !== 'no') { %><%= pageOrFlux %><<%= instanceType %><% } else { %><%= listOrFlux %><<%= instanceType %><% } %>> findAll(<% if (pagination !== 'no') { %>Pageable pageable<% } %>); -<% for (const relationship of relationships) { if (relationship.relationshipType === 'one-to-one' && relationship.ownerSide !== true) { -%> + <% if (!paginationNo) { %><%= pageOrFlux %><<%= instanceType %><% } else { %><%= listOrFlux %><<%= instanceType %><% } %>> findAll(<% if (!paginationNo) { %>Pageable pageable<% } %>); +<%_ for (const relationship of relationships) { _%> + <%_ if (relationship.relationshipOneToOne && !relationship.ownerSide) { _%> /** * Get all the <%= restClass %> where <%= relationship.relationshipNameCapitalized %> is {@code null}. * @@ -89,7 +90,7 @@ public interface <%= entityClass %>Service { <%= listOrFlux %><<%= instanceType %>> findAllWhere<%= relationship.relationshipNameCapitalized %>IsNull(); <%_ } } _%> - <%_ if (relationshipsContainEagerLoad) { _%> +<%_ if (relationshipsContainEagerLoad) { _%> /** * Get all the <%= entityInstancePlural %> with eager load of many-to-many relationships. * @@ -98,7 +99,7 @@ public interface <%= entityClass %>Service { */ <%= pageOrFlux %><<%= instanceType %>> findAllWithEagerRelationships(Pageable pageable); - <%_ } _%> +<%_ } _%> <%_ if (reactive) { _%> /** * Returns the number of <%= entityInstancePlural %> available. @@ -106,14 +107,14 @@ public interface <%= entityClass %>Service { * */ Mono countAll(); - <%_ if (searchEngine === 'elasticsearch') { _%> + <%_ if (searchEngineElasticsearch) { _%> /** * Returns the number of <%= entityInstancePlural %> available in search repository. * */ Mono searchCount(); - <%_ } _%> + <%_ } _%> <%_ } _%> @@ -133,15 +134,17 @@ public interface <%= entityClass %>Service { * @return a Mono to signal the deletion <%_ } _%> */ - <%- reactive ? 'Mono' : 'void' %> delete(<%= primaryKey.type %> id);<% if (searchEngine !== false) { %> + <%- reactive ? 'Mono' : 'void' %> delete(<%= primaryKey.type %> id);<% if (searchEngine) { %> /** * Search for the <%= entityInstance %> corresponding to the query. * * @param query the query of the search. - * <% if (pagination !== 'no') { %> - * @param pageable the pagination information.<% } %> +<%_ if (!paginationNo) { _%> + * + * @param pageable the pagination information. +<%_ } _%> * @return the list of entities. */ - <% if (pagination !== 'no') { %><%= pageOrFlux %><<%= instanceType %><% } else { %><%= listOrFlux %><<%= instanceType %><% } %>> search(String query<% if (pagination !== 'no') { %>, Pageable pageable<% } %>);<% } %> + <% if (!paginationNo) { %><%= pageOrFlux %><<%= instanceType %><% } else { %><%= listOrFlux %><<%= instanceType %><% } %>> search(String query<% if (!paginationNo) { %>, Pageable pageable<% } %>);<% } %> } diff --git a/generators/entity-server/templates/src/main/java/package/service/criteria/EntityCriteria.java.ejs b/generators/entity-server/templates/src/main/java/package/service/criteria/EntityCriteria.java.ejs index 06ffbf87e99..d5ae09b881e 100644 --- a/generators/entity-server/templates/src/main/java/package/service/criteria/EntityCriteria.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/criteria/EntityCriteria.java.ejs @@ -25,7 +25,7 @@ import tech.jhipster.service.filter.InstantFilter; <%_ if (fieldsContainLocalDate === true) { _%> import tech.jhipster.service.filter.LocalDateFilter; <%_ } _%> -<%_ if (fieldsContainUUID === true || otherEntityPrimaryKeyTypes.includes('UUID')) { _%> +<%_ if (fieldsContainUUID === true || otherEntityPrimaryKeyTypesIncludesUUID) { _%> import tech.jhipster.service.filter.UUIDFilter; <%_ } _%> <%_ if (fieldsContainZonedDateTime === true) { _%> @@ -36,35 +36,35 @@ import tech.jhipster.service.filter.ZonedDateTimeFilter; var filterVariables = []; var extraFilters = {}; fields.forEach((field) => { -const fieldType = field.fieldType; -if (isFilterableType(fieldType)) { + const fieldType = field.fieldType; + if (isFilterableType(fieldType)) { var filterType; - if (field.fieldIsEnum == true) { - filterType = fieldType + 'Filter'; - extraFilters[fieldType] = {type: filterType, superType: 'Filter<' + fieldType + '>', fieldType: fieldType}; - } else if (['Duration', 'UUID', 'LocalDate', 'ZonedDateTime', 'Instant', 'String', 'Long', 'Integer', 'Float', 'Double', 'BigDecimal', 'Boolean'].includes(fieldType)) { - filterType = fieldType + 'Filter'; + if (field.fieldIsEnum) { + filterType = fieldType + 'Filter'; + extraFilters[fieldType] = {type: filterType, superType: 'Filter<' + fieldType + '>', fieldType: fieldType}; + } else if (field.fieldTypeDuration || field.fieldTypeTemporal || field.fieldTypeCharSequence || field.fieldTypeNumeric || field.fieldTypeBoolean) { + filterType = fieldType + 'Filter'; } else { - filterType = 'Filter<' + fieldType + '>'; + filterType = 'Filter<' + fieldType + '>'; } filterVariables.push( { filterType : filterType, - name: field.fieldName, - type: fieldType, - fieldInJavaBeanMethod: field.fieldInJavaBeanMethod }); -} + name: field.fieldName, + type: fieldType, + fieldInJavaBeanMethod: field.fieldInJavaBeanMethod }); + } }); relationships.forEach((relationship) => { const relationshipType = relationship.otherEntity.primaryKey.type; const referenceFilterType = '' + relationshipType + 'Filter'; // user has a String PK when using OAuth, so change relationships accordingly let oauthAwareReferenceFilterType = referenceFilterType; -if (relationship.otherEntityName === 'user' && authenticationType === 'oauth2') { - oauthAwareReferenceFilterType = 'StringFilter'; +if (relationship.otherEntityUser && authenticationTypeOauth2) { + oauthAwareReferenceFilterType = 'StringFilter'; } filterVariables.push({ filterType : oauthAwareReferenceFilterType, - name: relationship.relationshipFieldName + 'Id', - type: relationshipType, - fieldInJavaBeanMethod: relationship.relationshipNameCapitalized + 'Id' }); + name: relationship.relationshipFieldName + 'Id', + type: relationshipType, + fieldInJavaBeanMethod: relationship.relationshipNameCapitalized + 'Id' }); }); _%> /** @@ -78,7 +78,7 @@ _%> */ public class <%= entityClass %>Criteria implements Serializable, Criteria { <%_ Object.keys(extraFilters).forEach((key) => { - extraFilter = extraFilters[key]; _%> + extraFilter = extraFilters[key]; _%> /** * Class for filtering <%= key %> */ @@ -148,11 +148,11 @@ public class <%= entityClass %>Criteria implements Serializable, Criteria { final <%= entityClass %>Criteria that = (<%= entityClass %>Criteria) o; return <%_ filterVariables.forEach((filterVariable, index) => { _%> - <%_ if (filterVariables.length === index + 1) { _%> + <%_ if (filterVariables.length === index + 1) { _%> Objects.equals(<%= filterVariable.name %>, that.<%= filterVariable.name %>); - <%_ } else { _%> + <%_ } else { _%> Objects.equals(<%= filterVariable.name %>, that.<%= filterVariable.name %>) && - <%_ } _%> + <%_ } _%> <%_ }); _%> } @@ -160,11 +160,11 @@ public class <%= entityClass %>Criteria implements Serializable, Criteria { public int hashCode() { return Objects.hash( <%_ filterVariables.forEach((filterVariable, index) => { _%> - <%_ if (filterVariables.length === (index + 1)) { _%> + <%_ if (filterVariables.length === (index + 1)) { _%> <%= filterVariable.name %> - <%_ } else { _%> + <%_ } else { _%> <%= filterVariable.name %>, - <%_ } _%> + <%_ } _%> <%_ }); _%> ); } diff --git a/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs b/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs index 519d78ce048..e3348f25f38 100644 --- a/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs @@ -21,7 +21,7 @@ package <%= packageName %>.service.dto; import java.util.Objects; <%_ if (typeof javadoc != 'undefined') { _%> import io.swagger.annotations.ApiModel; -<%_ } if (importApiModelProperty === true) { _%> +<%_ } if (importApiModelProperty) { _%> import io.swagger.annotations.ApiModelProperty; <%_ } _%> <%_ if (fieldsContainInstant) { _%> @@ -43,17 +43,17 @@ import java.io.Serializable; <%_ if (fieldsContainBigDecimal) { _%> import java.math.BigDecimal; <%_ } _%> -<%_ if (fieldsContainBlob && databaseType === 'cassandra') { _%> +<%_ if (fieldsContainBlob && databaseTypeCassandra) { _%> import java.nio.ByteBuffer; <%_ } _%> <%_ if (dtoReferences.some(reference => reference.collection)) { _%> import java.util.HashSet; import java.util.Set; <%_ } _%> -<%_ if (fieldsContainUUID === true) { _%> +<%_ if (fieldsContainUUID) { _%> import java.util.UUID; <%_ } _%> -<%_ if (fieldsContainBlob && databaseType === 'sql') { _%> +<%_ if (fieldsContainBlob && databaseTypeSql) { _%> import javax.persistence.Lob; <%_ } _%> <%_ Object.keys(uniqueEnums).forEach(function(element) { _%> @@ -69,66 +69,64 @@ import <%= packageName %>.domain.enumeration.<%= element %>; public class <%= dtoClass %> implements Serializable { <%_ for (reference of dtoReferences) { - if (typeof reference.doc !== 'undefined') { + if (typeof reference.doc !== 'undefined') { _%> <%- formatAsFieldJavadoc(reference.doc) %> - <%_ } - const field = reference.field; - const required = field && field.fieldValidate && field.fieldValidateRules.includes('required'); - if (field) { - if (field.fieldValidate === true) { - _%> + <%_ } + const field = reference.field; + const required = field && field.fieldValidate && field.fieldValidationRequired; + if (field) { + if (field.fieldValidate ) { _%> <%- include('../../common/field_validators', {field, reactive}); -%> - <%_ } - } - _%> - <%_ if (reference.doc) { _%> + <%_ } + } _%> + <%_ if (reference.doc) { _%> @ApiModelProperty(value = "<%- formatAsApiDescription(reference.doc) %>"<% if (required) { %>, required = true<% } %>) - <%_ } _%> - <%_ if (reference.type === 'byte[]' && databaseType === 'sql') { _%> + <%_ } _%> + <%_ if (field && field.fieldTypeBytes && databaseTypeSql) { _%> @Lob - <%_ } _%> - <%_ if (reference.field && reference.field.fieldTypeBlobContent === 'text') { _%> + <%_ } _%> + <%_ if (field && field.blobContentTypeText) { _%> private String <%= reference.name %>; - <%_ } else if (reference.collection && reference.relationship) { _%> + <%_ } else if (reference.collection && reference.relationship) { _%> private Set<<%= asDto(reference.relationship.otherEntity.entityNameCapitalized) %>> <%= reference.name %> = new HashSet<>(); - <%_ } else if (reference.relationship) { _%> + <%_ } else if (reference.relationship) { _%> private <%= asDto(reference.relationship.otherEntity.entityNameCapitalized) %> <%= reference.name %>; - <%_ } else { _%> + <%_ } else { _%> private <%= reference.type %> <%= reference.name %>; - <%_ } _%> + <%_ } _%> - <%_ if (reference.field && reference.field.fieldWithContentType) { _%> + <%_ if (reference.field && reference.field.fieldWithContentType) { _%> private String <%= reference.name %>ContentType; -<%_ } - } + <%_ } +} _%> <%_ for (reference of dtoReferences) { _%> - <%_ if (reference.field && reference.field.fieldTypeBlobContent === 'text') { _%> + <%_ if (reference.field && reference.field.blobContentTypeText) { _%> public <%= buildJavaGetter(reference, 'String') %> { - <%_ } else if (reference.collection && reference.relationship) { _%> + <%_ } else if (reference.collection && reference.relationship) { _%> public <%- buildJavaGetter(reference, `Set<${ asDto(reference.relationship.otherEntity.entityNameCapitalized) }>` ) %> { - <%_ } else if (reference.relationship) { _%> + <%_ } else if (reference.relationship) { _%> public <%= buildJavaGetter(reference, asDto(reference.relationship.otherEntity.entityNameCapitalized)) %> { - <%_ } else { _%> + <%_ } else { _%> public <%= buildJavaGetter(reference) %> { - <%_ } _%> + <%_ } _%> return <%= reference.name %>; } - <%_ if (reference.field && reference.field.fieldTypeBlobContent === 'text') { _%> + <%_ if (reference.field && reference.field.blobContentTypeText) { _%> public void <%= buildJavaSetter(reference, `String ${reference.name}`) %> { - <%_ } else if (reference.collection && reference.relationship) { _%> + <%_ } else if (reference.collection && reference.relationship) { _%> public void <%- buildJavaSetter(reference, `Set<${ asDto(reference.relationship.otherEntity.entityNameCapitalized) }> ${reference.name}`) %> { - <%_ } else if (reference.relationship) { _%> + <%_ } else if (reference.relationship) { _%> public void <%= buildJavaSetter(reference, `${ asDto(reference.relationship.otherEntity.entityNameCapitalized) } ${reference.name}`) %> { - <%_ } else { _%> + <%_ } else { _%> public void <%= buildJavaSetter(reference) %> { - <%_ } _%> + <%_ } _%> this.<%= reference.name %> = <%= reference.name %>; } - <%_ if (reference.field && reference.field.fieldWithContentType) { _%> + <%_ if (reference.field && reference.field.fieldWithContentType) { _%> public String get<%= javaBeanCase(reference.name) %>ContentType() { return <%= reference.name %>ContentType; @@ -137,7 +135,7 @@ _%> public void set<%= javaBeanCase(reference.name) %>ContentType(String <%= reference.name %>ContentType) { this.<%= reference.name %>ContentType = <%= reference.name %>ContentType; } - <%_ } _%> + <%_ } _%> <%_ } _%> <%_ const idNames = primaryKey ? [...primaryKey.fields.map(f => f.fieldName)] : [] _%> @@ -150,34 +148,34 @@ _%> return false; } - <%_ if (!embedded) { _%> +<%_ if (!embedded) { _%> <%= dtoClass %> <%= dtoInstance %> = (<%= dtoClass %>) o; if (<%- idNames.map(n => `this.${n} == null`).join(' && ') %>){ return false; } return <%- idNames.map(n => `Objects.equals(this.${n}, ${dtoInstance}.${n})`).join(' &&\n ') %>; - <%_ } else { _%> +<%_ } else { _%> return false; - <%_ } _%> +<%_ } _%> } @Override public int hashCode() { - <%_ if (!embedded) { _%> +<%_ if (!embedded) { _%> return Objects.hash(<%- idNames.map(n => `this.${n}`).join(', ') %>); - <%_ } else { _%> +<%_ } else { _%> return getClass().hashCode(); - <%_ } _%> +<%_ } _%> } // prettier-ignore @Override public String toString() { return "<%= dtoClass %>{" + - <%_ for ([idx, reference] of dtoReferences.entries()) { - const isNumeric = reference.type && ['integer', 'long', 'float', 'double', 'bigdecimal'].includes(reference.type.toLowerCase()); _%> - "<%= idx === 0 ? '' : ', ' %><%= reference.name %>=<% if (! isNumeric) { %>'<% } %>" + <%= buildJavaGet(reference) %> <% if (! isNumeric) { %>+ "'" <% } %>+ - <%_ } _%> +<%_ for ([idx, reference] of dtoReferences.entries()) { + const isNumeric = (reference.field && reference.field.fieldTypeNumeric) || (reference.relationship && reference.relationship.relatedField && reference.relationship.relatedField.fieldTypeNumeric)_%> + "<%= idx === 0 ? '' : ', ' %><%= reference.name %>=<% if (!isNumeric) { %>'<% } %>" + <%= buildJavaGet(reference) %> <% if (! isNumeric) { %>+ "'" <% } %>+ +<%_ } _%> "}"; } } diff --git a/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs b/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs index 3a92e90b309..dc2a21f7dde 100644 --- a/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs @@ -16,15 +16,15 @@ See the License for the specific language governing permissions and limitations under the License. -%> -package <%= packageName %>.service<% if (service === 'serviceImpl') { %>.impl<% } %>; +package <%= packageName %>.service<% if (serviceImpl) { %>.impl<% } %>; <%_ -const serviceClassName = service === 'serviceImpl' ? entityClass + 'ServiceImpl' : entityClass + 'Service'; +const serviceClassName = serviceImpl ? entityClass + 'ServiceImpl' : entityClass + 'Service'; const instanceType = restClass; const instanceName = restInstance; -const optionalOrMono = (reactive === true) ? 'Mono' : 'Optional'; -const listOrFlux = (reactive === true) ? 'Flux' : 'List'; -const pageOrFlux = (reactive === true) ? 'Flux' : 'Page'; +const optionalOrMono = (reactive) ? 'Mono' : 'Optional'; +const listOrFlux = (reactive) ? 'Flux' : 'List'; +const pageOrFlux = (reactive) ? 'Flux' : 'Page'; const mapper = entityInstance + 'Mapper'; const dtoToEntity = mapper + '.'+ 'toEntity'; const entityToDto = 'toDto'; @@ -33,7 +33,7 @@ const repository = entityInstance + 'Repository'; const searchRepository = entityInstance + 'SearchRepository'; _%> -<%_ if (service === 'serviceImpl') { _%> +<%_ if (serviceImpl) { _%> import <%= packageName %>.service.<%= entityClass %>Service; <%_ } _%> import <%= packageName %>.domain.<%= persistClass %>; @@ -41,24 +41,24 @@ import <%= packageName %>.repository.<%= entityClass %>Repository; <%_ if (isUsingMapsId === true) { _%> import <%= packageName %>.repository.<%= mapsIdAssoc.otherEntityNameCapitalized %>Repository; <%_ } _%> -<%_ if (searchEngine === 'elasticsearch') { _%> +<%_ if (searchEngineElasticsearch) { _%> import <%= packageName %>.repository.search.<%= entityClass %>SearchRepository; <%_ } _%> -<%_ if (dto === 'mapstruct') { _%> +<%_ if (dtoMapstruct) { _%> import <%= packageName %>.service.dto.<%= dtoClass %>; import <%= packageName %>.service.mapper.<%= entityClass %>Mapper; <%_ } _%> import org.slf4j.Logger; import org.slf4j.LoggerFactory; -<%_ if (pagination !== 'no' || relationshipsContainEagerLoad) { _%> - <%_ if (!reactive) { _%> +<%_ if (!paginationNo || relationshipsContainEagerLoad) { _%> + <%_ if (!reactive) { _%> import org.springframework.data.domain.Page; - <%_ } _%> + <%_ } _%> import org.springframework.data.domain.Pageable; <%_ } _%> import org.springframework.stereotype.Service; -<%_ if (databaseType === 'sql') { _%> +<%_ if (databaseTypeSql) { _%> import org.springframework.transaction.annotation.Transactional; <%_ } _%> <%_ if (reactive) { _%> @@ -66,25 +66,25 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; <%_ } _%> -<%_ if (dto === 'mapstruct' && (pagination === 'no' ||  fieldsContainNoOwnerOneToOne === true)) { _%> +<%_ if (dtoMapstruct && (paginationNo || fieldsContainNoOwnerOneToOne)) { _%> import java.util.LinkedList; <%_ } _%> -<%_ if (pagination === 'no' ||  fieldsContainNoOwnerOneToOne === true) { _%> +<%_ if (paginationNo || fieldsContainNoOwnerOneToOne) { _%> import java.util.List; <%_ } _%> <%_ if (!reactive) { _%> import java.util.Optional; <%_ } _%> -<%_ if (primaryKey.type === 'UUID') { _%> +<%_ if (primaryKey.hasUUID) { _%> import java.util.UUID; <%_ } _%> -<%_ if (fieldsContainNoOwnerOneToOne === true || (pagination === 'no' && ((searchEngine !== false) || dto === 'mapstruct'))) { _%> +<%_ if (fieldsContainNoOwnerOneToOne || (paginationNo && ((searchEngine) || dtoMapstruct))) { _%> import java.util.stream.Collectors; <%_ } _%> -<%_ if (fieldsContainNoOwnerOneToOne === true || (pagination === 'no' && searchEngine === 'elasticsearch')) { _%> +<%_ if (fieldsContainNoOwnerOneToOne || (paginationNo && searchEngineElasticsearch)) { _%> import java.util.stream.StreamSupport; <%_ } _%> -<%_ if (searchEngine === 'elasticsearch') { _%> +<%_ if (searchEngineElasticsearch) { _%> import static org.elasticsearch.index.query.QueryBuilders.*; <%_ } _%> @@ -92,99 +92,101 @@ import static org.elasticsearch.index.query.QueryBuilders.*; /** * Service Implementation for managing {@link <%= persistClass %>}. */ -@Service<% if (databaseType === 'sql') { %> +@Service<% if (databaseTypeSql) { %> @Transactional<% } %> -public class <%= serviceClassName %><% if (service === 'serviceImpl') { %> implements <%= entityClass %>Service<% } %> { +public class <%= serviceClassName %><% if (serviceImpl) { %> implements <%= entityClass %>Service<% } %> { private final Logger log = LoggerFactory.getLogger(<%= serviceClassName %>.class); <%- include('../../common/inject_template', {asEntity, asDto, viaService: false, constructorName: serviceClassName, queryService: false, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: false}); -%> - <%_ if (service !== 'serviceImpl') { _%> +<%_ if (!serviceImpl) { _%> /** * Save a <%= entityInstance %>. * * @param <%= instanceName %> the entity to save. * @return the persisted entity. */ - <%_ } _%> - <%_ if (service === 'serviceImpl') { _%> +<%_ } _%> +<%_ if (serviceImpl) { _%> @Override - <%_ } _%> +<%_ } _%> public <% if (reactive) { %>Mono<<% } %><%= instanceType %><% if (reactive) { %>><% } %> save(<%= instanceType %> <%= instanceName %>) { log.debug("Request to save <%= entityClass %> : {}", <%= instanceName %>); <%- include('/partials/save_template', {asEntity, asDto, viaService: false, returnDirectly: true, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: false}); -%> } - <%_ if (service !== 'serviceImpl') { _%> +<%_ if (!serviceImpl) { _%> /** * Partially update a <%= entityInstance %>. * * @param <%= instanceName %> the entity to update partially. * @return the persisted entity. */ - <%_ } _%> - <%_ if (service === 'serviceImpl') { _%> +<%_ } _%> +<%_ if (serviceImpl) { _%> @Override - <%_ } _%> +<%_ } _%> public <% if (!reactive) { %>Optional<<% } %><% if (reactive) { %>Mono<<% } %><%= instanceType %>> partialUpdate(<%= instanceType %> <%= instanceName %>) { log.debug("Request to partially update <%= entityClass %> : {}", <%= instanceName %>); <%- include('../../common/patch_template', {asEntity, asDto, isService: true, viaService: false}); -%> } - <%_ if (service !== 'serviceImpl') { _%> +<%_ if (!serviceImpl) { _%> /** * Get all the <%= entityInstancePlural %>. - *<% if (pagination !== 'no') { %> - * @param pageable the pagination information.<% } %> + * + <%_ if (!paginationNo) { _%> + * @param pageable the pagination information. + <%_ } _%> * @return the list of entities. */ - <%_ } _%> - <%_ if (service === 'serviceImpl') { _%> +<%_ } _%> +<%_ if (serviceImpl) { _%> @Override - <%_ } _%> - <%_ if (databaseType === 'sql') { _%> +<%_ } _%> +<%_ if (databaseTypeSql) { _%> @Transactional(readOnly = true) - <%_ } _%> - public <% if (pagination !== 'no') { %><%= pageOrFlux %><<%= instanceType %><% } else { %><%= listOrFlux %><<%= instanceType %><% } %>> findAll(<% if (pagination !== 'no') { %>Pageable pageable<% } %>) { +<%_ } _%> + public <% if (!paginationNo) { %><%= pageOrFlux %><<%= instanceType %><% } else { %><%= listOrFlux %><<%= instanceType %><% } %>> findAll(<% if (!paginationNo) { %>Pageable pageable<% } %>) { log.debug("Request to get all <%= entityClassPlural %>"); - <%_ if (pagination === 'no') { _%> - return <%= entityInstance %>Repository.<% if (relationshipsContainEagerLoad) { %>findAllWithEagerRelationships<% } else { %>findAll<% } %>()<% if (dto === 'mapstruct') { %><% if (!reactive) { %>.stream()<% } %> +<%_ if (paginationNo) { _%> + return <%= entityInstance %>Repository.<% if (relationshipsContainEagerLoad) { %>findAllWithEagerRelationships<% } else { %>findAll<% } %>()<% if (dtoMapstruct) { %><% if (!reactive) { %>.stream()<% } %> .map(<%= entityToDtoReference %>)<% if (!reactive) { %> .collect(Collectors.toCollection(LinkedList::new))<% } } %>; - <%_ } else { _%> +<%_ } else { _%> return <%= entityInstance %>Repository.findAll<% if (reactive) { %>By<% } %>(pageable)<% if (dto !== 'mapstruct') { %>;<% } else { %> .map(<%= entityToDtoReference %>);<% } %> - <%_ } _%> +<%_ } _%> } - <%_ if (relationshipsContainEagerLoad) { _%> +<%_ if (relationshipsContainEagerLoad) { _%> - <%_ if (service !== 'serviceImpl') { _%> + <%_ if (!serviceImpl) { _%> /** * Get all the <%= entityInstancePlural %> with eager load of many-to-many relationships. * * @return the list of entities. */ - <%_ } _%> + <%_ } _%> public <%= pageOrFlux %><<%= instanceType %>> findAllWithEagerRelationships(Pageable pageable) { - return <%= entityInstance %>Repository.findAllWithEagerRelationships(pageable)<% if (dto !== 'mapstruct') { %>;<% } else { %>.map(<%= entityToDtoReference %>);<% } %> + return <%= entityInstance %>Repository.findAllWithEagerRelationships(pageable)<% if (!dtoMapstruct) { %>;<% } else { %>.map(<%= entityToDtoReference %>);<% } %> } - <%_ } _%> +<%_ } _%> <%- include('../../common/get_filtered_template', {asEntity, asDto}); -%> <%_ if (reactive) { _%> - <%_ if (service !== 'serviceImpl') { _%> + <%_ if (!serviceImpl) { _%> /** * Returns the number of <%= entityInstancePlural %> available. * @return the number of entities in the database. * */ - <%_ } _%> + <%_ } _%> public Mono countAll() { return <%= entityInstance %>Repository.count(); } - <%_ if (searchEngine === 'elasticsearch') { _%> + <%_ if (searchEngineElasticsearch) { _%> - <%_ if (service !== 'serviceImpl') { _%> + <%_ if (!serviceImpl) { _%> /** * Returns the number of <%= entityInstancePlural %> available in search repository. * @@ -193,69 +195,71 @@ public class <%= serviceClassName %><% if (service === 'serviceImpl') { %> imple public Mono searchCount() { return <%= entityInstance %>SearchRepository.count(); } - <%_ } _%> + <%_ } _%> <%_ } _%> - <%_ if (service !== 'serviceImpl') { _%> +<%_ if (!serviceImpl) { _%> /** * Get one <%= entityInstance %> by id. * * @param id the id of the entity. * @return the entity. */ - <%_ } _%> - <%_ if (service === 'serviceImpl') { _%> +<%_ } _%> +<%_ if (serviceImpl) { _%> @Override - <%_ } _%> - <%_ if (databaseType === 'sql') { _%> +<%_ } _%> +<%_ if (databaseTypeSql) { _%> @Transactional(readOnly = true) <%_ } _%> public <%= optionalOrMono %><<%= instanceType %>> findOne(<%= primaryKey.type %> id) { log.debug("Request to get <%= entityClass %> : {}", id);<%- include('../../common/get_template', {asEntity, asDto, viaService: false, returnDirectly:true}); -%> } - <%_ if (service !== 'serviceImpl') { _%> +<%_ if (!serviceImpl) { _%> /** * Delete the <%= entityInstance %> by id. * * @param id the id of the entity. -<%_ if (reactive) { _%> + <%_ if (reactive) { _%> * @return a Mono to signal the deletion -<%_ } _%> + <%_ } _%> */ - <%_ } _%> - <%_ if (service === 'serviceImpl') { _%> +<%_ } _%> +<%_ if (serviceImpl) { _%> @Override - <%_ } _%> +<%_ } _%> public <%- reactive ? 'Mono' : 'void' %> delete(<%= primaryKey.type %> id) { log.debug("Request to delete <%= entityClass %> : {}", id); <%- include('../../common/delete_template', {viaService: false, fromResource: false}); -%> } - <%_ if (searchEngine !== false) { _%> +<%_ if (searchEngine) { _%> - <%_ if (service !== 'serviceImpl') { _%> + <%_ if (!serviceImpl) { _%> /** * Search for the <%= entityInstance %> corresponding to the query. * - * @param query the query of the search.<% if (pagination !== 'no') { %> - * @param pageable the pagination information.<% } %> + * @param query the query of the search. + <%_ if (!paginationNo) { _%> + * @param pageable the pagination information. + <%_ } _%> * @return the list of entities. */ - <%_ } _%> - <%_ if (service === 'serviceImpl') { _%> + <%_ } _%> + <%_ if (serviceImpl) { _%> @Override - <%_ } _%> - <%_ if (databaseType === 'sql') { _%> + <%_ } _%> + <%_ if (databaseTypeSql) { _%> @Transactional(readOnly = true) - <%_ } _%> - public <% if (pagination !== 'no') { %><%= pageOrFlux %><<%= instanceType %><% } else { %><%= listOrFlux %><<%= instanceType %><% } %>> search(String query<% if (pagination !== 'no') { %>, Pageable pageable<% } %>) { - <%_ if (pagination === 'no') { _%> + <%_ } _%> + public <% if (!paginationNo) { %><%= pageOrFlux %><<%= instanceType %><% } else { %><%= listOrFlux %><<%= instanceType %><% } %>> search(String query<% if (!paginationNo) { %>, Pageable pageable<% } %>) { + <%_ if (paginationNo) { _%> log.debug("Request to search <%= entityClassPlural %> for query {}", query);<%- include('../../common/search_stream_template', {viaService: false, fromResource: false}); -%> - <%_ } else { _%> + <%_ } else { _%> log.debug("Request to search for a page of <%= entityClassPlural %> for query {}", query); - return <%= entityInstance %><% if (searchEngine === 'elasticsearch') { %>Search<% } %>Repository.search(<% if (searchEngine === 'elasticsearch') { %><%= reactive ? 'query' : 'queryStringQuery(query)' %><% } else { %><%= entityClass %>.PREFIX, query<% } %>, pageable)<%_ if (dto !== 'mapstruct') { _%>;<% } else { %> + return <%= entityInstance %><% if (searchEngineElasticsearch) { %>Search<% } %>Repository.search(<% if (searchEngineElasticsearch) { %><%= reactive ? 'query' : 'queryStringQuery(query)' %><% } else { %><%= entityClass %>.PREFIX, query<% } %>, pageable)<%_ if (!dtoMapstruct) { _%>;<% } else { %> .map(<%= entityToDtoReference %>); - <%_ } } _%> + <%_ } } _%> } - <%_ } _%> +<%_ } _%> } diff --git a/generators/entity-server/templates/src/main/java/package/service/mapper/EntityMapper.java.ejs b/generators/entity-server/templates/src/main/java/package/service/mapper/EntityMapper.java.ejs index 1e26662ecf3..2c95ea9c9f0 100644 --- a/generators/entity-server/templates/src/main/java/package/service/mapper/EntityMapper.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/mapper/EntityMapper.java.ejs @@ -20,8 +20,8 @@ package <%= packageName %>.service.mapper; <%_ let existingMappings = []; -let uuidMapMethod = dtoReferences.some(reference => reference.valueReference && reference.valueReference.field && reference.valueReference.field.fieldType === 'UUID'); -let byteMapMethod = dtoReferences.some(reference => reference.valueReference && reference.valueReference.field && reference.valueReference.field.fieldType === 'byte[]'); +let uuidMapMethod = dtoReferences.some(reference => reference.valueReference && reference.valueReference.field && reference.valueReference.field.fieldTypeUUID); +let byteMapMethod = dtoReferences.some(reference => reference.valueReference && reference.valueReference.field && reference.valueReference.field.fieldTypeBytes); for (reference of dtoReferences) { // if the entity is mapped twice, we should implement the mapping once if (reference.relationship && !reference.relationship.otherEntity.embedded && !existingMappings.includes(reference.name) && asEntity(reference.relationship.otherEntityNameCapitalized) !== persistClass) { @@ -33,7 +33,7 @@ _%> <%_ if (dtoReferences.some(r => r.relationship && r.relationship.otherRelationship && r.relationship.otherRelationship.reference.collection && - r.relationship.relationshipType === 'many-to-many' + r.relationship.relationshipManyToMany ) || otherDtoReferences.some(r => r.collection)) { _%> import java.util.Set; <%_ } _%> @@ -54,108 +54,108 @@ import java.util.UUID; @Mapper(componentModel = "spring", uses = {<%= [...new Set(existingMappings.map(otherEntityNameCapitalized => otherEntityNameCapitalized + 'Mapper.class'))].join(', ') %>}) public interface <%= entityClass %>Mapper extends EntityMapper<<%= dtoClass %>, <%= persistClass %>> { <%_ /***** Basic dto mapping *****/ - if (!embedded) { - var renMapAnotEnt = false; //Render Mapping Annotation during Entity to DTO conversion? - for (reference of dtoReferences.filter(reference => reference.relationship && !reference.relationship.otherEntity.embedded)) { - renMapAnotEnt = true; - let qualifiedByName = reference.relationship.otherEntityField; - qualifiedByName = qualifiedByName + (reference.collection ? 'Set' : ''); _%> + if (!embedded) { + var renMapAnotEnt = false; //Render Mapping Annotation during Entity to DTO conversion? + for (reference of dtoReferences.filter(reference => reference.relationship && !reference.relationship.otherEntity.embedded)) { + renMapAnotEnt = true; + let qualifiedByName = reference.relationship.otherEntityField; + qualifiedByName = qualifiedByName + (reference.collection ? 'Set' : ''); _%> @Mapping(target = "<%= reference.name %>", source = "<%= reference.name %>", qualifiedByName="<%= qualifiedByName %>") <%_ } _%> <%_ for (reference of dtoReferences.filter(reference => reference.field && reference.field.mapstructExpression)) { - renMapAnotEnt = true; _%> + renMapAnotEnt = true; _%> @Mapping( target = "<%= reference.name %>", expression = "<%- reference.field.mapstructExpression %>") <%_ } _%> - <%_ if (renMapAnotEnt === true) { _%> + <%_ if (renMapAnotEnt) { _%> <%= dtoClass %> toDto(<%= persistClass %> s); <%_ } %> <%_ } %> <%_ /***** Id mapping *****/ - const otherIdReferences = otherDtoReferences.filter(r => !r.relatedReference || r.relatedReference.id); - if (!embedded && otherIdReferences.length > 0) { - if (otherIdReferences.some(r => !r.collection)) { _%> +const otherIdReferences = otherDtoReferences.filter(r => !r.relatedReference || r.relatedReference.id); +if (!embedded && otherIdReferences.length > 0) { + if (otherIdReferences.some(r => !r.collection)) { _%> @Named("<%= primaryKey.name %>") @BeanMapping(ignoreByDefault = true) - <%_ let renMapAnotEnt = false; //Render Mapping Annotation during Entity to DTO conversion? - for (reference of dtoReferences.filter(reference => reference.id)) { - renMapAnotEnt = true; _%> + <%_ let renMapAnotEnt = false; //Render Mapping Annotation during Entity to DTO conversion? + for (reference of dtoReferences.filter(reference => reference.id)) { + renMapAnotEnt = true; _%> @Mapping(target = "<%= reference.name %>", source = "<%= reference.name %>") - <%_ } _%> - <%_ if (renMapAnotEnt === true) { _%> + <%_ } _%> + <%_ if (renMapAnotEnt) { _%> <%= dtoClass %> toDtoId(<%= persistClass %> <%= persistInstance %>); - <%_ } _%> <%_ } _%> - <%_ if (otherIdReferences.some(r => r.collection)) { _%> + <%_ } _%> + <%_ if (otherIdReferences.some(r => r.collection)) { _%> @Named("<%= primaryKey.name %>Set") @BeanMapping(ignoreByDefault = true) - <%_ let renMapAnotEnt = false; //Render Mapping Annotation during Entity to DTO conversion? - for (reference of dtoReferences.filter(reference => reference.id)) { - renMapAnotEnt = true; _%> + <%_ let renMapAnotEnt = false; //Render Mapping Annotation during Entity to DTO conversion? + for (reference of dtoReferences.filter(reference => reference.id)) { + renMapAnotEnt = true; _%> @Mapping(target = "<%= reference.name %>", source = "<%= reference.name %>") - <%_ } _%> - <%_ if (renMapAnotEnt === true) { _%> + <%_ } _%> + <%_ if (renMapAnotEnt === true) { _%> Set<<%= dtoClass %>> toDtoIdSet(Set<<%= persistClass %>> <%= persistInstance %>); - <%_ } _%> <%_ } _%> + <%_ } _%> <%_ } _%> <%_ if (!embedded) { // DTO -> entity mapping - var renMapAnotDto = false; //Render Mapping Annotation during DTO to Entity conversion? - if(primaryKey.ids.length > 1) { - renMapAnotDto = true; - primaryKey.ids.forEach(id => { _%> + var renMapAnotDto = false; //Render Mapping Annotation during DTO to Entity conversion? + if(primaryKey.ids.length > 1) { + renMapAnotDto = true; + primaryKey.ids.forEach(id => { _%> @Mapping(target = "id.<%= id.name %>", source = "<%= id.nameDotted %>") - <%_ }) - } - for (reference of dtoReferences.filter(reference => reference.relationship)) { - if (reference.owned === false) { - renMapAnotDto = true; _%> + <%_ }) + } + for (reference of dtoReferences.filter(reference => reference.relationship)) { + if (reference.owned === false) { + renMapAnotDto = true; _%> @Mapping(target = "<%= reference.name %>", ignore = true) - <%_ } - if (reference.collection && fluentMethods) { - renMapAnotDto = true; _%> + <%_ } + if (reference.collection && fluentMethods) { + renMapAnotDto = true; _%> @Mapping(target = "remove<%= reference.relationship.relationshipNameCapitalized %>", ignore = true) - <%_ } _%> <%_ } _%> - <%_ if (renMapAnotDto === true) { _%> + <%_ } _%> + <%_ if (renMapAnotDto) { _%> <%= persistClass %> toEntity(<%= dtoClass %> <%= dtoInstance %>); - <%_ } _%> - <%_ /***** Add filtered backreference *****/ - const addedMappers = []; - for (const otherReference of otherDtoReferences.filter(r => r.relatedReference && !r.relatedReference.id)) { - const reference = otherReference.relationship.otherRelationship && otherReference.relationship.otherRelationship.reference; - const collection = otherReference.collection; - const mapperName = otherReference.relationship.otherEntityField + (collection ? 'Set' : ''); - if (addedMappers.includes(mapperName)) continue; - addedMappers.push(mapperName); - const backReferenceDtoClass = collection ? `Set<${dtoClass}>` : dtoClass; - const backReferenceEntityClass = collection ? `Set<${persistClass}>` : persistClass; _%> + <%_ } _%> + <%_ /***** Add filtered backreference *****/ + const addedMappers = []; + for (const otherReference of otherDtoReferences.filter(r => r.relatedReference && !r.relatedReference.id)) { + const reference = otherReference.relationship.otherRelationship && otherReference.relationship.otherRelationship.reference; + const collection = otherReference.collection; + const mapperName = otherReference.relationship.otherEntityField + (collection ? 'Set' : ''); + if (addedMappers.includes(mapperName)) continue; + addedMappers.push(mapperName); + const backReferenceDtoClass = collection ? `Set<${dtoClass}>` : dtoClass; + const backReferenceEntityClass = collection ? `Set<${persistClass}>` : persistClass; _%> @Named("<%= mapperName %>") @BeanMapping(ignoreByDefault = true) - <%_ dtoReferences.filter(r => r.id && r != reference).forEach(r => { _%> + <%_ dtoReferences.filter(r => r.id && r != reference).forEach(r => { _%> @Mapping(target = "<%= r.name %>", source = "<%= r.name %>") - <%_ }); _%> - <%_ if (otherReference.relationship.relatedField && !otherReference.relationship.relatedField.id) { _%> + <%_ }); _%> + <%_ if (otherReference.relationship.relatedField && !otherReference.relationship.relatedField.id) { _%> @Mapping(target = "<%= otherReference.relationship.relatedField.reference.name %>", source = "<%= otherReference.relationship.relatedField.reference.name %>") - <%_ } _%> + <%_ } _%> <%- backReferenceDtoClass %> toDto<%= _.upperFirst(mapperName) %>(<%- backReferenceEntityClass %> <%= persistInstance %>); - <%_ }; _%> + <%_ } _%> - <%_ if (uuidMapMethod) { _%> + <%_ if (uuidMapMethod) { _%> default String map(UUID value) { return Objects.toString(value, null); } - <%_ } _%> - <%_ if (byteMapMethod) { _%> + <%_ } _%> + <%_ if (byteMapMethod) { _%> default String map(byte[] value) { return new String(value); } - <%_ } _%> + <%_ } _%> <%_ } _%> } diff --git a/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs b/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs index 8690a9f61b0..bdc44d1aa3d 100644 --- a/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/web/rest/EntityResource.java.ejs @@ -19,39 +19,39 @@ package <%= packageName %>.web.rest; <%_ -const viaService = service !== 'no'; +const viaService = !serviceNo; let manyToManyWithUser = false; for (const relationship of relationships) { - if (relationship.otherEntityName === 'user' && relationship.relationshipType === 'many-to-many') { - manyToManyWithUser = true; - break; - } + if (relationship.otherEntityUser && relationship.relationshipManyToMany) { + manyToManyWithUser = true; + break; + } } _%> -<%_ if (dto !== 'mapstruct' || service === 'no') { _%> +<%_ if (!dtoMapstruct || serviceNo) { _%> import <%= packageName %>.domain.<%= persistClass %>; <%_ } _%> import <%= packageName %>.repository.<%= entityClass %>Repository; -<%_ if (service !== 'no') { _%> +<%_ if (!serviceNo) { _%> import <%= packageName %>.service.<%= entityClass %>Service; <%_ } else { _%> - <%_ if (isUsingMapsId === true) { _%> + <%_ if (isUsingMapsId === true) { _%> import <%= packageName %>.repository.<%= mapsIdAssoc.otherEntityNameCapitalized %>Repository; - <%_ } _%> - <%_ if (searchEngine === 'elasticsearch') { _%> + <%_ } _%> + <%_ if (searchEngineElasticsearch) { _%> import <%= packageName %>.repository.search.<%= entityClass %>SearchRepository; - <%_ } _%> + <%_ } _%> <%_ } _%> <%_ if (saveUserSnapshot) { _%> import <%= packageName %>.repository.UserRepository; <%_ } _%> import <%= packageName %>.web.rest.errors.BadRequestAlertException; -<%_ if (dto === 'mapstruct') { _%> +<%_ if (dtoMapstruct) { _%> import <%= packageName %>.service.dto.<%= dtoClass %>; - <%_ if (service === 'no') { _%> + <%_ if (serviceNo) { _%> import <%= packageName %>.service.mapper.<%= entityClass %>Mapper; - <%_ } _%> + <%_ } _%> <%_ } _%> <%_ if (jpaMetamodelFiltering) { _%> import <%= packageName %>.service.criteria.<%= entityClass %>Criteria; @@ -59,29 +59,29 @@ import <%= packageName %>.service.<%= entityClass %>QueryService; <%_ } _%> import tech.jhipster.web.util.HeaderUtil; -<%_ if (pagination !== 'no') { _%> +<%_ if (!paginationNo) { _%> import tech.jhipster.web.util.PaginationUtil; <%_ } _%> import tech.jhipster.web.util.<% if (reactive) { %>reactive.<% } %>ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; -<%_ if (pagination !== 'no') { _%> +<%_ if (!paginationNo) { _%> import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; - <%_ if (reactive) { _%> + <%_ if (reactive) { _%> import org.springframework.data.domain.PageImpl; - <%_ } _%> + <%_ } _%> import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; - <%_ if (reactive) { _%> + <%_ if (reactive) { _%> import org.springframework.http.server.reactive.ServerHttpRequest; - <%_ } _%> - <%_ if (!reactive) { _%> + <%_ } _%> + <%_ if (!reactive) { _%> import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - <%_ } else { _%> + <%_ } else { _%> import org.springframework.web.util.UriComponentsBuilder; - <%_ } _%> + <%_ } _%> <%_ } else if (reactive) { _%> import org.springframework.http.HttpStatus; <%_ } _%> @@ -89,7 +89,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; <%_ } _%> import org.springframework.http.ResponseEntity; -<%_ if (databaseType === 'sql' && !viaService && (!saveUserSnapshot || isUsingMapsId === true)) { _%> +<%_ if (databaseTypeSql && !viaService && (!saveUserSnapshot || isUsingMapsId)) { _%> import org.springframework.transaction.annotation.Transactional; <%_ } _%> import org.springframework.web.bind.annotation.*; @@ -108,27 +108,27 @@ import javax.validation.constraints.NotNull; <%_ } _%> import java.net.URI; import java.net.URISyntaxException; -<%_ if (pagination === 'no' && dto === 'mapstruct' && !viaService && fieldsContainNoOwnerOneToOne === true) { _%> +<%_ if (paginationNo && dtoMapstruct && !viaService && fieldsContainNoOwnerOneToOne) { _%> import java.util.LinkedList; <%_ } _%> -<%_ if (pagination !== 'no' && reactive) { _%> +<%_ if (!paginationNo && reactive) { _%> import java.util.ArrayList; <%_ } _%> import java.util.List; import java.util.Objects; import java.util.Optional; -<%_ if (primaryKey.fields.some(f => f.fieldType === 'UUID')) { _%> +<%_ if (primaryKey.hasUUID) { _%> import java.util.UUID; <%_ } _%> -<%_ if ((searchEngine !== false || fieldsContainNoOwnerOneToOne === true) && !reactive) { _%> - <%_ if (!viaService) { _%> +<%_ if ((searchEngine || fieldsContainNoOwnerOneToOne) && !reactive) { _%> + <%_ if (!viaService) { _%> import java.util.stream.Collectors; - <%_ } _%> - <%_ if (databaseType !== 'sql' || !reactive) { _%> + <%_ } _%> + <%_ if (!databaseTypeSql || !reactive) { _%> import java.util.stream.StreamSupport; - <%_ } _%> + <%_ } _%> <%_ } _%> -<%_ if (searchEngine === 'elasticsearch' && !reactive) { _%> +<%_ if (searchEngineElasticsearch && !reactive) { _%> import static org.elasticsearch.index.query.QueryBuilders.*; <%_ } _%> @@ -138,7 +138,7 @@ import static org.elasticsearch.index.query.QueryBuilders.*; */ @RestController @RequestMapping("/api") -<%_ if (databaseType === 'sql' && !viaService && !saveUserSnapshot) { _%> +<%_ if (databaseTypeSql && !viaService && !saveUserSnapshot) { _%> @Transactional <%_ } _%> public class <%= entityClass %>Resource { @@ -146,10 +146,10 @@ public class <%= entityClass %>Resource { private final Logger log = LoggerFactory.getLogger(<%= entityClass %>Resource.class); <%_ if (!readOnly) { _%> - <%_ let entityName = entityInstance; - if (clientRootFolder && !skipUiGrouping) { - entityName = _.camelCase(`${clientRootFolder}${entityClass}`); - } _%> + <%_ let entityName = entityInstance; + if (clientRootFolder && !skipUiGrouping) { + entityName = _.camelCase(`${clientRootFolder}${entityClass}`); + } _%> private static final String ENTITY_NAME = "<%= entityName %>"; @Value("${jhipster.clientApp.name}") @@ -176,28 +176,28 @@ public class <%= entityClass %>Resource { if (<%= instanceName %>.get<%= primaryKey.nameCapitalized %>() != null) { throw new BadRequestAlertException("A new <%= entityInstance %> cannot already have an ID", ENTITY_NAME, "idexists"); } - <%_ if (saveUserSnapshot) { _%> - <%_ if (manyToManyWithUser) { _%> + <%_ if (saveUserSnapshot) { _%> + <%_ if (manyToManyWithUser) { _%> if (<%= instanceName %>.getUsers() != null) { // Save users in case they are new and only exists in gateway userRepository.saveAll(<%= instanceName %>.getUsers()); } - <%_ } else { _%> + <%_ } else { _%> if (<%= instanceName %>.getUser() != null) { // Save user in case it's new and only exists in gateway userRepository.save(<%= instanceName %>.getUser()); } - <%_ } _%> - <%_ } _%> - <%_ for (field of primaryKey.fields.filter(f => f.autoGenerateByService)) { _%> + <%_ } _%> + <%_ } _%> + <%_ for (field of primaryKey.fields.filter(f => f.autoGenerateByService)) { _%> <%= instanceName %>.set<%= field.fieldNameCapitalized %>(UUID.randomUUID()); - <%_ } _%> + <%_ } _%> <%- include('/partials/save_template', {asEntity, asDto, viaService: viaService, returnDirectly: false, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: true}); -%> - <%_ if (!reactive) { _%> + <%_ if (!reactive) { _%> return ResponseEntity.created(new URI("/api/<%= entityApiUrl %>/" + result.get<%= primaryKey.nameCapitalized %>())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, result.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)) .body(result); - <%_ } else { _%> + <%_ } else { _%> .map(result -> { try { return ResponseEntity.created(new URI("/api/<%= entityApiUrl %>/" + result.get<%= primaryKey.nameCapitalized %>())) @@ -207,7 +207,7 @@ public class <%= entityClass %>Resource { throw new RuntimeException(e); } }); - <%_ } _%> + <%_ } _%> } /** @@ -233,43 +233,43 @@ public class <%= entityClass %>Resource { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } -<%_ if (!reactive) { _%> + <%_ if (!reactive) { _%> if (!<%= entityInstance %>Repository.existsById(<%= primaryKey.name %>)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } -<%_ } else { _%> + <%_ } else { _%> return <%= entityInstance %>Repository.existsById(<%= primaryKey.name %>).flatMap(exists -> { if (!exists) { return Mono.error(new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound")); } -<%_ } _%> + <%_ } _%> - <%_ if (saveUserSnapshot) { _%> - <%_ if (manyToManyWithUser) { _%> + <%_ if (saveUserSnapshot) { _%> + <%_ if (manyToManyWithUser) { _%> if (<%= instanceName %>.getUsers() != null) { // Save users in case they are new and only exists in gateway userRepository.saveAll(<%= instanceName %>.getUsers()); } - <%_ } else { _%> + <%_ } else { _%> if (<%= instanceName %>.getUser() != null) { // Save user in case it's new and only exists in gateway userRepository.save(<%= instanceName %>.getUser()); } - <%_ } _%> - <%_ } _%> + <%_ } _%> + <%_ } _%> <%- include('/partials/save_template', {asEntity, asDto, viaService: viaService, returnDirectly: false, isUsingMapsId: false, mapsIdAssoc: mapsIdAssoc}); -%> - <%_ if (!reactive) { _%> + <%_ if (!reactive) { _%> return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)) .body(result); - <%_ } else { _%> + <%_ } else { _%> .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.type !== 'String') { %>.toString()<% } %>)) .body(result) ); }); - <%_ } _%> + <%_ } _%> } @@ -296,38 +296,38 @@ public class <%= entityClass %>Resource { throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid"); } - <%_ if (!reactive) { _%> + <%_ if (!reactive) { _%> if (!<%= entityInstance %>Repository.existsById(<%= primaryKey.name %>)) { throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"); } - <%_ } else { _%> + <%_ } else { _%> return <%= entityInstance %>Repository.existsById(<%= primaryKey.name %>).flatMap(exists -> { if (!exists) { return Mono.error(new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound")); } - <%_ } _%> + <%_ } _%> - <%_ if (saveUserSnapshot) { _%> - <%_ if (manyToManyWithUser) { _%> + <%_ if (saveUserSnapshot) { _%> + <%_ if (manyToManyWithUser) { _%> if (<%= instanceName %>.getUsers() != null) { // Save users in case they are new and only exists in gateway userRepository.saveAll(<%= instanceName %>.getUsers()); } - <%_ } else { _%> + <%_ } else { _%> if (<%= instanceName %>.getUser() != null) { // Save user in case it's new and only exists in gateway userRepository.save(<%= instanceName %>.getUser()); } - <%_ } _%> - <%_ } _%> + <%_ } _%> + <%_ } _%> <%- include('../../common/patch_template', {asEntity, asDto, isService: false, viaService: viaService}); -%> - <%_ if (!reactive) { _%> + <%_ if (!reactive) { _%> return ResponseUtil.wrapOrNotFound( result, HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.type !== 'String') { %>.toString()<% } %>) ); - <%_ } else { _%> + <%_ } else { _%> return result .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))) .map(res -> ResponseEntity.ok() @@ -335,54 +335,54 @@ public class <%= entityClass %>Resource { .body(res) ); }); - <%_ } _%> + <%_ } _%> } <%_ } _%> /** * {@code GET /<%= entityApiUrl %>} : get all the <%= entityInstancePlural %>. * - <%_ if (pagination !== 'no') { _%> +<%_ if (!paginationNo) { _%> * @param pageable the pagination information. - <%_ if (reactive) { _%> + <%_ if (reactive) { _%> * @param request a {@link ServerHttpRequest} request. - <%_ } _%> - <%_ } _%> - <%_ if (!jpaMetamodelFiltering && relationshipsContainEagerLoad) { _%> + <%_ } _%> +<%_ } _%> +<%_ if (!jpaMetamodelFiltering && relationshipsContainEagerLoad) { _%> * @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many). - <%_ } _%> - <%_ if (jpaMetamodelFiltering) { _%> +<%_ } _%> +<%_ if (jpaMetamodelFiltering) { _%> * @param criteria the criteria which the requested entities should match. - <%_ } else if (fieldsContainNoOwnerOneToOne) { _%> +<%_ } else if (fieldsContainNoOwnerOneToOne) { _%> * @param filter the filter of the request. - <%_ } _%> +<%_ } _%> * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of <%= entityInstancePlural %> in body. */ @GetMapping("/<%= entityApiUrl %>") - <%_ if (databaseType === 'sql' && isUsingMapsId === true && !viaService) { _%> +<%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%> @Transactional(readOnly = true) - <%_ } _%> +<%_ } _%> <%- include('../../common/get_all_template', {asEntity, asDto, viaService}); -%> - <%_ if (reactive && pagination === 'no') { _%> +<%_ if (reactive && paginationNo) { _%> /** * {@code GET /<%= entityApiUrl %>} : get all the <%= entityInstancePlural %> as a stream. * @return the {@link Flux} of <%= entityInstancePlural %>. */ @GetMapping(value = "/<%= entityApiUrl %>", produces = MediaType.APPLICATION_NDJSON_VALUE) - <%_ if (databaseType === 'sql' && isUsingMapsId === true && !viaService) { _%> + <%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%> @Transactional(readOnly = true) - <%_ } _%> + <%_ } _%> public Flux<<%= instanceType %>> getAll<%= entityClassPlural %>AsStream() { log.debug("REST request to get all <%= entityClassPlural %> as a stream"); - <%_ if (viaService) { _%> + <%_ if (viaService) { _%> return <%= entityInstance %>Service.findAll(); - <%_ } else { _%> - return <%= entityInstance %>Repository.findAll()<%_ if (dto === 'mapstruct') { _%>.map(<%= entityToDtoReference %>)<%_ } _%>; - <%_ } _%> + <%_ } else { _%> + return <%= entityInstance %>Repository.findAll()<%_ if (dtoMapstruct) { _%>.map(<%= entityToDtoReference %>)<%_ } _%>; + <%_ } _%> } - <%_ } _%> +<%_ } _%> /** * {@code GET /<%= entityApiUrl %>/:id} : get the "id" <%= entityInstance %>. * @@ -390,9 +390,9 @@ public class <%= entityClass %>Resource { * @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 (databaseType === 'sql' && isUsingMapsId === true && !viaService) { _%> +<%_ if (databaseTypeSql && isUsingMapsId && !viaService) { _%> @Transactional(readOnly = true) - <%_ } _%> +<%_ } _%> public <% if (reactive) { %>Mono<<% } %>ResponseEntity<<%= instanceType %>><% if (reactive) { %>><% } %> get<%= entityClass %>(@PathVariable <%= primaryKey.type %> id) { log.debug("REST request to get <%= entityClass %> : {}", id);<%- include('../../common/get_template', {asEntity, asDto, viaService, returnDirectly:false}); -%> return ResponseUtil.wrapOrNotFound(<%= instanceName %>); @@ -406,40 +406,40 @@ public class <%= entityClass %>Resource { * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/<%= entityApiUrl %>/{id}") - <%_ if (reactive) { _%> + <%_ if (reactive) { _%> @ResponseStatus(code = HttpStatus.NO_CONTENT) - <%_ } _%> + <%_ } _%> public <% if (reactive) { %>Mono<<% } %>ResponseEntity<% if (reactive) { %>><% } %> delete<%= entityClass %>(@PathVariable <%= primaryKey.type %> id) { log.debug("REST request to delete <%= entityClass %> : {}", id); <%- include('../../common/delete_template', {viaService: viaService, fromResource: true}); -%> - <%_ if (!reactive) { _%> - return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)).build(); - <%_ } else { _%> - <%_ if (databaseType === 'couchbase') { _%> + <%_ if (!reactive) { _%> + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (!primaryKey.fields[0].fieldTypeString) { %>.toString()<% } %>)).build(); + <%_ } else { _%> + <%_ if (databaseTypeCouchbase) { _%> .then(Mono.just(ResponseEntity.noContent() .headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)).build()) ); - <%_ } else { %> + <%_ } else { %> .map(result -> ResponseEntity.noContent() .headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (primaryKey.type !== 'String') { %>.toString()<% } %>)).build() ); - <%_ } _%> <%_ } _%> + <%_ } _%> } <%_ } _%> -<%_ if (searchEngine !== false) { _%> +<%_ if (searchEngine) { _%> /** * {@code SEARCH /_search/<%= entityApiUrl %>?query=:query} : search for the <%= entityInstance %> corresponding * to the query. * * @param query the query of the <%= entityInstance %> search. - <%_ if (pagination !== 'no') { _%> + <%_ if (!paginationNo) { _%> * @param pageable the pagination information. - <%_ if (reactive) { _%> + <%_ if (reactive) { _%> * @param request a {@link ServerHttpRequest} request. - <%_ } _%> <%_ } _%> + <%_ } _%> * @return the result of the search. */ @GetMapping("/_search/<%= entityApiUrl %>")<%- include('../../common/search_template', {asEntity, asDto, viaService}); -%> diff --git a/generators/entity-server/templates/src/main/resources/config/cql/changelog/added_entity.cql.ejs b/generators/entity-server/templates/src/main/resources/config/cql/changelog/added_entity.cql.ejs index 0bbb13908bf..caf379890af 100644 --- a/generators/entity-server/templates/src/main/resources/config/cql/changelog/added_entity.cql.ejs +++ b/generators/entity-server/templates/src/main/resources/config/cql/changelog/added_entity.cql.ejs @@ -19,42 +19,40 @@ CREATE TABLE IF NOT EXISTS <%= entityInstance %> ( <%_ for (const field of fields) { - const fieldType = field.fieldType; - const fieldName = field.fieldName; - const fieldNameUnderscored = field.fieldNameUnderscored; - const fieldTypeBlobContent = field.fieldTypeBlobContent; _%> - <%_ if (fieldType === 'UUID') { _%> + const fieldName = field.fieldName; + const fieldNameUnderscored = field.fieldNameUnderscored; _%> + <%_ if (field.fieldTypeUUID) { _%> <%= fieldName %> uuid, - <%_ } else if (fieldType === 'String' || field.fieldIsEnum) { _%> + <%_ } else if (field.fieldTypeString || field.fieldIsEnum) { _%> <%= fieldName %> text, - <%_ } else if (fieldType === 'Integer') { _%> + <%_ } else if (field.fieldTypeInteger) { _%> <%= fieldName %> int, - <%_ } else if (fieldType === 'Long') { _%> + <%_ } else if (field.fieldTypeLong) { _%> <%= fieldName %> bigint, - <%_ } else if (fieldType === 'Float') { _%> + <%_ } else if (field.fieldTypeFloat) { _%> <%= fieldName %> float, - <%_ } else if (fieldType === 'Double') { _%> + <%_ } else if (field.fieldTypeDouble) { _%> <%= fieldName %> double, - <%_ } else if (fieldType === 'BigDecimal') { _%> + <%_ } else if (field.fieldTypeBigDecimal) { _%> <%= fieldName %> decimal, - <%_ } else if (fieldType === 'LocalDate') { _%> + <%_ } else if (field.fieldTypeLocalDate) { _%> <%= fieldName %> date, - <%_ } else if (fieldType === 'Instant') { _%> + <%_ } else if (field.fieldTypeInstant) { _%> <%= fieldName %> timestamp, - <%_ } else if (fieldType === 'Duration') { _%> + <%_ } else if (field.fieldTypeDuration) { _%> <%= fieldName %> text, - <%_ } else if (fieldType === 'ZonedDateTime') { _%> + <%_ } else if (field.fieldTypeZonedDateTime) { _%> <%= fieldName %> tuple, - <%_ } else if (fieldType === 'Boolean') { _%> + <%_ } else if (field.fieldTypeBoolean) { _%> <%= fieldName %> boolean, - <%_ } else if (fieldType === 'ByteBuffer') { _%> - <%_ if (fieldTypeBlobContent !== 'text') { _%> + <%_ } else if (field.fieldTypeByteBuffer) { _%> + <%_ if (!field.blobContentTypeText) { _%> <%= fieldName %> blob, <%= fieldNameUnderscored %>_content_type text, - <%_ } else { _%> + <%_ } else { _%> <%= fieldName %> text, - <%_ } _%> <%_ } _%> + <%_ } _%> <%_ } _%> PRIMARY KEY(id) ); diff --git a/generators/entity/index.js b/generators/entity/index.js index a843a6fae16..b35239e6043 100644 --- a/generators/entity/index.js +++ b/generators/entity/index.js @@ -718,6 +718,10 @@ class EntityGenerator extends BaseBlueprintGenerator { return this._preparingRelationships(); } + _derivedCompositePrimaryKeyProperties(types) { + this.context.otherEntityPrimaryKeyTypesIncludesUUID = types.includes(UUID); + } + // Public API method used by the getter and also by Blueprints _default() { return { @@ -759,6 +763,7 @@ class EntityGenerator extends BaseBlueprintGenerator { .map(rel => rel.otherEntity.primaryKey.fields.map(f => f.fieldType)) .flat(); this.context.otherEntityPrimaryKeyTypes = Array.from(new Set(types)); + this._derivedCompositePrimaryKeyProperties(types); }, /** diff --git a/utils/entity.js b/utils/entity.js index 2a5f294748f..4115bcbc615 100644 --- a/utils/entity.js +++ b/utils/entity.js @@ -24,15 +24,17 @@ const { parseLiquibaseChangelogDate } = require('./liquibase'); const { entityDefaultConfig } = require('../generators/generator-defaults'); const { stringHashCode } = require('../generators/utils'); const { fieldToReference } = require('./field'); -const { PaginationTypes } = require('../jdl/jhipster/entity-options'); +const { PaginationTypes, ServiceTypes } = require('../jdl/jhipster/entity-options'); const { GATEWAY, MICROSERVICE } = require('../jdl/jhipster/application-types'); const { MapperTypes } = require('../jdl/jhipster/entity-options'); const { OAUTH2 } = require('../jdl/jhipster/authentication-types'); const { CommonDBTypes } = require('../jdl/jhipster/field-types'); -const { BOOLEAN } = CommonDBTypes; +const { BOOLEAN, UUID } = CommonDBTypes; const { MAPSTRUCT } = MapperTypes; const { PAGINATION, INFINITE_SCROLL } = PaginationTypes; +const { SERVICE_IMPL } = ServiceTypes; +const NO_SERVICE = ServiceTypes.NO; const NO_PAGINATION = PaginationTypes.NO; const NO_MAPPER = MapperTypes.NO; @@ -91,11 +93,14 @@ const BASE_TEMPLATE_DATA = { function _derivedProperties(entityWithConfig) { const pagination = entityWithConfig.pagination; const dto = entityWithConfig.dto; + const service = entityWithConfig.service; _.defaults(entityWithConfig, { paginationPagination: pagination === PAGINATION, paginationInfiniteScroll: pagination === INFINITE_SCROLL, paginationNo: pagination === NO_PAGINATION, dtoMapstruct: dto === MAPSTRUCT, + serviceImpl: service === SERVICE_IMPL, + serviceNo: service === NO_SERVICE, }); } @@ -223,6 +228,12 @@ function prepareEntityForTemplates(entityWithConfig, generator) { return entityWithConfig; } +function _derivedPrimaryKeyProperties(primaryKey) { + _.defaults(primaryKey, { + hasUUID: primaryKey.fields.some(field => field.fieldType === UUID), + }); +} + function prepareEntityPrimaryKeyForTemplates(entityWithConfig, generator, enableCompositeId = true) { const idFields = entityWithConfig.fields.filter(field => field.id); const idRelationships = entityWithConfig.relationships.filter(relationship => relationship.id); @@ -379,6 +390,7 @@ function prepareEntityPrimaryKeyForTemplates(entityWithConfig, generator, enable }, }; } + _derivedPrimaryKeyProperties(entityWithConfig.primaryKey); return entityWithConfig; } diff --git a/utils/field.js b/utils/field.js index 080d59ea29f..a1433f8e349 100644 --- a/utils/field.js +++ b/utils/field.js @@ -443,4 +443,4 @@ function fieldToReference(entity, field, pathPrefix = []) { }; } -module.exports = { prepareFieldForTemplates, fieldIsEnum, getEnumValuesWithCustomValues, fieldToReference }; +module.exports = { prepareFieldForTemplates, fieldIsEnum, getEnumValuesWithCustomValues, fieldToReference, derivedProperties }; From d325d2da1808d7504a5c2f6d3b3ad48f9f0d9c58 Mon Sep 17 00:00:00 2001 From: Charlie Mordant Date: Tue, 20 Apr 2021 22:01:22 +0200 Subject: [PATCH 2/5] use single entity type for PK UUID --- .../repository/EntityRepository.java.ejs | 2 +- .../EntityRepository_reactive.java.ejs | 2 +- .../search/EntitySearchRepository.java.ejs | 2 +- .../package/service/EntityService.java.ejs | 2 +- .../package/service/dto/EntityDTO.java.ejs | 2 +- .../service/impl/EntityServiceImpl.java.ejs | 2 +- generators/entity/index.js | 26 ++++++++++++++----- utils/entity.js | 14 +++++++--- utils/field.js | 6 ++--- 9 files changed, 39 insertions(+), 19 deletions(-) diff --git a/generators/entity-server/templates/src/main/java/package/repository/EntityRepository.java.ejs b/generators/entity-server/templates/src/main/java/package/repository/EntityRepository.java.ejs index 5db05b22711..050826c7ab9 100644 --- a/generators/entity-server/templates/src/main/java/package/repository/EntityRepository.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/repository/EntityRepository.java.ejs @@ -63,7 +63,7 @@ import java.util.List; import java.util.Optional; <%_ } _%> <%_ } _%> -<%_ if (primaryKey.hasUUID) { _%> +<%_ if (primaryKey.typeUUID) { _%> import java.util.UUID; <%_ } _%> diff --git a/generators/entity-server/templates/src/main/java/package/repository/EntityRepository_reactive.java.ejs b/generators/entity-server/templates/src/main/java/package/repository/EntityRepository_reactive.java.ejs index da9d469390d..19b04f7e5cc 100644 --- a/generators/entity-server/templates/src/main/java/package/repository/EntityRepository_reactive.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/repository/EntityRepository_reactive.java.ejs @@ -54,7 +54,7 @@ import reactor.core.publisher.Flux; <%_ if (relationshipsContainEagerLoad || databaseTypeSql) { _%> import reactor.core.publisher.Mono; <%_ } _%> -<%_ if (primaryKey.hasUUID) { _%> +<%_ if (primaryKey.typeUUID) { _%> import java.util.UUID; <%_ } _%> diff --git a/generators/entity-server/templates/src/main/java/package/repository/search/EntitySearchRepository.java.ejs b/generators/entity-server/templates/src/main/java/package/repository/search/EntitySearchRepository.java.ejs index 7a9bfde82f9..654954c684c 100644 --- a/generators/entity-server/templates/src/main/java/package/repository/search/EntitySearchRepository.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/repository/search/EntitySearchRepository.java.ejs @@ -31,7 +31,7 @@ import org.springframework.data.elasticsearch.repository.<% if (reactive) {%>Rea <%_ if (reactive) { _%> import reactor.core.publisher.Flux; <%_ } _%> -<%_ if (primaryKey.hasUUID) { _%> +<%_ if (primaryKey.typeUUID) { _%> import java.util.UUID; <% } %> diff --git a/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs b/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs index b3277d71d55..8462f15736e 100644 --- a/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/EntityService.java.ejs @@ -48,7 +48,7 @@ import java.util.List; <%_ if (!reactive) { _%> import java.util.Optional; <%_ } _%> -<%_ if (primaryKey.hasUUID) { _%> +<%_ if (primaryKey.typeUUID) { _%> import java.util.UUID; <%_ } _%> diff --git a/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs b/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs index e3348f25f38..1327b889320 100644 --- a/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs @@ -173,7 +173,7 @@ _%> public String toString() { return "<%= dtoClass %>{" + <%_ for ([idx, reference] of dtoReferences.entries()) { - const isNumeric = (reference.field && reference.field.fieldTypeNumeric) || (reference.relationship && reference.relationship.relatedField && reference.relationship.relatedField.fieldTypeNumeric)_%> + const isNumeric = (reference.field && reference.field.fieldTypeNumeric) || (reference.relationship && reference.relationship.otherEntity.primaryKey && reference.relationship.otherEntity.primaryKey.typeNumeric)_%> "<%= idx === 0 ? '' : ', ' %><%= reference.name %>=<% if (!isNumeric) { %>'<% } %>" + <%= buildJavaGet(reference) %> <% if (! isNumeric) { %>+ "'" <% } %>+ <%_ } _%> "}"; diff --git a/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs b/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs index dc2a21f7dde..8d5d982a0cd 100644 --- a/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/impl/EntityServiceImpl.java.ejs @@ -75,7 +75,7 @@ import java.util.List; <%_ if (!reactive) { _%> import java.util.Optional; <%_ } _%> -<%_ if (primaryKey.hasUUID) { _%> +<%_ if (primaryKey.typeUUID) { _%> import java.util.UUID; <%_ } _%> <%_ if (fieldsContainNoOwnerOneToOne || (paginationNo && ((searchEngine) || dtoMapstruct))) { _%> diff --git a/generators/entity/index.js b/generators/entity/index.js index b35239e6043..54b525a2fca 100644 --- a/generators/entity/index.js +++ b/generators/entity/index.js @@ -28,7 +28,12 @@ const BaseBlueprintGenerator = require('../generator-base-blueprint'); const constants = require('../generator-constants'); const statistics = require('../statistics'); const { isReservedClassName, isReservedTableName } = require('../../jdl/jhipster/reserved-keywords'); -const { prepareEntityForTemplates, prepareEntityPrimaryKeyForTemplates, loadRequiredConfigIntoEntity } = require('../../utils/entity'); +const { + prepareEntityForTemplates, + prepareEntityPrimaryKeyForTemplates, + loadRequiredConfigIntoEntity, + derivedPrimaryKeyProperties, +} = require('../../utils/entity'); const { prepareFieldForTemplates, fieldIsEnum } = require('../../utils/field'); const { prepareRelationshipForTemplates } = require('../../utils/relationship'); const { stringify } = require('../../utils'); @@ -167,7 +172,12 @@ class EntityGenerator extends BaseBlueprintGenerator { this._setupEntityOptions(this, this, this.context); useBlueprints = - !this.fromBlueprint && this.instantiateBlueprints(GENERATOR_ENTITY, { entityExisted, configExisted, arguments: [name] }); + !this.fromBlueprint && + this.instantiateBlueprints(GENERATOR_ENTITY, { + entityExisted, + configExisted, + arguments: [name], + }); } // Public API method used by the getter and also by Blueprints @@ -718,10 +728,6 @@ class EntityGenerator extends BaseBlueprintGenerator { return this._preparingRelationships(); } - _derivedCompositePrimaryKeyProperties(types) { - this.context.otherEntityPrimaryKeyTypesIncludesUUID = types.includes(UUID); - } - // Public API method used by the getter and also by Blueprints _default() { return { @@ -757,6 +763,10 @@ class EntityGenerator extends BaseBlueprintGenerator { this.context.entityContainsCollectionField = this.context.relationships.some(relationship => relationship.relationshipCollection); }, + processEntityPrimaryKeysDerivedProperties() { + derivedPrimaryKeyProperties(this.context.primaryKey); + }, + processPrimaryKeyTypesForRelations() { const types = this.context.relationships .filter(rel => rel.otherEntity.primaryKey) @@ -1051,6 +1061,10 @@ class EntityGenerator extends BaseBlueprintGenerator { } return entityTableName; } + + _derivedCompositePrimaryKeyProperties(types) { + this.context.otherEntityPrimaryKeyTypesIncludesUUID = types.includes(UUID); + } } module.exports = EntityGenerator; diff --git a/utils/entity.js b/utils/entity.js index 4115bcbc615..4845aa132ee 100644 --- a/utils/entity.js +++ b/utils/entity.js @@ -228,9 +228,11 @@ function prepareEntityForTemplates(entityWithConfig, generator) { return entityWithConfig; } -function _derivedPrimaryKeyProperties(primaryKey) { +function derivedPrimaryKeyProperties(primaryKey) { _.defaults(primaryKey, { - hasUUID: primaryKey.fields.some(field => field.fieldType === UUID), + hasUUID: primaryKey.fields && primaryKey.fields.some(field => field.fieldType === UUID), + typeUUID: primaryKey.type === UUID, + typeNumeric: !primaryKey.composite && primaryKey.fields[0].fieldTypeNumeric, }); } @@ -390,7 +392,6 @@ function prepareEntityPrimaryKeyForTemplates(entityWithConfig, generator, enable }, }; } - _derivedPrimaryKeyProperties(entityWithConfig.primaryKey); return entityWithConfig; } @@ -446,4 +447,9 @@ function loadRequiredConfigIntoEntity(entity, config) { return entity; } -module.exports = { prepareEntityForTemplates, prepareEntityPrimaryKeyForTemplates, loadRequiredConfigIntoEntity }; +module.exports = { + prepareEntityForTemplates, + prepareEntityPrimaryKeyForTemplates, + loadRequiredConfigIntoEntity, + derivedPrimaryKeyProperties, +}; diff --git a/utils/field.js b/utils/field.js index a1433f8e349..736747f7a4f 100644 --- a/utils/field.js +++ b/utils/field.js @@ -183,7 +183,7 @@ const generateFakeDataForField = (field, faker, changelogDate, type = 'csv') => return data; }; -function derivedProperties(field) { +function _derivedProperties(field) { const fieldType = field.fieldType; const fieldTypeBlobContent = field.fieldTypeBlobContent; const validationRules = field.fieldValidate ? field.fieldValidateRules : []; @@ -383,7 +383,7 @@ function prepareFieldForTemplates(entityWithConfig, field, generator) { field.path = [field.fieldName]; field.relationshipsPath = []; field.reference = fieldToReference(entityWithConfig, field); - derivedProperties(field); + _derivedProperties(field); return field; } @@ -443,4 +443,4 @@ function fieldToReference(entity, field, pathPrefix = []) { }; } -module.exports = { prepareFieldForTemplates, fieldIsEnum, getEnumValuesWithCustomValues, fieldToReference, derivedProperties }; +module.exports = { prepareFieldForTemplates, fieldIsEnum, getEnumValuesWithCustomValues, fieldToReference }; From 5100cd6736cf6178c8fae269768c1c52f118bc32 Mon Sep 17 00:00:00 2001 From: Charlie Mordant Date: Wed, 21 Apr 2021 13:59:55 +0200 Subject: [PATCH 3/5] Skip derived properties when primary keys does not exist Co-authored-by: Marcelo Shima --- generators/entity/index.js | 1 + 1 file changed, 1 insertion(+) diff --git a/generators/entity/index.js b/generators/entity/index.js index 54b525a2fca..43a24692802 100644 --- a/generators/entity/index.js +++ b/generators/entity/index.js @@ -764,6 +764,7 @@ class EntityGenerator extends BaseBlueprintGenerator { }, processEntityPrimaryKeysDerivedProperties() { + if (!this.context.primaryKey) return; derivedPrimaryKeyProperties(this.context.primaryKey); }, From 6693d025c908b7c1d7a31edcfbdb98054fc325a4 Mon Sep 17 00:00:00 2001 From: Charlie Mordant Date: Wed, 21 Apr 2021 16:37:23 +0200 Subject: [PATCH 4/5] simplify DTO toString template logic Co-authored-by: Marcelo Shima --- .../src/main/java/package/service/dto/EntityDTO.java.ejs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs b/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs index 1327b889320..12b5d61f796 100644 --- a/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs @@ -173,8 +173,8 @@ _%> public String toString() { return "<%= dtoClass %>{" + <%_ for ([idx, reference] of dtoReferences.entries()) { - const isNumeric = (reference.field && reference.field.fieldTypeNumeric) || (reference.relationship && reference.relationship.otherEntity.primaryKey && reference.relationship.otherEntity.primaryKey.typeNumeric)_%> - "<%= idx === 0 ? '' : ', ' %><%= reference.name %>=<% if (!isNumeric) { %>'<% } %>" + <%= buildJavaGet(reference) %> <% if (! isNumeric) { %>+ "'" <% } %>+ + const isQuoted = reference.field && !reference.field.fieldTypeNumeric _%> + "<%= idx === 0 ? '' : ', ' %><%= reference.name %>=<% if (isQuoted) { %>'<% } %>" + <%= buildJavaGet(reference) %> <% if (!isQuoted) { %>+ "'" <% } %>+ <%_ } _%> "}"; } From 17a382e658054e1236b93fc3452ef5b32ea28954 Mon Sep 17 00:00:00 2001 From: Charlie Mordant Date: Wed, 21 Apr 2021 17:38:44 +0200 Subject: [PATCH 5/5] mshima mybad ^^ - dto tostring method Co-authored-by: Marcelo Shima --- .../src/main/java/package/service/dto/EntityDTO.java.ejs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs b/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs index 12b5d61f796..c2a55badfe9 100644 --- a/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs +++ b/generators/entity-server/templates/src/main/java/package/service/dto/EntityDTO.java.ejs @@ -174,7 +174,7 @@ _%> return "<%= dtoClass %>{" + <%_ for ([idx, reference] of dtoReferences.entries()) { const isQuoted = reference.field && !reference.field.fieldTypeNumeric _%> - "<%= idx === 0 ? '' : ', ' %><%= reference.name %>=<% if (isQuoted) { %>'<% } %>" + <%= buildJavaGet(reference) %> <% if (!isQuoted) { %>+ "'" <% } %>+ + "<%= idx === 0 ? '' : ', ' %><%= reference.name %>=<% if (isQuoted) { %>'<% } %>" + <%= buildJavaGet(reference) %> <% if (isQuoted) { %>+ "'" <% } %>+ <%_ } _%> "}"; }