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...
Related
I'm using Hibernate Query Language(HQL) with Oracle database in my Java spring MVC application. I have write an HQL update query in this way:
String hql = "update " + MyModel.class.getName() + " e set e.field = " + value + " where ..."
//Acquiring session
...
Query query = session.createQuery(hql);
int result = query.executeUpdate();
The executeUpdate() method returns number of updated rows. But I want to get a list of the ids of updated rows after executing the update query. Is there any way of doing this in HQL?
As far as I know there is no such functionality in JPA/Hibernate. But you can create native query and use native SQL. I do not know oracle, but in PostgreSQL I would write :
String sql = "update table set field = :values where ... returning id";
Query query = session.createNativeQuery(sql);
query.setParameter("value", value);
List ids = query.list();
May be oracle have similar functional and this will help you.
Blaze-Persistence, a library that works on top of JPA/Hibernate, adds support for this.
Here some more information about that: https://persistence.blazebit.com/documentation/core/manual/en_US/index.html#returning-from-update-statement
I am using eclipse link as JPA and Oracle as DB. I am using getEntityManager().createNativeQuery in java. In my query I want to use IN clause but it is not working and no exception as well.
From page user passes the input as 336885,56239,895423
Sample Query
"select emp_name from emp where emp_id in ( ?id)"
query.setParameter("id", empBO.getEventIds());
I am using Java to convert the using split and concat
336885,56239,895423 to '336885','56239','895423'
but it is not working out for me.
I knew if we use JPQL this going to work for me. the reason behind choosing Native is to avoid creating Model objects for tables.
Update
I have used JPQL query since I need to deliver the code quickly. I have tried second answer what posted here. But no result came. when I get a free time I will try once again why IN is not working.
The reason why this wouldn't work with JPA is the same why this wouldn't work directly with JDBC - it is lack of support in JDBC of multi-valued parameters.
When JPQL processor sees in (?id) it converts it into an expression that its underlying SQL engine could "understand" - usually, something that looks like this:
WHERE emp_id IN (?id_0, ?id_1, ?id_2, ...)
This is supported by JDBC, so it executes without an error.
If you would like to perform a native query, you need to do this conversion yourself. Start with the template that you have, insert question marks for the number of IDs that you are sending, and bind IDs from the list to these parameters:
StringBuilder queryStr = new StringBuilder("select emp_name from emp where emp_id in (");
int[] ids = empBO.getEventIds();
for (int i = 0 ; i != ids.length() ; i++) {
queryStr.append("?id_");
queryStr.append(i);
}
queryStr.append(")");
... // Construct your query, then...
for (int i = 0 ; i != ids.length() ; i++) {
query.setParameter("id_"+i, ids[i]);
}
You can show the log of jpa to see the request in you code.
log4j.logger.org.hibernate=info<BR>
or
<logger name="org.hibernate"><BR>
<level value="info"/> <BR>
</logger><BR>
You can also try without parenthese :
"select emp_name from emp where emp_id in ?id"
Are you sure for ? ?
"select emp_name from emp where emp_id in :id"
Regards,
I am trying to update a Db2 database using Java and the following code:
String sSqlString = "UPDATE P6DEVCDB00.P6OSTAPF SET STATVAL = '" + sStatVal + "' WHERE OPIID = '" + sOperationsitemid + "' AND CONGRPC = '" + sConfigGrpCode + "'";
// Do your select on a Db table.
//statement = con.createStatement();
statement = con.prepareStatement(sSqlString);
int RowsAffected = statement.executeUpdate();
con.commit();
System.out.println(RowsAffected);
I then get the following error :
DB2 SQL Error: SQLCODE=-7008, SQLSTATE=55019, SQLERRMC=P6OSTAPF ;
P6DEVCDB00;3, DRIVER=3.58.81
I have printed out the sql that it's going to run :
UPDATE P6DEVCDB00.P6OSTAPF SET STATVAL = 'ON'
WHERE OPIID = 'B20120707000681531' AND CONGRPC = 'STKLSTSTAT
When I run this sql directly with a SQLUI tool it works and the record gets updated...
Your problem is that you're attempting to use transactions over tables that are not 'journaled' - that is, setup for transactions.
Ideally, you should set up all tables (that will be run under a transaction) as journaled, specifically to test that property; regardless of being able to simulate failures, you need to make sure that your code can handle being under transactions.
Also, depending on your situation, you may not need to explicitly manage transactions. If you're using a framework like Spring, they can usually manage transactions for you, although this will usually mean that you still need journaling on your iSeries tables.
If you're just trying to test basic code behavior, look into using an in-memory database, such as HSQLDB (can emulate some LUW DB2 behavior, but not library lists, unfortunately) - this will absolve you of the need to have a connection to your box, and to set up journaling.
I'm using Hibernate for database access. I'm using the following query in my code to fetch the data I need:
SELECT proasset
FROM com.company.claims.participant.AbstractBeneficiary bene
JOIN bene.approvals approval
JOIN bene.proassetkey proasset
join proasset.relatedparties proassetparties
WHERE approval.user_dt > :currentDate
AND approval.user_type = :userType
I'm using it as query in the following:
Query q = this.getSessionFactory().getCurrentSession().createSQLQuery(query.toString())
q.setDate("currentDate", new Date());
q.setString("userType", APPROVER_USER_TYPE);
List<ProAsset> proassets = q.list();
However, I encounter the following when trying to run it:
SQL Error: 933, SQLState: 42000
ORA-00933: SQL command not properly ended
If it matters, the query is being constructed using a StringBuilder and it uses \n to break the lines
Any thoughts on the problem?
It looks like you are trying to mix ORM with a native (plain old SQL) query.
createSQLQuery requires native SQL. You are using classes instead of table names. Try a read of this:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html
In short you need to write a query like:
select fu
from bar
where situation = 'snafu'
Perhaps you are really wanting to write a namedQuery? They use ORM syntax where you join entities as it seems you are doing in your example.
Check these examples out:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html#querysql-namedqueries
Correct the syntax by removing the inappropriate clauses. It may be possible to duplicate the removed clause with another SQL statement. For example, to order the rows of a view, do so when querying the view and not when creating it. This error can also occur in SQL*Forms applications if a continuation line is indented. Check for indented lines and delete these spaces.
Alright, so I used createSQLQuery() instead of createQuery() and I was using the column names instead of the variable names.
Here's what my code looks like now:
StringBuilder query = new StringBuilder();
query.append("SELECT proasset\n" +
"FROM com.avivausa.claims.participant.AbstractBeneficiary bene\n" +
"JOIN bene.approvals approval\n" +
"JOIN bene.proAsset proasset\n" +
"join proasset.additionalParties proassetparties\n" +
"WHERE approval.userDate < current_date()\n");
query.append("AND approval.userType = ").append(UserAuditType.APPROVER);
Query q = this.getSessionFactory().getCurrentSession().createQuery(query.toString());
List<ProAsset> proassets = q.list();
Obviously I made some refactoring changes too, but the main changes were what I stated above. Thank you for your responses though!
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