Home > Mobile >  Dynamic parameters on dynamic (complex) query JPA/Hibernate
Dynamic parameters on dynamic (complex) query JPA/Hibernate

Time:10-22

I am trying to build a complex query that involves filtering which i did it like so on JDBC:

private String buildFilteredQuery(List<Long> extensions, List<Long> categories, Long courseId) {
        ...
        StringBuilder extensionQuery = new StringBuilder();
        if (!extensions.isEmpty()) {
            extensionQuery.append("AND (");
            extensions.forEach(e -> extensionQuery.append("fileExtensionId = ? OR "));
            extensionQuery.delete(extensionQuery.length() - 4, extensionQuery.length());
            extensionQuery.append(")");
        }
        ...
    }

The problem is that now over JPA i can't really do this since instead of the ? i should put the variable to be mapped (e.g :fileExtension )

So how can i build a dynamic query that takes dynamic parameters to it?

CodePudding user response:

Like @Guillaume said, i ended up only using one stament with an IN clause:

private String buildFilteredQuery(List<Long> extensions, List<Long> categories, Long courseId) {
        ...
        StringBuilder query = new StringBuilder();
        if (!extensions.isEmpty()) query.append("AND ( fileExtensionId IN ( :extensionIds ) ) ");
        ...
    }
  • Related