【问题标题】:Spring Data JPA with Postgres issue with modifying a column dynamicallySpring Data JPA with Postgres 动态修改列问题
【发布时间】:2021-06-28 14:49:41
【问题描述】:

这是我的 @Query 修饰方法,用于使用新值更新列。列名不固定,作为参数传递。

@Modifying
@Transactional
@Query(value="UPDATE user SET :column=:newValue WHERE id=:id",nativeQuery = true)
fun partialUpdate(@Param("id") id: String,@Param("column") column: String, @Param("newValue")newValue: String): Int

这是堆栈跟踪

2021-04-01T15:18:03,396Z [http-nio-8080-exec-1] WARN  o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 42601
2021-04-01T15:18:03,396Z [http-nio-8080-exec-1] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - ERROR: syntax error at or near "$1"
  Position: 19
2021-04-01T15:18:03,442Z [http-nio-8080-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
  Position: 19
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2285)

这可能是什么原因造成的?

【问题讨论】:

    标签: postgresql hibernate kotlin jpa spring-data-jpa


    【解决方案1】:

    JPA 不支持将列名作为参数传递。改用 CriteraAPI

    @Transactional
        fun partialUpdate(id: String, column: String, newValue: String):Int {
            val cb: CriteriaBuilder = em.getCriteriaBuilder()
            val update = cb.createCriteriaUpdate(User::class.java)
            val user = update.from(User::class.java)
            update.set(user.get(column), newValue).where(cb.equal(user.get<String>("id"), id))
            return em.createQuery(update).executeUpdate()
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-21
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 2021-02-06
      • 2017-08-21
      相关资源
      最近更新 更多