HQL-query with discriminator column cannot query by type of subclass - hql

I'm using JPA1.0 and Hibernate 3.3. (There is currently no option to upgrade).
I want to query a generic table GenericOrderType with #Inheritance(strategy = InheritanceType.SINGLE_TABLE) strategy and #Discriminatorcolumn(name="ORDER_TYPE").
Running the following query WITHOUT AND type(o) = 'SubOrderType' works.
select OBJECT(o) from GenericOrderType o where o.id = :orderid AND type(o) = 'MiniOrderType'
If I append AND type(o) = 'MiniOrderType' I get a persistence exception.
javax.persistence.PersistenceException: org.hibernate.HibernateException: Unable to resolve entity name from Class [java.lang.String] expected instance/subclass of [com.doe.GenericOrderType]
I did not find the correct syntax to query by type (subclass) with Hibernate 3.3 and JPA 1.
http://docs.jboss.org/hibernate/core/3.3/reference/en-US/html/
Any hints appreciated.
Thank you

Related

Spring data jpa projection could not extract ResultSet

I'm trying to map my entity to projection using the below query but i'm getting error as
Exception : could not extract ResultSet SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
here is the query
#Query("select rf.rfqID as rfqID,rf.creationDate as creationDate," +
"rf.deadLineDate as deadLineDate,rf.details as details," +
"rf.message as message, rf.rfqDoc as rfqDoc," +
"CASE WHEN (rf.creationDate > CURRENT_DATE) THEN 'open' ELSE 'closed' END as status," +
"rf.rfqMembers as rfqMembers " +
"from RFQ rf where rf.createdBy = ?1")
Page<RfqDto> loadAllRfq(String creator, Pageable pageable);
In my Dto I have an extra status column which I don't want to persist in db and would like to get the status via query
here is my projection interface
public interface RfqDto {
String rfqID();
Date creationDate();
Date deadLineDate();
String details();
String message();
String rfqDoc();
String status();
List<RfqMember> rfqMembers();
}
The root cause of your problem is here:
In my Dto I have an extra status column which I don't want to persist in db and would like to get the status via query
As it's explained in the documentation:
The important bit here is that the properties defined here exactly match properties in the aggregate root.
...
The query execution engine creates proxy instances of that interface at runtime for each element returned and forwards calls to the exposed methods to the target object.
So, you can not use spring data jpa projection for your case. You can not use hibernate/jpa projection as well, because it dose not support collections in row results.
You can try to use Blaze-Persistence Entity Views. See for example this answer.

Check on DB with Spring JPA

I am working on a project with Spring boot. I have a problem with Spring JPA Data. I want to check if a record already exists in the db using two parameters
#Transactional
#Modifying
#Query("SELECT CASE WHEN COUNT(dfe) > 0 THEN 'true' ELSE 'false' END FROM DeployedFunctionEntity dfe WHERE dfe.function.idFunction = ?1 and dfe.gatewayId = ?2")
boolean existsByFunctionIdAndGatewayId(#Param("idFunction") Integer functionId,
#Param("gatewayId") Integer gatewayId);
boolean exist = deployedFunctionDao.existsByFunctionIdAndGatewayId(functionId, gatewayId);
I always get the following error:
org.springframework.dao.InvalidDataAccessApiUsageException: Modifying queries can only use void or int/Integer as return type!;
The nested exception is
java.lang.IllegalArgumentException: Modifying queries can only use void or int/Integer as return type!
How can I fix it?
The #Modifying has no use for non-modifying queries, thus, must only be used for INSERT, UPDATE, DELETE or DDL queries. Since you are only making a SELECT query, remove the annotation and it'll work without problems.

Spring Data JPA giving error when joining over multiple tables

I have the following query which joins over multiple tables for getting the necessary output:
public interface UserRepositoryJpaRepository <User, Long> {
#Query("SELECT o.id, u.id, u.name, i.name,i.id FROM User u, Item i LEFT JOIN u.order o LEFT JOIN o.payment p WHERE p.id=:id AND o.id=i.order")
List<MixedResult>getUsersWithOrderByPayment_id(#Param("id") Long id);
However, when running Spring Boot 1.4.1 with Spring Data JPA 1.10.5.BUILD-SNAPSHOT, I am getting the following error message :
org.springframework.dao.InvalidDataAccessApiUsageException: No aliases
found in result tuple! Make sure your query defines aliases!; nested
exception is java.lang.IllegalStateException: No aliases found in
result tuple! Make sure your query defines aliases!
However, I see that the generated SQL is fine and it works

what is the right jpa query to get some column from table instead of all table data

I am getting this given exception
Exception in thread "Thread-2" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.freeGo.model.Pump at com.freeGo.util.HealthTask.run(HealthTask.java:33) at java.lang.Thread.run(Thread.java:745)
My code is :
#Query("SELECT p.id, p.timestamp FROM Pump p WHERE p.isActive = :isActive")
public List<Pump> findByIsActive(#Param("isActive") int isActive);
if i don't use Query annotation as
public List<Pump> findByIsActive(#Param("isActive") int isActive);
then it's run successfully, but it return's all table data but i want only 2 column.
My project in spring-3 and jpa.
There is nothing wrong with the query, if that's what you want. You will be getting a object[] (object array) from the query instead of a List<Pump>. So, make the return type List<Object[]> and get id in column 0 and time in column 1.
If you want to make it a little better code, you should probably get the query to return a custom DTO.
#Query("SELECT new MyDto(p.id, p.timestamp) FROM Pump p WHERE p.isActive = :isActive")
and return a List<MyDto>
Reference: Spring JPA selecting specific columns

orderBy and OneToMany-Relation -- criteria query with jpa 2.0

I have the following structure...
Entity A
- ...
- Collection<B> c (#OneToMany)
Entity B
- ...
- Date d
I want the queryResult to be ordered by the Date d via an orderBy-Statement in my criteriaQuery. How can I achieve this?
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<A> cq = cb.createQuery(A.class);
Root<A> r = cq.from(A.class);
cq.select(r);
// orderBy-Statement -> cq.orderBy(cb.desc(r.get("c.d")).as(Date.class)));
// Error: javax.servlet.ServletException: javax.ejb.EJBException: java.lang.IllegalArgumentException: Unable to resolve attribute [c.d] against path
List<A> l = em.createQuery(cq).getResultList();
Is it possible to have the ordering in the query?
If not, i'm supposed to write a method for ordering my resultList afterwards, right?
Well, all in all I wasn't able to figure out how to use the orderBy-Statement I want. But Now I'm satisfied with an alternative approach (and in my opinion an even better one!):
Fetching the needed data from the database (unordered)
creating a datamodel and using it in the GUI
doing the sorting/ordering on the datamodel/GUI
By the way: I'm using the Primefaces.org-framework. Saves me a lot of work^^
What about this one?
cq.orderBy(cb.desc(r.get("c").get("d")));

Resources