简体   繁体   中英

Dynamic parameters on dynamic (complex) query JPA/Hibernate

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 (eg :fileExtension )

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

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 ) ) ");
        ...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM