The question may seems stupid but I am stuck on executing that kind of query:
UPDATE user SET productArr = ARRAY[ARRAY[2,2],ARRAY[3,2],ARRAY[1,3]] WHERE id = 1;
within a @Query
Spring Data.
I defined my repository method like:
@Modifying
@Query(value = """
UPDATE user
SET productArr = :productArr WHERE id = :userId
""", nativeQuery = true)
void updateProductArr (@Param("productArr") String productArr, @Param("userId") Long userId);
I set String productArr="ARRAY[ARRAY[2,2],ARRAY[3,2],ARRAY[1,3]]"
The error is:
org.postgresql.util.PSQLException: ERROR: column "productArr" is of type text[] but expression is of type text
I tried to change the type of productArr
from String to String[]
or List<String>
without success.
I also tried this solution: UPDATE user SET productArr = REPLACE(:productArr,'"','') WHERE id = :userId
but same result.
Please note that when I run that query on a database console it works well.
Thank you in advance for your help.
2
Answers
When you update your data using this query:
Postgres automatically converts you integer array to string array, because as I understand the
productArr
field is type oftext[]
You can filter this field using this correct SQL queries:
or
In your spring project you have two ways do this.
For example:
And use:
Your problem is brought on by a type mismatch between the PostgreSQL array type and the
productArr
argument of your Spring Data query. To fix this, modify the type of theproductArr
parameter in your method signature toString[]
and explicitly define the parameter type using the::text[]
cast in your query. This guarantees for the update query to run effectively.