In Eclipselink, when I use #SqlResultSetMappings and I use Query Hint eclipselink.cursor, the console shows me the following exception:
Caused By: java.lang.IllegalArgumentException: Query null, query hint eclipselink.cursor is not valid for this type of query.
at org.eclipse.persistence.internal.jpa.QueryHintsHandler$CursorHint.applyToDatabaseQuery(QueryHintsHandler.java:1640)
at org.eclipse.persistence.internal.jpa.QueryHintsHandler$Hint.apply(QueryHintsHandler.java:367)
at org.eclipse.persistence.internal.jpa.QueryHintsHandler$Hint.apply(QueryHintsHandler.java:345)
at org.eclipse.persistence.internal.jpa.QueryHintsHandler.apply(QueryHintsHandler.java:172)
at org.eclipse.persistence.internal.jpa.QueryImpl.setHintInternal(QueryImpl.java:763)
Truncated. see log file for complete stacktrace
The code is:
#SqlResultSetMapping(
name = "resultSetMapping",
entities = #EntityResult(entityClass = Entity.class))
Query q = em.createNativeQuery(sql, "resultSetMapping";
q.setHint(QueryHints.CURSOR, HintValues.TRUE);
q.getSingleResult();
Why cannot I use SqlResultSetMappings with eclipselink.cursor?
Related
I am using JPA to query an OracleSQL database.
However, I am getting the error:
Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: CLIENT_ID of: com.fdmgroup.pojo.File [SELECT c FROM com.fdmgroup.pojo.File c WHERE c.CLIENT_ID = :clientId]
When I write the following query
String sqlQuery = "SELECT c FROM XD_FILES c WHERE c.CLIENT_ID = :clientId";
TypedQuery<File> query = em.createQuery(sqlQuery, File.class);
query = query.setParameter("clientId", clientId);
ArrayList<File> clientFiles = (ArrayList<File>) query.getResultList();
File has this column
#ManyToOne(targetEntity = Client.class)
#JoinColumn(name = "CLIENT_ID")
private Client client;
I am unsure why as it appears to have the field "client" linked to "CLIEND_ID".
You will need to mention the property name in the query and not the column name.
So the query should look like the following:
String sqlQuery = "SELECT c FROM XD_FILES c WHERE c.clientId = :clientId";
Your query seems native query and not a JPQL, you can solve this in two ways.
1) change em.createQuery(sqlQuery, File.class); to em.createNativeQuery(sqlQuery, File.class);
2) Change your query from native query to JPQL, your query should be like
select c from File c where c.client.clientID=:clientId
(Assuming clientID is primary key column name in Client class)
I tried to run native sql query with resulttransformer (AliasToBeanResultTransformer), it gives error like below.
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.ozpas.ozentegre.entity.EntDevirlog cannot be cast to java.util.Map
at org.hibernate.property.access.internal.PropertyAccessMapImpl$SetterImpl.set(PropertyAccessMapImpl.java:102)
at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:78)
By the way, my native sql query does not include all fields in the entity ( EntDevirlog ), there are only some fields in that entity. shall the query include all fields in the entity ?
as i understood, hibernate transforms result into a map object instead EntDevirlog entity. It uses PropertyAccessMapImpl. how can i solve this problem to get the result as a list ( arraylist ) ? thanks.
Session session = HibernateUtilMikro.getSessionFactory().openSession();
List<EntDevirlog> results = new ArrayList<EntDevirlog>();
Transaction tx = null;
String sql = "mynativequery";
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("tarih", tarih);
query.setParameter("srmkodu", srmkodu);
query.setParameter("s1", EnumPanoislemtipleri.islem1.getValue());
query.setParameter("s2", EnumPanoislemtipleri.islem2.getValue());
query.setResultTransformer(new AliasToBeanResultTransformer(EntDevirlog.class));
results = query.list();
tx.commit();
Just use the quotes for the aliases
"select firstName as \"firstName\",
lastName as \"lastName\" from Employee"
Read for a more deeply explanation here:
mapping Hibernate query results to custom class?
Following is my code snippet:
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath*:META-INF/spring/applicationContext*.xml");
JpaTransactionManager jpatm = (JpaTransactionManager) ctx
.getBean("transactionManager");
EntityManager em = jpatm.getEntityManagerFactory()
.createEntityManager();
String sqlQuery = "SELECT suc FROM SubUsrCont suc, UDMap uDMap WHERE suc.userid = uDMap.userid AND uDMap.parentuserid = :parentuserid";
TypedQuery<SubUsrCont> query = (TypedQuery<SubUsrCont>) em.createQuery(sqlQuery, SubUsrCont.class);
query.setParameter("parentuserid", parentid);
ArrayList<SubUsrCont> listContent = (ArrayList<SubUsrCont>) query.getResultList();
But when ever executed I get the following error:
[http-8080-1] ERROR org.hibernate.hql.PARSER - line 1:92: expecting OPEN, found '.'
Can anybody help???
Well, I found it and successfully tested it as well. It was due to my POJO package name. Previously it was in.myproject.myname. I changed it to com.myproject.myname. HQL was taking in as the SQL Keyword IN and was looking for OPEN '('.
Why are you using a Native SQL query inside em.createQuery()? This will not work because HQL can not have SELECT and furthermore you don't set the value for parameter :parentuserid.
String sqlQuery = "FROM SubUsrCont suc, UDMap uDMap WHERE suc.userid = uDMap.userid AND uDMap.parentuserid = :parentuserid";
TypedQuery<SubUsrCont> query = (TypedQuery<SubUsrCont>) em.createQuery(sqlQuery, SubUsrCont.class);
query.setParameter("parentuserid", <PARENT USER ID TO BE SEARCHED>);
Try this and see
If you would like to execute SQL use createNativeQuery. Also try "SELECT suc.* ...
Also you don't set the parameter :parentuserid
Use query setParameter("parentuserid",someValue)
I can't resolve error with dynamic parameter list "where in". Another query working
#NamedQuery(name = "News.delete", query = "DELETE n FROM News n WHERE n.newsId in (:ids)")
but
Caused by: java.lang.NoSuchMethodError: org.hibernate.hql.antlr.HqlBaseParser.recover(Lantlr/RecognitionException;Lantlr/collections/impl/BitSet;)V
at org.hibernate.hql.antlr.HqlBaseParser.optionalFromTokenFromClause(HqlBaseParser.java:400)
at org.hibernate.hql.antlr.HqlBaseParser.deleteStatement(HqlBaseParser.java:259)
at org.hibernate.hql.antlr.HqlBaseParser.statement(HqlBaseParser.java:148)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:248)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:157)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:77)
at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:56)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
at org.hibernate.impl.SessionFactoryImpl.checkNamedQueries(SessionFactoryImpl.java:402)
at org.hibernate.impl.SessionFactoryImpl.(SessionFactoryImpl.java:352)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1294)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:132)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:221)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:251)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1390)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1359)
UPD
new error
public void removeNews(List<Integer> listOfIdNewsForDeleting) throws DAOException {
EntityManager entityManager = getJpaTemplate().getEntityManagerFactory().createEntityManager();
Query query = entityManager.createNamedQuery("News.delete");
query.setParameter("ids", listOfIdNewsForDeleting);
int deleted = query.executeUpdate();}
javax.persistence.TransactionRequiredException: Executing an update/delete query
I can't get transaction. So i can't use JpaTemplate pass list of id of news for deleting. Maybe JpaCallback
You are having incompatible versions of hibernate and antlr. Upgrade your antlr.jar
Use DELETE FROM News n WHERE n.newsId in (:ids)
See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#batch-direct for the reference.
My entity has a named query which looks like this:
#NamedQuery(name = "Person.find", query = "select p from Organization p where p.name=:NAME")
In my code I want to set the query cache hint:
query.setHint("eclipselink.cache-usage", "CheckCacheThenDatabase");
If I try to get whole result list:
List<Person> result = query.getResultList();
EclipseLink throws an exception:
Exception [EclipseLink-6124] (Eclipse Persistence Services - 1.0.1 (Build 20080905)): org.eclipse.persistence.exceptions.QueryException
Exception Description: Required query of class org.eclipse.persistence.queries.ReadAllQuery, found class org.eclipse.persistence.queries.ReadObjectQuery
If I try to get only a single result, it works:
Person person = query.getSingleResult();
If I remove the query hint, then getResultList() works also.
I don't understand the exception - isn't it saying that it is specifically expecting getResultList()?? What am I doing wrong?
EclipseLink documentation says:
"EclipseLink does not support the cache usage for native queries or queries that have complex result sets such as returning data or multiple objects."
Also the documentation says:
"CheckCacheThenDatabase – You can configure any read-object query to check the cache completely before you resort to accessing the database."
So the behaviour seems to be ok, I just found the exception misleading.
EDIT: Try something like this in the entity definition, that should be enough: (Coded on the web page so there can be errors)
Entity
#Cache(expiry = 3600000, // 1 hour size = 10000)
#NamedQueries({
#NamedQuery(name = "Person.findByPK", query = "select p from Person p " +
"where p.name=:NAME",
hints = {
#QueryHint(name = QueryHints.CACHE_USAGE,
value = CacheUsage.CheckCacheThenDatabase),
#QueryHint(name = QueryHints.QUERY_TYPE, value = QueryType.ReadObject)
}
})