Created
          July 19, 2018 21:33 
        
      - 
      
- 
        Save djangofan/e7ddb5e1a96316ee198f50f89c02defc to your computer and use it in GitHub Desktop. 
    An example of QueryManager in Java for JPA
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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