Creating new Objects in JPQL returns only one object - jpa

I have a JPA Entity with a large number of fields and millions of records. For a report, I need only some of the fields. So I want to create an Object with the essential fields due to resource constraints. I tried to create a list of new objects in JPQL. It gives only one object as a result, where multiple objects are expected.
String j;
j = "select new lk.gov.health.phsp.pojcs.ClientEncounterComponentBasicDataToQuery("
+ "f.name, "
+ "f.code, "
+ "f.item.code, "
+ "f.shortTextValue, "
+ "f.integerNumberValue, "
+ "f.longNumberValue, "
+ "f.realNumberValue, "
+ "f.booleanValue, "
+ "f.dateValue, "
+ "f.itemValue.code"
+ ") ";
j += " from ClientEncounterComponentItem f "
+ " where f.retired=false "
+ " and f.encounter.id=:eid";
Map m = new HashMap();
m.put("eid", endId);
The EBJ is as follows.
public List<Object> findObjects(String jpql, Map<String, Object> parameters, TemporalType tt) {
TypedQuery<Object> qry = getEntityManager().createQuery(jpql, Object.class);
Set s = parameters.entrySet();
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
Object pVal = m.getValue();
String pPara = (String) m.getKey();
if (pVal instanceof Date) {
Date pDate = (Date) pVal;
qry.setParameter(pPara, pDate, TemporalType.DATE);
} else {
qry.setParameter(pPara, pVal);
}
}
try {
return qry.getResultList();
} catch (Exception e) {
return null;
}
}
What am I doing wrong? I am using EclipseLink as the persistence provider.

Related

set boolean value in sqlite android

I have column which is supposed to contain the true and false value in db. I understand that they should be in form of 0 and 1. I have an int column "status" but it always returns zero.
#Override
public void onCreate(SQLiteDatabase db) {
String create_table = "CREATE TABLE " + TABLE_NAME + "( "
+ "ID INTEGER PRIMARY KEY ,"
+ VALUE + " TEXT NOT NULL, "
+ STATUS + " INTEGER NOT NULL)";
db.execSQL(create_table);
}
public int getStatus(String _id,int status)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + STATUS + " FROM "
+TABLE_NAME+" WHERE " + _ID +" =? " , new String[] {_id});
if(cursor.moveToFirst()){
return cursor.getInt(cursor.getColumnIndex(STATUS));
} else {
return 0;
}
}
I need to set to true in the case below but item_status returns zero everytime. I checked the db and there is NULL in the whole status column.
if (success) {
status = 1;
int item_status = db.getStatus(fetchId(),status);
Toast.makeText(this, " item_status " + item_status , Toast.LENGTH_SHORT).show();
}

How to make a union query search using Criteria API

I tried to make a search in db for several fields using input string.
What i've got using HQL.
#Override
public List<Teacher> searchByString(String str) {
String[] fields = {"fam", "name", "otch", "phoneNumber"};
List<Teacher> result = new ArrayList<>();
for (int i = 0; i < fields.length-1 ; i++) {
result.addAll(em.createQuery(
"SELECT c FROM Teacher c WHERE lower(c." + fields[i] + ") LIKE lower(?1)")
.setParameter("1", "%" + str + "%")
.getResultList());
}
result.addAll(em.createQuery(
"SELECT c FROM Teacher c WHERE to_char(c." + "dateOfBirth, 'yyyy-mm-dd'" + ") LIKE ?1")
.setParameter("1", "%" + str + "%")
.getResultList());
return result;
}
This example working, but i need to have it in Criteria. I found nothing about "union" in Criteria API. How can i achive this result?

Select results truncated without error message

I'm using Google Cloud SQL from an App Engine application via Java and JDBC.
I select rows of a table using following code:
public void processGcmRegistrations(String whereCondition, String appName,
String[] appVariants, boolean onlyTestDevices,
String orderByCondition,
GcmRegistrationProcessor processor) throws DbException {
if (whereCondition == null && appName == null)
throw new IllegalArgumentException("One of the parameters \"whereCondition\", " +
"\"appNmae\" must not be null.");
if (whereCondition == null) {
whereCondition = "APP_NAME = '" + appName + "' " +
createInListCondition("APP_VARIANT", appVariants);
if (onlyTestDevices)
whereCondition += " AND TEST_DEVICE = 1 ";
}
String orderByConditionStr = "";
if (orderByCondition != null)
orderByConditionStr = " ORDER BY " + orderByCondition;
String selectStmt = "SELECT GCM_ID, GCM_REGISTRATION_TIME, APP_NAME, APP_VARIANT, " +
"INSTALLATION_ID, DEVICE, LAST_UPDATE " +
"FROM GcmRegistration WHERE " + whereCondition + orderByConditionStr;
log.info("GcmIds Select: " + selectStmt);
ResultSet rs = null;
try {
long start = System.currentTimeMillis();
rs = dbConnection.createStatement().executeQuery(selectStmt);
log.info("Select duration: " + ((System.currentTimeMillis()-start)/1000) + " secs.");
int count = 0;
while (rs.next()) {
GcmRegistration reg = new GcmRegistration();
reg.gcmId = rs.getString(1);
reg.gcmRegistrationTime = rs.getLong(2);
reg.appName = rs.getString(3);
reg.appVariant = rs.getString(4);
reg.installationId = rs.getString(5);
reg.device = rs.getString(6);
reg.lastUpdate = rs.getLong(7);
processor.processGcmRegistration(reg);
count++;
}
log.info(count + " GcmRegistrations processed.");
} catch (Exception e) {
String errorMsg = "Selecting GCM_IDs from table GcmRegistration failed.";
log.log(Level.SEVERE, errorMsg, e);
throw new DbException(errorMsg, e);
} finally {
if (rs != null)
rs.close();
}
}
I always execute this method with the same parameters and receive usually about 152000 rows.
In rare cases (I guess 1 from 50) I receive only about 62000 rows without any exception! rs.next() returns false, although not all result rows are delivered.
For Google: Last time this happened was 8/22/14 23:20 (MEST)

I want to fetch the values from AdvancedCriteria

I want to fetch the values from AdvancedCriteria
My Code is like this
Now how can I retrieve values from objects ?
How did you get the values from criteria?
AdvancedCriteria cr = filterBuilder.getCriteria();
JavaScriptObject jso = cr.getJsObj();
Map map = cr.getValues();
Set keys = map.keySet();
Iterator it = keys.iterator();
while( it.hasNext()){
String key = it.next().toString();
system.out.println("=> "+map.get(key));
}
Out put
=> AdvancedCriteria
=> and
=> [object Object]
To print advanced criteria with inner criterias and advanced criterias you can do something like this:
public void onClick(ClickEvent event) {
AdvancedCriteria crit = filterBuilder.getCriteria();
printCriteria(crit, 0);
}
public void printCriteria(AdvancedCriteria ac, int level) {
char[] indentArray = new char[level];
Arrays.fill(indentArray, '\t');
String indent = new String(indentArray);
OperatorId operator = ac.getOperator();
Criteria[] c = ac.getCriteria();
for (int i = 0; i < c.length; i++) {
if (c[i].isAdvanced()) {
System.out.println(indent + "(");
printCriteria(c[i].asAdvancedCriteria(), level + 1);
System.out.println(indent + ")");
} else {
System.out.println(indent +
c[i].getAttributeAsString("fieldName") + " " +
c[i].getAttributeAsString("operator") + " " +
c[i].getAttributeAsString("value"));
}
if ((i + 1) < c.length) {
System.out.println(indent + operator);
}
}

How to write a dynamic where 'like' query in Entity framework?

Here is my code:
//order my baselist is context.Entity
public static GridData Getdata<T>(ObjectSet<T> baseList,
int currentPage,
int rowsPerPage,
string sortcolumn,
string sortord,
string searchQuery,
string searchColumns)where T: class{
var query = baseList.OrderBy("it." + sortcolumn + " " + sortord);
string strPredicate = string.Empty;
if (!string.IsNullOrEmpty(searchColumns))
{
strPredicate = "it." + searchColumns + " LIKE #" + searchColumns + " ";
query = baseList.Where(strPredicate, new ObjectParameter(searchColumns, searchQuery)).OrderBy("it." + sortcolumn + " " + sortord);
}
}
My problem is i am trying to write down or form a like query in entity framework and seems like it does not support it.
You can use .Contains which is the LIKE operator equivalent in entity framework.
you can use this
query = baseList.Where(baseli=>baseli.Contains(searchColumns )).OrderBy("it." + sortcolumn + " " + sortord);
:)