Getting error in joining tables using hibernate - java

I am trying to join multiple table using hibernate but its not working for me can someone please help me out.
I tried Criteria that was not working then thought of using query even that is not working
My code looks like
final Session session = getSession();
String query = "SELECT r.REFERRER_ID from REFERRAL_PAYMENT_INFO r, SIGNUP_REFERRAL s";
Query q = session.createQuery(query);
List list = q.list();
I am getting this error -
"Caused by: org.hibernate.hql.ast.QuerySyntaxException:
REFERRAL_PAYMENT_INFO is not mapped [SELECT r.REFERRER_ID from REFERRAL_PAYMENT_INFO
r, SIGNUP_REFERRAL s]"

You must use the classes (entities) you mapped in HQL queries. If you want to use normal SQL, then you have to call session.createSQLQuery().
Look at the documentation for hibernate session:
http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html

Related

no result after transforming postgres query to jpql in spring data jpa

I am trying to write a query to fetch list as this query is native sql query, all I need is to transform to spring jpql in which I am failing badly. if there is any link related to this please let me know
I am supposed to get list from this query. as this query is working fine with postgres console but when I even tried this with spring jpa as native query
it is showing results in console but not fetching in service layer [edit:] I mean not calculating any result set.
I am sure I am missing some important/small thing here.
below is the native postgres query
selcet t.id,count(*), count(*) filter (where t.status = 'DONE') from table t where t.id in ([list]) group by t.id
what Im trying is
SELECT t.id, count(t), count(t.id) where staus = 'DONE' from Table t where t.id in ([list]) group by t.id
edit: with constructor based query this is not even working
I am not even sure how to start this query
while being new to this I am not even able to start how to solve this.
Any hint, insight will be useful

How to get count using JPA

I am writing very simple native query in JPA, it is executing in oracle if I run it directly but failed when run trough JPA.
String sql = "select count(*) from demo.sb_test_config cf, isisdba.sb_transpoter st where cf.policy_id = st.policy_id " +
"and cf.payment_type = 'PAID' and st.sb_t_id = :tId" ;
Query query = em.createNativeQuery(sql);
query.setParameter("tId", 8);
Long response = (Long)query.getSingleResult();
Can some help to find the root cause. What I missing while executing JPA.
Thanks in advance
How does it fail in JPA?
I can see that you are attempting to use old SQL join syntax to get data from two different schemas - is JPA set to allow you to do that?
You did not even say how your attempts fail...

MSSQL Invalid Syntax with Hibernate when using DISTINCT?

So I have this piece of Java code:
final Query query = session.createSQLQuery("SELECT DISTINCT(expense_document.id) FROM expense_document JOIN generic_object ON expense_document.id = generic_object.id JOIN expense_document_item ON expense_document_item.document_id = expense_document.id JOIN generic_object ON expense_document_item.id = generic_object.id WHERE expense_document.client_id = :client_id").setParameter("client_id", client.getId()).setMaxResults(1000);
and when this code is executed I get:
org.hibernate.exception.SQLGrammarException: could not execute query
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'from'.
I can not find what MS SQL does not like about this query. When I am connected to MySQL, this line will not cause any problems.
Try removing the parenthesis around the parameter to the distinct keyword.
Use it like this:
select distinct something from somewhere
Your query looks fine.. are you using an up to date driver for MSSQL?
See how to configure hibernate config file for sql server for supported SQL server drivers.
You should be able to do:
final Query query = session.createSQLQuery("SELECT DISTINCT(expense_document.id) FROM expense_document JOIN generic_object ON expense_document.id = generic_object.id JOIN expense_document_item ON expense_document_item.document_id = expense_document.id JOIN generic_object ON expense_document_item.id = generic_object.id WHERE expense_document.client_id = :client_id").setParameter("client_id", client.getId()).setMaxResults(1000);
or
final Query query = session.createSQLQuery("SELECT DISTINCT expense_document.id FROM expense_document JOIN generic_object ON expense_document.id = generic_object.id JOIN expense_document_item ON expense_document_item.document_id = expense_document.id JOIN generic_object ON expense_document_item.id = generic_object.id WHERE expense_document.client_id = :client_id").setParameter("client_id", client.getId()).setMaxResults(1000);
However, if you're using hibernate, why aren't you using HQL, JPA Query language or Criteria? That should ensure that you don't have to change SQL syntax depending upon the vendor as they differ slightly in different flavours. I feel using JPA with entity manager might be the way forward if you're switching between different databases as createSqlQuery will send the string as native SQL to the vendor.
Hibernate EntityManager implements the programming interfaces and
lifecycle rules as defined by the JPA 2.0 specification
https://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html_single/
If you're using something like hibernate, then createSqlQuery is really good for sending vendor specific queries when you want to set hints for example.

How to use CONCAT_WS() in Hibernate HQL

To combine multiple columns as one,
I found one answer
SELECT id,CONCAT_WS(',', field_1, field_2, field_3, field_4) list
FROM `table`;
This query working fine in SQL but it gives me error in HQL:
Error is .
(java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode )
please help me to find out what wrong i did, help me to know how to use CONCAT_WS() IN HQL
below how i written my HQL query
SELECT C1._URI,C1.HEALTH_FACILITY,C1.DISTRICT,CONCAT_WS(',', C1.BLOCKS_OF_BHUBRI, C1.BLOCKS_OF_GOLAGHAT, C1.BLOCKS_OF_HAILAKANDI) as Block_name
FROM GapAnalysisWashInHealthFacilitiesCore C1
any help will appreciate
CONCAT_WS is a function specific to mySql. HQL is a generic language and not aware of native SQL functions and syntax. If you really need the function, then you should use Hibernate's API for native SQL.
Session session = ...;
Query query = session.createSQLQuery("
SELECT id,CONCAT_WS(',', field_1, field_2, field_3, field_4) Block_name FROM `table`");
List result = query.list();
Then you may like to have a look at Result Transformers to get result as list of GapAnalysisWashInHealthFacilitiesCore objects.

Executing hibernate template's findByNamedQuery

I'm pretty new to hibernate and I was trying it out in one of my applications. I chose to use annotation session factory bean and my editor generated entity classes for each table from the DB which had named queries. hibernateTemplate.findByAll worked fine. But when I tried hibernateTemplate.findByNamedQuery("findById", "<some_id>"), it gave an error: java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based. After a bit of googling, tried out multiple solutions:
Changed the namedQuery that was generated by editor from : #NamedQuery(name = "Table.findById", query = "SELECT u FROM Table t WHERE t.id = :id"), to : #NamedQuery(name = "Table.findById", query = "SELECT u FROM Table t WHERE t.id = ?") but got the same error.
Tried using hibernateTemplate.findByNamedParam but ended up getting error: java.lang.IllegalArgumentException: node to traverse cannot be null!
I can use hibernateTemplate.find() to achieve this but how do I use findByNamedQuery/Param methods to achieve the same since the documentation says these methods may be used to fetch records based on a field?

Categories