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

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

Related

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

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

Syntax Error in query expression with vb 6.0

sql = "update Attendance set Attended=Attended+1 where Student ID like 15001"
db.Execute (sql)
is is showing :
"syntax error(missing operator) in query expression 'Student ID like
15001'
If realy you have a space between Student and ID tehn your query must be :
sql = "update Attendance set Attended=Attended+1 where [Student ID] like 15001"
db.Execute (sql)
sql should always be written with an _. For Example Student ID should always be Student_ID so that it has the idea of reading which column it needs to filter its search. For future purposes always create a column name with an _.
sql = "update Attendance set Attended=Attended+1 where Student_ID like 15001"
db.Execute (sql)
or
sql = "update Attendance set Attended=Attended+1 where [Student ID] like 15001"
db.Execute (sql)
Try something that looks a bit cleaner...
sql = "Update tblAttendance SET "
sql = sql & " Attended = Attended + 1 "
sql = sql & " Where Student_ID = 15001 "
db.execute SQL <-- no paranthesis

Oracle - Update with join

Using Oracle 11g. I need to do an update with a self join. Oracle doesn't support updates with joins and using MERGE isn't working as I'm trying to do an update on columns used in the on clause
What I've tried:
update
(
select a.ID, a.FROM_STAGE_ID, a.TO_STAGE_ID, b.TO_STAGE_ID
from STATES a,
STATES b
where a.ID = b.ID and
a.TO_STAGE_ID = b.FROM_STAGE_ID and
a.TO_STAGE_ID = 'FIZZBUZZ' and
a.FROM_STAGE_ID <> b.TO_STAGE_ID and
a.CODE = b.CODE
)
set a.TO_STAGE_ID=b.TO_STAGE_ID;
This resulted in : "SQL Error: ORA-00904: "B"."TO_STAGE_ID": invalid identifier"
MERGE
INTO STATES a
USING STATES b
ON (
a.ID = b.ID and
a.TO_STAGE_ID = b.FROM_STAGE_ID and
a.TO_STAGE_ID = 'FIZZBUZZ' and
a.FROM_STAGE_ID <> b.TO_STAGE_ID and
a.CODE = b.CODE
)
WHEN MATCHED THEN
UPDATE
set a.TO_STAGE_ID = b.TO_STAGE_ID;
This resulted in: "SQL Error: ORA-38104: Columns referenced in the ON Clause cannot be updated: "A"."TO_STAGE_ID"
38104. 00000 - "Columns referenced in the ON Clause cannot be updated: %s"
*Cause: LHS of UPDATE SET contains the columns referenced in the ON Clause
I can try deleting the rows that require updating and populating them from a staging/temp table, but am interested to see if there is another way.
The error in the first case is because you are trying to reference the columns using table aliases that are only valid within the scope of the subquery. You should be able to get around that by aliasing the columns:
update
(
select a.ID, a.FROM_STAGE_ID, a.TO_STAGE_ID a_to_stage_id, b.TO_STAGE_ID b_to_stage_id
from STATES a,
STATES b
where a.ID = b.ID and
a.TO_STAGE_ID = b.FROM_STAGE_ID and
a.TO_STAGE_ID = 'FIZZBUZZ' and
a.FROM_STAGE_ID <> b.TO_STAGE_ID and
a.CODE = b.CODE
)
set a_to_stage_id = b_to_stage_id
This still may not work - it depends on whether the join preserves the key of the original table.

Resources