JpaRepository nativeQuery - table does not exists - spring

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);

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.

jhipster : unable to select specific columns

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

jdbc result set metadata: getting physical column names on aliased columns

I'm using jdbc to execute query statements (in jruby)
# made-up example
sql = "select " +
"c.type as cartype, " +
"o.id as ownerid, " +
"o.type as ownertype " +
"from cars c " +
"inner join owners o " +
"on c.vin = o.vin"
# 'stmt' gotten with jdbc-connection.create_statement()
result_set = stmt.execute_query(sql)
meta_data = result_set.get_meta_data()
col_count = result_set.get_column_count()
I can query the various column aliases (get_column_name) and tables (get_table_name) for each column through the column indexes, but I also need the actual/physical names of the columns, un-aliased.
How do I get the physical/actual name of column, as it is defined in the schema ("ownerid" column alias is column "id", for instance)?
From tests with other database types, it looks as though this is database+driver specific. Using mysql get_column_name returns the actual/physical column name while get_column_label returns the alias. As an aside, both database types (mysql and sqlite) return the physical table name through get_table_name.

Resources