Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
An example of QueryManager in Java for JPA
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.Map;
public class QueryBuilder {
private final EntityManager entityManager;
private final Map<String, Object> parameters = new HashMap<>();
private String resultSetMapping;
private String query;
public QueryBuilder(EntityManager entityManager) {
this.entityManager = entityManager;
public QueryBuilder withQuery(String query) {
this.query = query;
return this;
public QueryBuilder withParameter(String key, Object value) {
parameters.put(key, value);
return this;
public QueryBuilder withResultSetMapping(String resultSetMapping) {
this.resultSetMapping = resultSetMapping;
return this;
public Query build() {
Query nativeQuery = entityManager.createNativeQuery(query, resultSetMapping);
for (String name : parameters.keySet()) {
nativeQuery.setParameter(name, parameters.get(name));
return nativeQuery;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment