1 19 20 package org.apache.cayenne.jpa; 21 22 import javax.persistence.Query; 23 24 import org.apache.cayenne.ObjectContext; 25 import org.apache.cayenne.map.DataMap; 26 import org.apache.cayenne.query.SQLTemplate; 27 28 public class JpaNativeQuery extends JpaQuery { 29 30 private static final String POSITIONAL_PARAM_PREFIX = "positional_"; 31 32 public JpaNativeQuery(ObjectContext context, String sqlString, Class resultClass) { 33 super(context); 34 setQuery(new SQLTemplate(resultClass, processSQLString(sqlString))); 35 } 36 37 public JpaNativeQuery(ObjectContext context, String sqlString, String dataMapName) { 38 super(context); 39 DataMap map = context.getEntityResolver().getDataMap(dataMapName); 40 setQuery(new SQLTemplate(map, processSQLString(sqlString))); 41 } 42 43 protected String processSQLString(String sqlString) { 44 47 50 sqlString = sqlString.replace(':', '$'); 51 52 if (sqlString.indexOf('?') >= 0) { 54 sqlString = sqlString.replaceAll("\\?([0-9]+)", "\\$" 56 + POSITIONAL_PARAM_PREFIX 57 + "$1"); 58 } 59 60 return sqlString; 61 } 62 63 72 public Query setParameter(int position, Object value) { 73 74 String name = POSITIONAL_PARAM_PREFIX + Integer.toString(position); 77 try { 78 return setParameter(name, value); 79 } 80 catch (IllegalArgumentException e) { 81 throw new IllegalArgumentException ("Invalid positional parameter: " 82 + position, e); 83 } 84 } 85 86 } 87 | Popular Tags |