I have an sql query. Can anyone convert to hibernate criteria?
SELECT TH_ID,TH_NAME FROM t_o2_th_master WHERE TH_ID IN(SELECT TH_ID FROM t_o2_user_gameplay WHERE USER_ID=10010 AND STATUS_TYPE_CODE_ID=1303)
This is my entity class for fields name:
SELECT treasureHuntId,treasureHuntName FROM TreasureHuntMasterEntity WHERE treasureHuntId IN(SELECT treasureHuntId FROM UserGamePlayEntity WHERE userId:userID AND statusTypeCodeId:statusTypeCodeID)
change
WHERE userId:userID
to
WHERE userId = :userID
We can directly run SQL queries using hibernate. Hibernate provides two different types of queries
HQL queries. We can do everything that is possible in SQL
Criteria queries . We have define criteria based on objects.
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
Criteria criteria =session.createCriteria( t_o2_th_master.class );
criteria.createCriteria( "t_o2_user_gameplay", "user" );
criteria.add( Restrictions.eq( "user.userId", 10010 ) );
criteria.add( Restrictions.eq( "user.statusTypeId", 1303 ) );
t_o2_th_master masterList = criteria.list();
t_o2_th_master master=null;
if(masterList.size()>0){
master=masterList.get(0);
}
Related
How can I write this SQL query as a Hibernate JPA Criteria (with Restrictions, etc) in Java ?
SELECT q.*
FROM queue AS q
WHERE q.executed = false AND
q.queued_on = (SELECT min(queued_on) FROM queue WHERE item_id = q.item_id);
I only managed to write the first part like this:
getBaseCriteria()
.add(Restrictions.eq("executed", false))
// Missing Second Where Filter Here
.addOrder(Order.asc("queuedOn"))
.list();
Try to create a separate criteria instance for the subquery and simply add as another restriction as follows:
DetachedCriteria subCriteria = DetachedCriteria.forClass(Queue.class, "sub")
.add(Restrictions.eqProperty("sub.itemId","main.itemId"))
.setProjection(Projections.projectionList().add(Projections.min("sub.queuedOn")));
session.createCriteria(Queue.class, "main")
.add(Subqueries.propertyEq("main.queuedOn", subCriteria ));
.add(Restrictions.eq("main.executed", false));
.addOrder(Order.asc("main.queuedOn"))
.list();
I've written this in sql server:
select max(processed_trans_id) from EQUITY_TRANSACTION where transaction_date <= '2016-06-22' and company_id=75 group by comp_acct_id
But when I try to write the same in Hibernate Criteria, like this:
DetachedCriteria dCriteria = DetachedCriteria.forClass(EquityTransaction.class)
.add(Restrictions.eq("clientCompany.id", sb.getClientCompany().getId()))
.add(Restrictions.le("transactionDate", sb.getQualifyDate()))
.setProjection(Projections.projectionList()
.add(Projections.max("processedTransaction.id"), "processedTransaction.id")
.add(Projections.groupProperty("holderCompanyAccount.id")));
I get this as the sql query from hibernate:
select max(processed_trans_id), comp_acct_id from EQUITY_TRANSACTION where transaction_date <= '2016-06-22' and company_id=75 group by comp_acct_id
How do I replicate the original SQL query in Hibernate criteria?
I was able to resolve this using the following query. Worked like a charm!
DetachedCriteria dCriteriaEt1 = DetachedCriteria.forClass(EquityTransaction.class, "et1")
.add(Restrictions.eq("clientCompany.id", decldDvd.getClientCompany().getId()))
.add(Restrictions.le("transactionDate", decldDvd.getQualifyDate()))
.setProjection(Projections.projectionList()
.add(Projections.max("processedTransaction.id"), "processedTransaction.id"))
.add(Restrictions.eqProperty("et1.holderCompanyAccount.id", "et2.holderCompanyAccount.id"));
logger.info("Retrieving all qualified company account balances...");
Criteria getQualifiedBalances = dao.getSession().createCriteria(EquityTransaction.class, "et2")
.add(Subqueries.propertyIn("processedTransaction.id", dCriteriaEt1))
.add(Restrictions.gt("balance", 0l))
.setProjection(Projections.projectionList()
.add(Projections.property("holderCompanyAccount.id"),"holderCompanyAccount.id")
.add(Projections.property("balance"), "balance"))
.addOrder(Order.asc("holderCompanyAccount.id"))
.addOrder(Order.desc("processedTransaction.id"))
.setResultTransformer(new AliasToBeanNestedResultTransformer(EquityTransaction.class));
I have a class that uses Hibernate HQL queries. I would like to change these into Hibernate Criteria queries.
However, Hibernate Criteria is a lot harder for me to understand than HQL, even with tutorials. Could someone show me how one of the queries would look like using Hibernate Criteria/Filters?
Configuration configuration = new Configuration();
configuration.configure().setProperty("hibernate.show_sql", "false");
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(serviceRegistry);
Session session =sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from TABLENAME WHERE IDObject1= :idObjectA" +
"AND IDObject2= :idObjectB AND IDSettingOption = :idSettingOption");
query.setParameter("idObjectA", idObjectB);
query.setParameter("idObjectB", idObjectB);
query.setParameter("idSettingOption", idSettingOption);
List results = query.list();
Thanks in advance!
Criteria criteria = session.createCriteria( TABLENAME.class );
criteria.add( Restrictions.eq( "IDObject1" , idObjectB) );
criteria.add( Restrictions.eq( "IDObject2" , idObjectB) );
criteria.add( Restrictions.eq( "IDSettingOption" ,idSettingOption) );
List results = criteria.list();
Here you can read about Criteria API, it has a lot of examples:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html
List results = session.createCriteria(Entity.class)
.add(Restrictions.eq("IDObject1", idObjectA))
.add(Restrictions.eq("IDObject2", idObjectB))
.add(Restrictions.eq("idSettingOption", idSettingOption))
.list();
I need to do this query with Java + Hibernate.
SELECT
table2.id,
COUNT(table2.id) AS count
FROM
table1
JOIN table2
ON table1.fk_tb2 = table2.id --many2one
GROUP BY
table2.id
I would use DetachedCriteria class.....how can i do this ?
Try using projections like this:
Criteria table1Crit = session.createCriteria("table1");
Criteria table2Crit = table1Crit.createCriteria("table2", Criteria.INNER_JOIN);
table2Crit.setProjection( Property.forName("id").count() );
use your query with createNativeQuery method
I would like to use a hibernate criteria object as a subquery on a second criteria, like this:
DetachedCriteria latestStatusSubquery = DetachedCriteria.forClass(BatchStatus.class);
latestStatusSubquery.setProjection(Projections.projectionList()
.add( Projections.max("created"), "latestStatusDate")
.add( Projections.groupProperty("batch.id"))
);
DetachedCriteria batchCriteria = DetachedCriteria.forClass(BatchStatus.class).createAlias("batch", "batch");
batch.add( Property.forName( "created" ).eq( latestStatusSubquery ) );
The problem is that adding a groupProperty automatically add that property to the select clause on the subselect query and I can't find any way to stop this from happening.
The result, of course a DB error because the subquery returns too many values.
Does anyone know a way around this?
Try like below sample,
DetachedCriteria subquery = DetachedCriteria.forClass(CustomerCommentsVO.class, "latestComment");
subquery.setProjection(Projections.max("latestComment.commentId"));
subquery.add(Expression.eqProperty("latestComment.prospectiveCustomer.prospectiveCustomerId", "comment.prospectiveCustomer.prospectiveCustomerId"));
objCriteria = objSession.createCriteria(CustomerCommentsVO.class,"comment");
objCriteria.add(Subqueries.propertyEq("comment.commentId", subquery));
List lstComments = objCriteria.list();