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.
Related
JPA repository throwing Error for custom query method:
org.h2.jdbc.JdbcSQLException: Table "NBMRBANKDTLSENTITY" not found; SQL statement:
select NBMRBankDtlsEntity from NBMRBankDtlsEntity where NBMRBankDtlsEntity.ipphId = ? [42102-191]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
Class :
#Repository
public interface NBMRBankDtlsRepository extends JpaRepository<NBMRBankDtlsEntity, Long> {
#Query(value ="select n from NBMRBankDtlsEntity n where n.ipphId = :ipphId",nativeQuery = true)
Optional<NBMRBankDtlsEntity> findByIPPHId(#Param("ipphId") Long ipphId);
}
The error message tells you: Table "NBMRBANKDTLSENTITY" not found. Therefore it probably doesn't exist. To fix this you'll have to create the table, manually through a script or through hibernates schema creation feature.
I am already creating a table also inserting the record, After that only i am calling this custom query method.
I have found the issue as i am using nativeQuery = true so it is expecting normal sql query to query DB directly not the java query which is creating issue. Now after changing below it works fine ,
#Query(value = "SELECT * from NB_MR_BANK_DTLS WHERE IPPH_ID = :ipphId",nativeQuery = true)
For java query we can use directly as it internally converts to SQL while querying the DB,
#Query(value = "select p from NBMRBankDtlsEntity p WHERE p.ipphId = :ipphId")
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?
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?
I try to use a native query in my Dao (extended from JpaRepository), but i get this exception :
org.springframework.orm.jpa.JpaSystemException: Could not extract result set metadata; nested exception is org.hibernate.HibernateException: Could not extract result set metadata
Here is my native query:
#Repository
public interface BenchDao extends JpaRepository<Bench, Long> {
#Query(nativeQuery=true,value="UPDATE TF_BENCH SET ISDELETED = 1, SEQ = (select CASE WHEN (min(BENCH.SEQ) < 1) THEN (min(BENCH.SEQ)-1) ELSE -1 END from TF_BENCH BENCH WHERE BENCH.STAGE = (select BENCH.STAGE from TF_BENCH BENCH WHERE id =29302)) WHERE id =29302")
void deleteBench();
When i try this request on Oracle SQL developper it works, but through spring and hibernate it doesn't.
In the stack trace exeception I have also this message :
Caused by: java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
I've tried to google exception messages, but I found nothing...
I think that a better solution was to add the #Modifying annotation to your method.
See more on the following Answer : Spring Data JPA delete native query throwing exception
I've found a solution : if someone need :
#Repository
public class BenchDaoCustomImpl implements BenchDaoCustom {
#PersistenceContext
private EntityManager em;
public void deleteBench(Long benchId) {
this.em.createNativeQuery("UPDATE TF_BENCH SET ISDELETED = 1, SEQ = (select CASE WHEN (min(BENCH.SEQ) < 1) THEN (min(BENCH.SEQ)-1) ELSE -1 END from TF_BENCH BENCH WHERE BENCH.STAGE = (select BENCH.STAGE from TF_BENCH BENCH WHERE id =?0)) WHERE id =?0")
.setParameter(0, benchId)
.executeUpdate();
}
}
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)
}
})