Skip to content

Commit

Permalink
unflatten criteria class fixes: jhipster#13133
Browse files Browse the repository at this point in the history
  • Loading branch information
yelhouti committed Mar 5, 2021
1 parent b0fed8a commit e465b3c
Show file tree
Hide file tree
Showing 12 changed files with 369 additions and 64 deletions.
15 changes: 13 additions & 2 deletions generators/entity-server/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,25 @@ const serverFiles = {
{
condition: generator => generator.jpaMetamodelFiltering,
path: SERVER_MAIN_SRC_DIR,
templates: [
{
file: 'package/service/EntityQueryService.java',
renameTo: generator => `${generator.packageFolder}/service/${generator.entityClass}QueryService.java`,
},
],
},
{
condition: generator => generator.criteria,
deleteOnNotCondition: true, // used if the relationship is not present anymore to delete the files since not needed anymore
path: SERVER_MAIN_SRC_DIR,
templates: [
{
file: 'package/service/criteria/EntityCriteria.java',
renameTo: generator => `${generator.packageFolder}/service/criteria/${generator.entityClass}Criteria.java`,
},
{
file: 'package/service/EntityQueryService.java',
renameTo: generator => `${generator.packageFolder}/service/${generator.entityClass}QueryService.java`,
file: 'package/service/EntityCriteriaService.java',
renameTo: generator => `${generator.packageFolder}/service/${generator.entityClass}CriteriaService.java`,
},
],
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@
beans.push({class: `${mapsIdEntity}Repository`, instance: mapsIdRepoInstance});
}
}
if (typeof criteriaService !== "undefined" && criteriaService) {
beans.push({class: `${entityClass}CriteriaService`, instance: `${entityInstance}CriteriaService`});
}
if (saveUserSnapshot && (viaService || constructorName.endsWith('Resource'))) {
beans.push({class: 'UserRepository', instance: 'userRepository'});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<%#
Copyright 2013-2021 the original author or authors from the JHipster project.

This file is part of the JHipster project, see https://www.jhipster.tech/
for more information.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-%>
package <%= packageName %>.service;

<%_
const serviceClassName = entityClass + 'CriteriaService';
const criteria = entityClass + 'Criteria';
_%>

<%_ if (relationships.length) { _%>
import javax.persistence.criteria.Root;
<%_ } _%>

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
<%_ if (relationships.length) { _%>
import org.springframework.context.annotation.Lazy;
<%_ } _%>
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import tech.jhipster.service.QueryService;

import <%= packageName %>.domain.<%= asEntity(entityClass) %>;
import <%= packageName %>.domain.*; // for static metamodels
import <%= packageName %>.service.criteria.<%= entityClass %>Criteria;

/**
* Service for converting criteria to specification
*/
@Service
public class <%= serviceClassName %> extends QueryService<<%= asEntity(entityClass) %>> {

private final Logger log = LoggerFactory.getLogger(<%= serviceClassName %>.class);

<%_ criteriaServices = Array.from(new Set(relationships.map(r => r.otherEntityName + 'CriteriaService'))) _%>
<%_ criteriaServices.forEach(cs => { _%>
private final <%= _.upperFirst(cs) %> <%= cs %>;
<%_ }) _%>

public <%= serviceClassName %>(<%= criteriaServices.map(cs => `@Lazy ${_.upperFirst(cs)} ${cs}`).join(', ') %>) {
<%_ criteriaServices.forEach(cs => { _%>
this.<%= cs %> = <%= cs %>;
<%_ }) _%>
}

/**
* Function to convert {@link <%= criteria %>} to a {@link Specification}
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching {@link Specification} of the entity.
*/
public Specification<<%= asEntity(entityClass) %>> createSpecification(<%= criteria %> criteria) {
log.debug("create specification from criteria : {}", criteria);
Specification<<%= asEntity(entityClass) %>> specification = Specification.where(null);
if (criteria != null) {
<%_ fields.forEach((field) => {
if (isFilterableType(field.fieldType)) { _%>
if (criteria.get<%= field.fieldInJavaBeanMethod %>() != null) {
specification = specification.and(<%= getSpecificationBuilder(field.fieldType) %>(criteria.get<%= field.fieldInJavaBeanMethod %>(), <%= asEntity(entityClass) %>_.<%= field.fieldName %>));
}
<%_ }
}); _%>

<%_ relationships.forEach((relationship) => { _%>
if (criteria.get<%= relationship.relationshipNameCapitalized %>() != null) {
Specification<<%= asEntity(relationship.otherEntityNameCapitalized) %>> <%= relationship.otherEntityName %>Specification = this.<%= relationship.otherEntityName %>CriteriaService.createSpecification(criteria.get<%= relationship.relationshipNameCapitalized %>());
specification = specification.and((root, query, criteriaBuilder) -> {
Root<<%= asEntity(relationship.otherEntityNameCapitalized) %>> <%= relationship.otherEntityName %>Root = query.from(<%= asEntity(relationship.otherEntityNameCapitalized) %>.class);
return criteriaBuilder.and(
<%_ if (['one-to-one'].includes(relationship.relationshipType)) { _%>
<%_ // this should work, without looking through pk and use pkGetter, the same way it does for manyToMany just by comparing entities, for some reason it doesn't _%>
<%_ // issue: https://hibernate.atlassian.net/browse/HHH-14341 _%>
<%_ relationship.otherEntity.primaryKey.ids.forEach(pk => {
const pkGetter = `get(${asEntity(relationship.otherEntity.entityClass)}_.${pk.name})` _%>
criteriaBuilder.equal(<%= relationship.otherEntityName %>Root.<%= pkGetter %>, root.get(<%= asEntity(entityClass) %>_.<%= relationship.relationshipName %>).<%= pkGetter %>),
<%_ }) _%>
<%_ } else if (['many-to-one'].includes(relationship.relationshipType)) { _%>
criteriaBuilder.equal(<%= relationship.otherEntityName %>Root, root.get(<%= asEntity(entityClass) %>_.<%= relationship.relationshipName %>)),
<%_ } else { _%>
criteriaBuilder.isMember(<%= relationship.otherEntityName %>Root, root.get(<%= asEntity(entityClass) %>_.<%= relationship.relationshipNamePlural %>)),
<%_ } _%>
<%= relationship.otherEntityName %>Specification.toPredicate(<%= relationship.otherEntityName %>Root, query, criteriaBuilder)
);
});
}
<%_ }); // forEach
_%>
}
return specification;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@ const criteria = entityClass + 'Criteria';
_%>
import java.util.List;

import javax.persistence.criteria.JoinType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
Expand All @@ -45,7 +43,6 @@ import org.springframework.transaction.annotation.Transactional;
import tech.jhipster.service.QueryService;

import <%= packageName %>.domain.<%= asEntity(entityClass) %>;
import <%= packageName %>.domain.*; // for static metamodels
import <%= packageName %>.repository.<%= entityClass %>Repository;<% if (searchEngine === 'elasticsearch') { %>
import <%= packageName %>.repository.search.<%= entityClass %>SearchRepository;<% } %>
import <%= packageName %>.service.criteria.<%= entityClass %>Criteria;
Expand All @@ -65,7 +62,7 @@ import <%= packageName %>.service.mapper.<%= entityClass %>Mapper;
public class <%= serviceClassName %> extends QueryService<<%= asEntity(entityClass) %>> {

private final Logger log = LoggerFactory.getLogger(<%= serviceClassName %>.class);
<%- include('../common/inject_template', {viaService: false, constructorName: serviceClassName, queryService: false, isUsingMapsId: false, mapsIdAssoc: null, isController: false}); -%>
<%- include('../common/inject_template', {viaService: false, constructorName: serviceClassName, queryService: false, isUsingMapsId: false, mapsIdAssoc: null, isController: false, criteriaService: true}); -%>

/**
* Return a {@link List} of {@link <%= instanceType %>} which matches the criteria from the database.
Expand All @@ -75,7 +72,7 @@ public class <%= serviceClassName %> extends QueryService<<%= asEntity(entityCla
@Transactional(readOnly = true)
public List<<%= instanceType %>> findByCriteria(<%= criteria %> criteria) {
log.debug("find by criteria : {}", criteria);
final Specification<<%= asEntity(entityClass) %>> specification = createSpecification(criteria);
final Specification<<%= asEntity(entityClass) %>> specification = <%= entityInstance %>CriteriaService.createSpecification(criteria);
<%_ if (dto === 'mapstruct') { _%>
return <%= entityListToDto %>(<%= repository %>.findAll(specification));
<%_ } else { _%>
Expand All @@ -92,7 +89,7 @@ public class <%= serviceClassName %> extends QueryService<<%= asEntity(entityCla
@Transactional(readOnly = true)
public Page<<%= instanceType %>> findByCriteria(<%= criteria %> criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<<%= asEntity(entityClass) %>> specification = createSpecification(criteria);
final Specification<<%= asEntity(entityClass) %>> specification = <%= entityInstance %>CriteriaService.createSpecification(criteria);
<%_ if (dto === 'mapstruct') { _%>
return <%= repository %>.findAll(specification, page)
.map(<%= entityToDtoReference %>);
Expand All @@ -109,40 +106,7 @@ public class <%= serviceClassName %> extends QueryService<<%= asEntity(entityCla
@Transactional(readOnly = true)
public long countByCriteria(<%= criteria %> criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<<%= asEntity(entityClass) %>> specification = createSpecification(criteria);
final Specification<<%= asEntity(entityClass) %>> specification = <%= entityInstance %>CriteriaService.createSpecification(criteria);
return <%= repository %>.count(specification);
}

/**
* Function to convert {@link <%= criteria %>} to a {@link Specification}
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching {@link Specification} of the entity.
*/
protected Specification<<%= asEntity(entityClass) %>> createSpecification(<%= criteria %> criteria) {
Specification<<%= asEntity(entityClass) %>> specification = Specification.where(null);
if (criteria != null) {
if (criteria.get<%= primaryKey.nameCapitalized %>() != null) {
specification = specification.and(<%= getSpecificationBuilder(primaryKey.type) %>(criteria.get<%= primaryKey.nameCapitalized %>(), <%= asEntity(entityClass) %>_.<%= primaryKey.name %>));
}
<%_
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 %>(), <%= asEntity(entityClass) %>_.<%= 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(<%= asEntity(entityClass) %>_.<%= metamodelFieldName %>, JoinType.LEFT).get(<%= asEntity(relationship.otherEntityNameCapitalized) %>_.<%= relationship.otherEntity.primaryKey.name %>)));
}
<%_ }); // forEach
_%>
}
return specification;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,18 +53,12 @@ if (isFilterableType(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';
}
filterVariables.push({ filterType : oauthAwareReferenceFilterType,
name: relationship.relationshipFieldName + 'Id',
relationships.forEach((relationship) => {
const relationshipType = relationship.relationshipType;
filterVariables.push({ filterType : `${relationship.otherEntityNameCapitalized}Criteria`,
name: relationship.relationshipFieldName,
type: relationshipType,
fieldInJavaBeanMethod: relationship.relationshipNameCapitalized + 'Id' });
fieldInJavaBeanMethod: relationship.relationshipNameCapitalized });
});
_%>
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1146,20 +1146,29 @@ class <%= entityClass %>ResourceIT <% if (databaseType === 'cassandra') { %>exte
<%_ } _%>
<%_ } _%>
<%= entityInstance %>Repository.saveAndFlush(<%= asEntity(entityInstance) %>);
<%= relationship.otherEntity.primaryKey.type %> <%= relationship.relationshipFieldName %>Id = <%= relationship.relationshipFieldName %>.get<%= relationship.otherEntity.primaryKey.nameCapitalized %>();
<%_ const filterId = relationship.otherEntity.primaryKey.ids[0];
const filterName = `${relationship.relationshipName}.${filterId.nameDotted}`;
let filterValue = relationship.relationshipName;
if (relationship.otherEntity.primaryKey.composite) {
filterValue += `.getId()`;
}
filterValue += `.${filterId.getter}()`;
const filterType = filterId.field.fieldType;
_%>

// Get all the <%= entityInstance %>List where <%= relationship.relationshipFieldName %> equals to <%= relationship.relationshipFieldName %>Id
default<%= entityClass %>ShouldBeFound("<%= relationship.relationshipFieldName %>Id.equals=" + <%= relationship.relationshipFieldName %>Id);
// Get all the <%= entityInstance %>List where <%= filterName %> equals to <%= filterValue %>
default<%= entityClass %>ShouldBeFound("<%= filterName %>.equals=" + <%= filterValue %>);

<%_
const initInvalidPrimaryKey = {
'String' : '"invalid-id"',
'Long' : '(' + relationship.relationshipFieldName + 'Id + 1)',
'Long' : '(' + filterValue + ' + 1)',
'Integer' : '(' + filterValue + ' + 1)',
'UUID' : 'UUID.randomUUID()'
}[relationship.otherEntity.primaryKey.type];
}[filterType];
_%>
// Get all the <%= entityInstance %>List where <%= relationship.relationshipFieldName %> equals to <%- initInvalidPrimaryKey %>
default<%= entityClass %>ShouldNotBeFound("<%= relationship.relationshipFieldName %>Id.equals=" + <%- initInvalidPrimaryKey %>);
// Get all the <%= entityInstance %>List where <%= filterName %> equals to <%- initInvalidPrimaryKey %>
default<%= entityClass %>ShouldNotBeFound("<%= filterName %>.equals=" + <%- initInvalidPrimaryKey %>);
}

<%_ }); _%>
Expand Down
8 changes: 7 additions & 1 deletion generators/entity/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ 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, loadRequiredConfigIntoEntity } = require('../../utils/entity');
const { prepareEntityForTemplates, loadRequiredConfigIntoEntity, setAndPropagateCriteria } = require('../../utils/entity');
const { prepareFieldForTemplates, fieldIsEnum } = require('../../utils/field');
const { prepareRelationshipForTemplates } = require('../../utils/relationship');
const { stringify } = require('../../utils');
Expand Down Expand Up @@ -639,6 +639,12 @@ class EntityGenerator extends BaseBlueprintGenerator {
.filter(reference => reference.owned || reference.relationship.otherEntity.embedded),
];
},

prepareCriteria() {
if (!this.context.criteria && this.context.jpaMetamodelFiltering) {
setAndPropagateCriteria(this.context);
}
},
};
}

Expand Down
8 changes: 7 additions & 1 deletion generators/generator-base.js
Original file line number Diff line number Diff line change
Expand Up @@ -2129,7 +2129,7 @@ module.exports = class JHipsterBaseGenerator extends PrivateBase {

const writeTasks = Object.values(files).map(blockTemplates => {
return blockTemplates.map(blockTemplate => {
if (!blockTemplate.condition || blockTemplate.condition(_this)) {
if (!blockTemplate.condition || blockTemplate.condition(_this) || blockTemplate.deleteOnNotCondition) {
const blockPath = blockTemplate.path || '';
return blockTemplate.templates.map(templateObj => {
let templatePath = blockPath;
Expand Down Expand Up @@ -2160,6 +2160,12 @@ module.exports = class JHipsterBaseGenerator extends PrivateBase {
templatePathTo = _this.destinationPath(templatePathTo);
}

if (blockTemplate.deleteOnNotCondition) {
if (_this.fs && _this.fs.exists(templatePathTo)) {
return _this.fs.delete(templatePathTo);
}
return undefined;
}
if (templateObj.override !== undefined && _this.fs && _this.fs.exists(templatePathTo)) {
if (typeof templateObj.override === 'function') {
if (!templateObj.override(_this)) {
Expand Down
11 changes: 11 additions & 0 deletions generators/server/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -1372,6 +1372,17 @@ const serverFiles = {
},
],
},
{
condition: generator => generator.user && generator.user.criteria,
path: SERVER_MAIN_SRC_DIR,
templates: [
{
file: 'package/service/criteria/UserCriteria.java',
renameTo: generator => `${generator.javaDir}service/criteria/UserCriteria.java`,
},
{ file: 'package/service/UserCriteriaService.java', renameTo: generator => `${generator.javaDir}service/UserCriteriaService.java` },
],
},
{
condition: generator => generator.isUsingBuiltInAuthority(),
path: SERVER_MAIN_SRC_DIR,
Expand Down
Loading

0 comments on commit e465b3c

Please sign in to comment.