hibernate criteria query in java - java

I have an ADD form which adds name, start date and end date into a database. What I want is to make a query which satisfies that if another date is entered for the same name, it will return false. Any suggestions please?
This is what I've tried, but it fails:
DetachedCriteria criteria = createCriteria();
criteria.add(Restrictions.ge("start_date", startDate));
criteria.add(Restrictions.lt("end_date", endDate));
criteria.add(Restrictions.eq("name", name));

Related

Hibernate Subqueries

I have a situation where I need to convert a query like :-
select hostname, avg(cpu_utilization_percentage) from cpu_utilization where timestamp In (select distinct(timestamp) from report.cpu_utilization order by timestamp desc limit 6) group by hostname
Now, this data I want to fetch using hibernate so I have used Subqueries:-
// For inner Query
DetachedCriteria subquery = DetachedCriteria.forClass(CpuUtilizationDTO.class);
subquery.setProjection(Projections.distinct(Projections.property("timeStamp"))).addOrder(Order.desc("timeStamp"));
subquery.getExecutableCriteria(session).setMaxResults(6);
// For Outer Query
Criteria query = session.createCriteria(CpuUtilizationDTO.class);
ProjectionList list = Projections.projectionList();
list.add(Projections.groupProperty("hostName"));
list.add(Projections.avg("cpuUtilizationpercentage"));
query.setProjection(list);
List<Object[]> obj= (List<Object[]>)hibernateTemplate.findByCriteria(query);ction(list);
//Now to add subquery into main query I am using
query.add(Subqueries.propertyIn("timeStamp", subquery));
But everytime I am getting the average of entire data. Can anyone please help that where did I miss?

Spring Data: multiple IN's inside a query

I have the following method inside my spring jpa data interface:
List<TransactRepViewModel> findByClientIdInAndClDateBetween(List<String> clientIdList, Date startDate, Date endDate)
The problem is that I get this error due to my clientIdList having about 5000-20000 String objects inside:
ORA-01795: maximum number of expressions in a list is 1000
Is there a way to use multiple IN's inside a spring-data query and split up my list to avoid the error?
Update:
Ths is how I get my client object list:
List<ClieTabModel> clieTabModelList = clieTabModelRepository.findByCompanyId(companyViewModel.getId());
This is how I get the list of client Id's:
List<String> clientIdList = new ArrayList <>();
for (ClieTabModel clieTabModel : clieTabModelList) {
clientIdList.add(clieTabModel.getClientId());
}
You can use the following query:
#Query("select u from User u where u.id in :clientIds and :startDate=? and endDate= :endDate")
List<TransactRepViewModel> findByClientIdInAndClDateBetween(Set<String> clientIds, Date startDate, Date endDate)
As I see your ER model should look like this:
Transact >--- Client >--- Company.
So, in this case you can write follow query:
List<TransactRepViewModel> findByClientCompanyIdAndClDateBetween(String companyId, Date startDate, Date endDate)

Retrieving date via Criteria fails

I want to retrieve through Hibernate via Criteria the instances which in their date column have the current date.
1) So in MySQL DB via MySQL_Workbench I inserted an instance writing in the current date '2015-07-25'.
2) My java code looks like this :
Date date = new Date();
factory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
Criteria cr = session.createCriteria(Logger.class);
//the following date-like cr. fails
cr.add(Restrictions.eq("RunDate",date));
//this cr. runs fine alone retreiving the requested instances
cr.add(Restrictions.like("Name", "John"));
//The following work fine
cr.setProjection(Projections.sum("Contacts"));
long resultCount = (long)cr.uniqueResult();
System.out.println(resultCount);
...
When running with the date criteria I have a null pointer exception.I tried also cr.like,cr.ge ... same results.
What do you have as a value in your database?
if your date in your DB has time value as well and you only want to compare with the current day, you should do basically the following:
WHERE RunDate >= '2015-07-25 00:00:00' AND RunDate <= '2015-07-25 23:59:59'
like that only in an equivalent to the Criteria API
regards

Select rows with max date hibernate

I need to write a criteria query for selecting rows with max date:
Criteria criteria;
//getting criteria
criteria.add(Restrictions.sqlRestriction("{alias}.date = (__QUERY_FOR_MAX_DATE__)"));
Is it possible to avoid writting sqlRestriction derictly and do it merely with Criteria query?
I mean applying some projections, or something similar... Without writing the sql-restriction explcicitly.
DetachedCriteria innerCriteria = DetachedCriteria.forClass(ClassName.class, "inner")
.setProjection(Projections.projectionList().add(Projections.max("inner.dateColumnName")));
Criteria crit = session.createCriteria(ClassName.class, "outer");
crit.add(Subqueries.propertyEq("outer.dateColumnName", innerCriteria));

Filtering records in app-engine (Java)

I have following code running perfectly. It filter records based on single parameter.
public List<Orders> GetOrders(String email)
{
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Orders.class);
query.setFilter("Email == pEmail");
query.setOrdering("Id desc");
query.declareParameters("String pEmail");
query.setRange(0,50);
return (List<Orders>) query.execute(email);
}
Now i want to filter on multiple parameters. sdate and edate is Start Date and End Date.
In datastore it is saved as Date (not String).
public List<Orders> GetOrders(String email,String icode,String sdate, String edate)
{
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Orders.class);
query.setFilter("Email == pEmail");
query.setFilter("ItemCode == pItemCode");
query.declareParameters("String pEmail");
query.declareParameters("String pItemCode");
.....//Set filter and declare other 2 parameters
.....//
......
query.setRange(0,50);
query.setOrdering("Id desc");
return (List<Orders>) query.execute(email,icode,sdate,edate);
}
Any clue?
My first problem is solved. But still have some problem
1: How I can filter by Date parameter (Getting as string in jsp) ?
2: The query.execute() method support upto 3 parameters. Is it possible to pass more?
You can't use multiple SetFilter() to setup multiple conditions. You must use a single if-like condition, so it will be
query.setFilter("Email == pEmail && ItemCode == pItemCode");
same for declareParameters with a comma-separeted list as follows
Query.declareParameters("String pEmail, String pItemCode");

Categories

Resources