Convert mysql query to JPQL query - java

How can i state the following mysql query in JPQL
select * from Price WHERE `valueDate` = (SELECT MAX(`valueDate`) FROM Price) and fundId = 2930
what i have tried is the following:
"select a from Price a where a.valueDate = select MAX(a.valueDate) and a.fund.id = :" +Price.QUERY_PARAM_FUND_ID
but get errors on that approach :
Caused by: <openjpa-2.3.0-r422266:1540826 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: "Encountered "MAX" at character 50, but expected: ["AND", "GROUP", "HAVING", "OR", "ORDER", <EOF>]." while parsing JPQL "select a from Price a where a.valueDate = select MAX(b.valueDate) from Price b and a.fund.id = :fundId"

I think it will work if you will added bracket before and after sub-query like.
"select a from Price a where a.valueDate = (select MAX(a.valueDate) from Price) and a.fund.id = :" +Price.QUERY_PARAM_FUND_ID
else let me say some thing related to hibernate implementation of JPA Specification.
If you have Hibernate model named 'Price' and you are going to do query through that model then. the HQL will be like that
try {
final StringBuilder qry = new StringBuilder();
qry.append(" SELECT")
.append(" FROM Price p")
.append(" WHERE p.valueDate = (SELECT MAX(pr.valueDate) FROM Price pr)")
.append(" AND p.fundId = :fundId");
return getJpaTemplate().execute(new JpaCallback() {
public Object doInJpa(EntityManager em)
throws PersistenceException {
Query q = em.createQuery(qry.toString());
q.setParameter("fundId", fundId);
return q.getResultList();
}
});
} catch (RuntimeException re) {}

Related

Query with 3 tables in native sql with hibernate

I have 3 tables related with their FK and I trying to do a native query selecting entities joined. I did with 2 tables joined and it worked, but it does not work with 3.
This is my generic method for it
public List<Object[]> select3Tables(String sql, String parameter,
String tableAlias, String entityName, String tableAlias2, String path,
String tableAlias3, String path2){
Transaction tx = null;
List<Object[]>returnList = null;
try {
Query query = session.createNativeQuery(sql)
.addEntity(tableAlias, entityName)
.addJoin(tableAlias2, path)
.addJoin(tableAlias3, path2)
.setParameter("parameter", parameter);
returnList = query.getResultList();
tx.commit();
} catch (HibernateException e) {
if(tx!=null) tx.rollback();
System.err.println(e.getMessage());
e.printStackTrace();
}
and here is where I triying to do it.
public List<Compra> selectCompraByPropietario(final String dniPropitario) {
Compra compra = new Compra();
String sql = "SELECT * FROM Compras c "
+ "JOIN Montes m ON c.id_compra = m.compraFK_id_compra "
+ "JOIN Propietarios p ON m.propietarioFK_id_propietario = p.id_propietario"
+ "WHERE p.dni =:parameter";
List<Object[]> list = new HibernateSession().select3Tables(sql, dniPropitario, "compras",
"backend.entities.Compra", "m", "compras.montes", "m", "propietarios.montes");
for(Object[]listData : list) {
compra = (Compra) listData[0];
data.add(compra);
}
System.out.println("tamaño de data " + data.size());
return data;
}
Currently I´m getting an error "could not determine fetch owner : null"
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.HibernateException: Could not determine fetch owner : null
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1626)
at org.hibernate.query.Query.getResultList(Query.java:165)
at backend.HibernateSession.select3Tables(HibernateSession.java:149)
at backend.repositories.CompraOperations.selectCompraByPropietario(CompraOperations.java:90)
at backend.MainBackend.main(MainBackend.java:54)
Caused by: org.hibernate.HibernateException: Could not determine fetch owner : null
at org.hibernate.loader.custom.CustomLoader.determineAppropriateOwnerPersister(CustomLoader.java:292)
any idea what am I doing wrong and how to make it work?
Thank you.
I have faced quite similar problems like you
Everything seems fine to me.
Just add a space after
+ "JOIN Propietarios p ON m.propietarioFK_id_propietario = p.id_propietario"
Write it as
+ "JOIN Propietarios p ON m.propietarioFK_id_propietario = p.id_propietario "
Hope this helps

Java SQL Resultset DataTypes

I’m a java novice and have been tinkering with an existing Proc. I’m attempting to perform an out.write on a value derived from a SQL resultset 'Grid_ProjectCode’, as shown here:
sStmt=null;rs=null;sql=null;
sStmt = conn.createStatement();
sql = "select Proj_Code, Placement_ACR, Category_ID, Alt_Aisle_Shelf, Placement_Start_Dt, Placement_End_Dt, Sales_Manager from DH_CURRENT_FUTURE_INVENTORY_VW where Placement_ACR in ('banFSI_ROI', 'banFSI','FSI')";
rs = sStmt.executeQuery(sql);
while ( rs.next() )
{
String Grid_ProjectCode = rs.getString("Proj_Code");
String Dup_Placement_ACR = rs.getString("Placement_ACR");
if (plCode.equalsIgnoreCase(Dup_Placement_ACR))
{
out.write("Dupe Found");
out.newLine();
out.write(Grid_ProjectCode);
out.newLine();
}
}
if(conn != null) { rs.close(); sStmt.close(); }
The Proc fails with the following error (runs as expected when the second out.write is removed/commented):
java.lang.ClassCastException: [Ljava.lang.Integer; incompatible with
[Ljava.lang.String;
The Proj_Code field referred to in the SQL query is an NVARCHAR2 defined in an Oracle Exadata schema.
The error suggests some sort of data type mismatch, but I’m not sure how this is can be fixed; would really appreciate some guidance.
Edited to include DDL for DH_CURRENT_FUTURE_INVENTORY_vw:
CREATE OR REPLACE FORCE VIEW "UNICA_F1"."DH_CURRENT_FUTURE_INVENTORY_VW" ("PROJ_CODE", "FLAG_PROJ_REQUEST", "OBJECT_ID", "UAP_GRID_ROW_ID", "PLACEMENT_IMPRESSIONS", "SUPPLIER_CATEGORY", "PLACEMENT_CLASH", "PLACEMENT_NAME", "PLACEMENT_AISLE_SHELF", "PLACEMENT_START_DT", "PLACEMENT_RATE", "PLACEMENT_SIZE", "PLACEMENT_END_DT", "PLACEMENT_DURATION", "PLACEMENT_ACR", "SALES_VALUE", "NOTES", "STATUS", "AD_SERVER", "UNIT_NR", "SORT_ORDER", "CATEGORY_ID", "AISLE_SHELF_ID", "PLACEMENT_COUNT", "RETAIL_ACR", "ALT_AISLE_SHELF", "PLACEMENT_SIZE2", "PLACEMENT_SIZE3", "PLACEMENT_SIZE4", "PLACEMENT_SIZE5", "CREATIVE_YN", "CPM", "CREATIVE_SIZE", "PRODUCT_ID", "SALES_AREA", "IMPRESSION_GOAL", "CLIENT_CATEGORY", "CLIENT_SUB_CAT", "BRAND_NM", "FORMAT_DESC", "IMPRESSION_CPM", "IMPRESSION_VALUE", "CREATIVE_COST", "SIZE_DESC", "DELIVERY_PROCESS", "PACKAGE_FLAG", "PACK_ID", "RETARGETING_FLAG", "BATCH_FLAG", "BASE_COST", "DISCOUNT", "CATEGORY", "SALES_MANAGER") AS
Select
PROJ_CODE,
FLAG_PROJ_REQUEST,
OBJECT_ID,
UAP_GRID_ROW_ID,
PLACEMENT_IMPRESSIONS,
SUPPLIER_CATEGORY,
PLACEMENT_CLASH,
PLACEMENT_NAME,
PLACEMENT_AISLE_SHELF,
PLACEMENT_START_DT,
PLACEMENT_RATE,
PLACEMENT_SIZE,
PLACEMENT_END_DT,
PLACEMENT_DURATION,
PLACEMENT_ACR,
SALES_VALUE,
NOTES,
STATUS,
AD_SERVER,
UNIT_NR,
SORT_ORDER,
CATEGORY_ID,
AISLE_SHELF_ID,
PLACEMENT_COUNT,
RETAIL_ACR,
ALT_AISLE_SHELF,
PLACEMENT_SIZE2,
PLACEMENT_SIZE3,
PLACEMENT_SIZE4,
PLACEMENT_SIZE5,
CREATIVE_YN,
CPM,
CREATIVE_SIZE,
PRODUCT_ID,
SALES_AREA,
IMPRESSION_GOAL,
CLIENT_CATEGORY,
CLIENT_SUB_CAT,
BRAND_NM,
FORMAT_DESC,
IMPRESSION_CPM,
IMPRESSION_VALUE,
CREATIVE_COST,
SIZE_DESC,
DELIVERY_PROCESS,
PACKAGE_FLAG,
PACK_ID,
RETARGETING_FLAG,
BATCH_FLAG,
BASE_COST,
DISCOUNT,
CATEGORY,
SALES_MANAGER
from
(
select b.Proj_Code, b.Flag_Proj_Request, a.*, c.Category, d.Sales_Manager
from dh_ddp_inventory a
inner join uap_projects b on a.Object_ID = b.Project_ID
inner join dh_lkp_taxo_categ_vw c on a.Category_ID = c.Category_ID
inner join dh_ddp_Request d on a.Object_ID = d.Object_ID
where b.Flag_Proj_Request = 'Y' and a.Placement_End_Dt >= Current_date
and b.Proj_Code not in (select Proj_Code from uap_projects where Flag_Proj_Request = 'N')
Union
select b.Proj_Code, b.Flag_Proj_Request, a.*, c.Category, d.Sales_Manager
from dh_ddp_inventory a
inner join uap_projects b on a.Object_ID = b.Project_ID
inner join dh_lkp_taxo_categ_vw c on a.Category_ID = c.Category_ID
inner join dh_ddp_Request d on a.Object_ID = d.Object_ID
where b.Flag_Proj_Request = 'N' and a.Placement_End_Dt >= Current_date
)
Order By Proj_Code asc, Object_ID desc, Placement_Name asc;
Somewhere you do in some form or the other:
String[] stringArray = ...;
Integer[] intArray = (Integer[]) stringArray;
As [Ljava.lang.Integer =
array ([)
of class java.lang.Integer (L)
To drill down to the error:
try {
... code ...
} catch (ClassCastException e) {
e.printStackTrace(); // To System.err.
e.printStackTrace(System.out); // To System.out.
logger.error("OMG", e); // To logger if there is one.
throw e; // Act as is the exception was not thrown
}
Look at the stack trace, it also lists the source causing the error, together with the line number.

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to className

Code:
public void getDetails() {
try {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);
List<CrbtSubMasterDemo> itr = query.list();
session.getTransaction().commit();
for (CrbtSubMasterDemo pojo : itr) {//excepion line
System.out.println("[" + pojo.getMobile() + "]");
}
} catch (Exception e) {
e.printStackTrace();
}
}
CrbtSubMasterDemo is pojo mapped with the db.
When I try to run it, it gives following Exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.telemune.demoPojo.CrbtSubMasterDemo
at com.telemune.demoHibernate.QueryTester.getDetails(QueryTester.java:57)
at com.telemune.demoHibernate.QueryTester.main(QueryTester.java:23)
The question is query.list() is returning the list of objects of pojo class. Then why is this Exception. I am new to Hibernate, sorry if its a silly question.
When you write this:
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Your result set is not a List of CrbtSubMasterDemo
Try to write:
String hql = "select FROM CrbtSubMasterDemo c where rownum<20";
Another way is define a new constructor of CrbtSubMasterDemo where you pass only two fields c.mobile, c.password
so your query becomes:
String hql = "select new " + CrbtSubMasterDemo.class.getName() + "(c.mobile, c.password) FROM CrbtSubMasterDemo c where rownum<20";
If you follow this solution, remeber to add a default constructor too (without parameters), so in your pojo you have:
public CrbtSubMasterDemo(String mobile, String password) {
this.mobile = mobile;
this.password = password
}
and
public CrbtSubMasterDemo() {
}
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);
Result of this will be List<Object[]>
List<Object[]> itr = query.list();
for (Object[] row : itr) {
System.out.println(String.format("mobile:%s, password:%s", row[0], row[1]));
}
if mobile and password are strings, of course. You can use a transformer to transform results directly to CrbtSubMasterDemo.
Hibernate 3.2: Transformers for HQL and SQL
FluentHibernateResultTransformer
Sir, Many times user faces this kinda requirements . Hibernate has ResultTransformer to convert a hql/sql in Object.
public CrbtSubMasterDemo{
private Stirng mobile;
private String password;
public CrbtSubMasterDemo(){
--------------
}
#####after setting the transation set whichever columns you are selecting should be given as name of property of your object
String hql = "select c.mobile as mobile, c.password as password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);
List<CrbtSubMasterDemo> itr = query.setResultTransformer(Transformers.aliasToBean(CrbtSubMasterDemo.class) ).list();
##No need to commit the transaction.
}
It will convert you query into the CrbtSubMasterDemo
Do not directly cast the result of "query.list();" to List of CrbtSubMasterDemo. As query.list() return object list. Iterate over the object list received and cast one by one to put in list List of CrbtSubMasterDemo

Is there any spring jpa equivalent to following query

Query :
#Query("Select p.name,t.points from Player p,Tournament t where t.id=?1 And p.id=t.player_id")
I have my player and tournament entity and their corresponding JPA repositories. But the problem is we can get only entities from our query, but i want to do above query, please help me with this i am new to it.
this is my sql query i want to add but where to add i am not getting:
Select p.name, t.points_rewarded from player p, participant t where t.tournament_id="1" and t.player_id=p.id;
This is how you can do it with JPQL for JPA:
String queryString = "select p.name, t.points from Tournament t," +
" Player p where t.player_id=p.id " +
"and t.id= :id_tournament";
Query query = this.entityManager.createQuery(queryString);
query.setParameter("id_tournament", 1);
List results = query.getResultList();
You can take a look at this JPA Query Structure (JPQL / Criteria) for further information about JPQL queries.
And this is ho you can do it using HQL for Hibernate, these are two ways of doing it:
String hql = "SELECT p.name, t.points from Player p,Tournament t WHERE t.id= '1' And p.id=t.player_id";
Query query = session.createQuery(hql);
List results = query.list();
Or using query.setParameter() method like this:
String hql = "SELECT p.name, t.points from Player p,Tournament t WHERE t.id= :tournament_id And p.id=t.player_id";
Query query = session.createQuery(hql);
query.setParameter("tournament_id",1);
List results = query.list();
You can take a look at this HQL Tutorial for further information about HQL queries.
Note:
In both cases you will get a list of Object's array List<Object[]> where element one array[0] is the p.name and the second one is t.points.
TypedQuery instead of normal Query in JPA
this is what i was looking for, thanks chsdk for help, i have to create pojos class, and in above link answer is working fine foe me,
Here is my code sample
String querystring = "SELECT new example.restDTO.ResultDTO(p.name,t.pointsRewarded) FROM Player p, Participant t where t.tournamentId=?1 AND t.playerId = p.id ORDER by t.pointsRewarded DESC";
EntityManager em = this.emf.createEntityManager();
try {
Query queryresults = em.createQuery(querystring).setParameter(1, tournamentId);
List<ResultDTO> result =queryresults.getResultList();
return new ResponseEntity<>(result, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} finally {
if (em != null) {
em.close();
}}

Unable to have correct value with SELECT query using MAX() in JPA

I am new in JPA and I have a problem when I try to query to the database using MAX() function.
Code of my function is following. Can anyone help me? Thank you.
public int getMaxId(){
entityManager = this.entityManagerFactory.createEntityManager();
Query query = entityManager.createQuery("SELECT * FROM user WHERE id = (SELECT MAX(u.id) FROM user u)");
User user = (User) query.getSingleResult();
int id = user.getId();
return id;
}
I am using JPA, TopLink and Apache Derby. My method should return the maximum id of table users.
Edit: I call that function from a service:
try {
int id = userDAO.getMaxId();
logger.info("Max id: " + id);
user.setId(id+1);
}
catch (Exception ex){
logger.error("Unable to get the max id.");
}
Value of user.setId() is always '0'.
Edit(2): Log
Caused by: Exception [EclipseLink-8034] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Error compiling the query [SELECT u FROM user u WHERE u.id = (SELECT MAX(uu.id) FROM user uu)]. Unknown entity type [user].
at org.eclipse.persistence.exceptions.JPQLException.entityTypeNotFound(JPQLException.java:483)
at org.eclipse.persistence.internal.jpa.parsing.ParseTreeContext.classForSchemaName(ParseTreeContext.java:138)
at org.eclipse.persistence.internal.jpa.parsing.SelectNode.getClassOfFirstVariable(SelectNode.java:327)
at org.eclipse.persistence.internal.jpa.parsing.SelectNode.getReferenceClass(SelectNode.java:316)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.getReferenceClass(ParseTree.java:436)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.adjustReferenceClassForQuery(ParseTree.java:75)
at org.eclipse.persistence.internal.jpa.parsing.JPQLParseTree.populateReadQueryInternal(JPQLParseTree.java:103)
at org.eclipse.persistence.internal.jpa.parsing.JPQLParseTree.populateQuery(JPQLParseTree.java:84)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:219)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:190)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:142)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:126)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1475)
... 35 more
My entity User is declared as follows:
#Entity
#Table(name = "user")
public class User {
#Id
private int id;
private String name;
private String lastName;
private String city;
private String password;
You can directly use more simple JPQL
return (Integer)entityManager.createQuery("select max(u.id) from User u").getSingleResult();
Or use TypedQuery
return entityManager.createQuery("select max(u.id) from User u", Integer.class).getSingleResult();
EDIT:
Unknown entity type [user]
You should use User instead of user.
Well it is hard to say from your comments and you haven't posted any logging.
How about this:
Query query = entityManager.createQuery("SELECT u FROM users u WHERE u.id = (SELECT MAX(u.id) FROM users u)");
Im Using that code:
Query qry = em.createQuery("SELECT MAX(t.column) FROM Table t");
Object obj = qry.getSingleResult();
if(obj==null) return 0;
return (Integer)obj;
Cause if there is no elements on Table "t", NullpointerException is throwing.
It's a good solution, but you have to use different names in tho two part of sql. Like this:
"SELECT u FROM users u WHERE u.id = (SELECT MAX(u2.id) FROM users u2)"

Categories