jhipster : unable to select specific columns - spring

when i select 4 column an error occur :
Caused by: org.postgresql.util.PSQLException: The column name id was not found in this ResultSet.
#Query(value = "select name,rating,numberofviews,status from learningunit", nativeQuery = true)
List<Learningunit> findAllData();
then i add id to the query and the same error occur with different column and so on
#Query(value = "select id,name,rating,numberofviews,status from learningunit", nativeQuery = true)
List<Learningunit> findAllData();
Caused by: org.postgresql.util.PSQLException: The column name summary
was not found in this ResultSet.
notes:i using jhipster and ever entity has a dto and mapper
entity
DTO
Mapper

finally i solved the problem using this query #Query(value = "select null as id , name,rating,numberofviews,null as status from learningunit", nativeQuery = true)
the point is to select null as the name of your column

Related

How to update row in table with condition is refer to another table

How can I update a table which the condition is refer to other table in spring jpa ?
I have table Task which relation to TaskProgress (many to one). And TaskProgress has some value eg: CREATE, INPROGRES, DONE, ARCHIVED,...
Here is my query in repostitory:
#Modifying
#Query("UPDATE Task t SET t.responsibleUser = null WHERE t.responsibleUser.id = :userId " +
"AND t.deleted = false AND t.taskProgress.name <> 'ARCHIVED'")
void removeResponsibleUserId(UUID userId);
But I got the error:
Hibernate: update task cross join set responsible_user_id=null where responsible_user_id=? and deleted=0 and name<>'ARCHIVED'
2020-11-25 00:38:51 - SQL Error: 1064, SQLState: 42000
2020-11-25 00:38:51 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set responsible_user_id=null where responsible_user_id=x'152B59C33A0035003500000' at line 1
Use an exists predicate like this:
#Modifying
#Query("UPDATE Task t SET t.responsibleUser = null WHERE t.responsibleUser.id = :userId " +
"AND t.deleted = false AND NOT EXISTS (SELECT 1 FROM t.taskProgress p WHERE p.name = 'ARCHIVED')")
void removeResponsibleUserId(UUID userId);

The column name id was not found in this ResultSet

#Query(value = "SELECT s FROM logines.work_hour s WHERE TO_TIMESTAMP(s.start_time, 'YYYY-MM-DD HH24:mi')\\:\\:timestamp BETWEEN :start_time\\:\\:timestamp AND now()\\:\\:timestamp", nativeQuery = true)
List<WorkHour> findByStartTime(#Param("start_time") String startTime);
org.postgresql.util.PSQLException: The column name id was not found in this ResultSet.
What might be an issue?
The issue could be due to the usage of only s in #Query. replacing s with all db column names with it i.e., s.coloumn1, s.column2, s.column3 will fix the issue.

Spring MVC, Select Special Columns in Native SELECT Query

this is my native SELECT Query in Repository
#Modifying
#Query(value = "SELECT * FROM tasks WHERE title LIKE '%Java%' ORDER BY id DESC ", nativeQuery = true)
List<Task> listAllTasks();
this works ok, but when I use custom column name instead of *, like this
#Modifying
#Query(value = "SELECT title FROM tasks WHERE title LIKE '%Java%' ORDER BY id DESC ", nativeQuery = true)
List<Task> listAllTasks();
I have this error :
org.postgresql.util.PSQLException: The column name id was not found in this ResultSet.
any Help?
The resultset doesn't have the "id" in it, you have to provide it.
You should change the way you are declaring your SQL:
SELECT t.title, t.id FROM tasks t WHERE t.title LIKE '%Java%' ORDER BY t.id DESC
Check out this sort example:Native Queries
Select * from Entity -> returns a List of Entity
Example:
#Query(select * from tasks)
List<Task> findAllTasks();
Select column from Entity -> returns a List of Types of the entity.
Example:
#Query(select t.title from tasks t)
List<String> findTitle_AllTasks();
title is of the type String
Select multiple columns from Entity -> returns an Object[] holding the data
Example:
#Query(select t.id, t.title from tasks t)
List<Object[]> findIdTitle_AllTasks();
So, you are retrieving String type data - title and asking to return a List of Task type. This is causing the problem. You can actually check the hibernate docs under HQL and JPQL to understand this.
Plus, you are doing a SELECT (DQL operation). #Modifying is rudimentary here as it is used for DML operations using Data JPA - UPDATE/DELETE.

JpaRepository nativeQuery - table does not exists

when trying to perform an update on table using JpaRepository and #Query annotation I receive an error "Table not exists" and:
has thrown exception:org.hibernate.exception.SQLGrammarException: could n
ot execute statement
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute s
tatement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException
: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
Caused by: oracle.jdbc.OracleDatabaseException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:498)
... 154 common frames omitted
My Query:
#Modifying
#Transactional
#Query(nativeQuery = true, value = "UPDATE T_MY_TABLE SET VISIBLE_FLAG = 0 "
+ "WHERE ID = :myId ")
int updateMyTab(#Param("myId") Long myId);
When using JpaRepository.save method to update the table, it executes normally without any problems.
Also, I have SELECT nativeQueries, which works. Only the updates does not.
On table there is:
- created synonym for the schema
- grants for select, insert, update, delete for the schema
Table DOES exists, the update, if executed directly on DB and on any schema/user it works without any problems and updates rows
I managed to solve the issue - problem was in database object naming. I used upper-case in object naming while tables names were case sensitive. I had to change:
#Modifying
#Transactional
#Query(nativeQuery = true, value = "UPDATE T_MY_TABLE SET VISIBLE_FLAG = 0 "
+ "WHERE ID = :myId ")
int updateMyTab(#Param("myId") Long myId);
to:
#Modifying
#Transactional
#Query(nativeQuery = true, value = "UPDATE "\t_my_table"\ SET VISIBLE_FLAG = 0 "
+ "WHERE ID = :myId ")
int updateMyTab(#Param("myId") Long myId);

JPA QueryDSL: count() leads to ORA-01722: invalid number

I have the following Query, which tries to find the count of all RUNNING Trackings:
new JPAQuery(getEntityManager()).from(myTracking)
.where(myTracking.trackingStatus.isNotNull(),
myTracking.trackingStatus.eq(TrackingStatus.RUNNING))
.count()
This leads to ORA-01722: invalid number. Why?
EDIT: Logging of the SQL statement:
/* select
count(myTracking)
from
MyTracking myTracking
where
myTracking.trackingStatus is not null
and myTracking.trackingStatus = ?1 */ select
count(mytrackin0_.ID) as col_0_0_
from
owner.T_my_TRACKING mytrackin0_
where
(
mytrackin0_.STATUS is not null
)
and mytrackin0_.STATUS=?
The solution is I forgot to add the #Enumerated(EnumType.STRING) to my Enum attribute.
MyEntity{
#Enumerated(EnumType.STRING)
private TrackingStatus trackingStatus;
}
This was resulting in the Enum-Position and NOT the Enum-String beeing inserted into the Database-Column.
Once I added the annotation the still running trackings in the database were compared with their Enum-Position to the Enum-String from the query -> ORA-01722: invalid number.
The solution was to delete/migrate the few wrong mapped trackings.

Resources