How to make a union query search using Criteria API - postgresql

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?

Related

How do I connect my Zoho Flow Custom Deluge Function? I keep getting error 57 (Unauthorized Access)

I am working on a project that involves Zoho Flow. We created a custom function that should update the item stock and status based on the sales order. However, when I try to run it I get error 57 (Unauthorized Access). I've tried multiple things and it still doesn't work. The connection seems fine when I tested it but it still work run.
See code below:
string Update_stock_or_change_inactive_item(string salesOrderId, string organization)
{
output = "";
salesOrder = zoho.inventory.getRecordsByID("SalesOrders",organization,salesOrderId);
output = salesOrder + " ";
productDetails = ifnull(salesOrder.get("line_items"),"");
lineitems = productDetails.toJSONList();
for each item in lineitems
{
itemMap = item.toMap();
productId = ifnull(itemMap.get("product_id"),"");
productName = ifnull(itemMap.get("name"),"");
quantity = ifnull(itemMap.get("quantity"),"0");
product = zoho.inventory.getRecordsByID("Items",organization,productId);
productMap = product.toMap();
//get product stock
availableStock = ifnull(productMap.get("actual_available_stock"),"0");
availableStockForSale = ifnull(productMap.get("actual_available_for_sale_stock"),"0");
status = ifnull(productMap.get("status"),"");
output = output + status;
//check and update stock
if(availableStock < quantity || availableStockForSale < quantity)
{
//update item to ensure that it is in stock
new_values = Map();
new_values.put("actual_available_stock",quantity);
new_values.put("actual_available_for_sale_stock",quantity);
new_values.put("status","active");
response = zoho.inventory.updateRecord("Items",organization,productId,new_values);
output = output + productName + " - stock updated to " + quantity + ", ";
}
else if(status != "active")
{
new_values.put("status","active");
output = output + productName + " - status updated to active, ";
}
else
{
output = output + productName + " stock not updated, ";
}
}
return output;
}

Creating new Objects in JPQL returns only one object

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.

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);
:)

Entity SQL Datetime Syntax error

Anyone know What is wrong with my syntax here? I am making dynamic eSQL Queries and running into an error when trying to make where condition for DateTime data type. This is the error:
The query syntax is not valid. Near term '2011', line 1, column 135.
If it matters the DateTime type in my entity is actually nullable DateTime?
However, I thought this is the correct syntax from everything I've read.
Here is the code:
List<EntityFilter<FirstRead>> filters = new List<EntityFilter<FirstRead>>()
{
new EntityFilter<StudyFirstRead> { PropertyName = "username", OpType = ExpressionType.Equal, Value = "cwoodhouse" },
new EntityFilter<StudyFirstRead> { PropertyName = "FirstRead", OpType = ExpressionType.LessThan, Value = "DATETIME'2011-02-01 00:00'" }
};
Where EntityFilter is:
public class EntityFilter<T>
{
public string PropertyName { get; set; }
public ExpressionType OpType { get; set; }
public object Value { get; set; }
And I am building dynamic queries like so:
StringBuilder builder = new StringBuilder();
int counter = 0;
string baseStr = #"SELECT VALUE val FROM " + contextName + "." + tableName + " AS val WHERE val.";
builder.Append(baseStr);
foreach (EntityFilter<T> filter in filters)
{
//builder.Append(filter.PropertyName + " " + filter.OpTypeString() + " #p" + counter);
builder.Append(filter.PropertyName + " " + filter.OpTypeString() + "'" + filter.Value + "'");
counter++;
if (counter < filters.Count)
builder.Append(" AND val.");
else
{
break;
}
}
return builder.ToString();
It actually is the correct syntax for entity SQL (different than regular SQL or T-SQL).
Turns out the problem was too many single quotes, because I had them in both the EntityFilter object and the method that built the dynamic query.
according to you code the end of your SQL statement would produce something like
AND val.FirstRead = 'DATETIME'2011-02-01 00:00''
when executed you will get error
Error 102: Incorrect syntax near '2011'.
obviously that is not syntactically correct SQL, the quick fix whould be to have your filters collection as such:
List<EntityFilter<FirstRead>> filters = new List<EntityFilter<FirstRead>>() {
new EntityFilter<StudyFirstRead> {
PropertyName = "username",
OpType = ExpressionType.Equal,
Value = "cwoodhouse"
}, new EntityFilter<StudyFirstRead> {
PropertyName = "FirstRead",
OpType = ExpressionType.LessThan,
Value = "2011-02-01 00:00"
}
};