【问题标题】:How to set null value for a column in table through spring boot JPA如何通过spring boot JPA为表中的列设置空值
【发布时间】:2023-02-06 20:45:52
【问题描述】:

如何通过 spring boot JPA 为表中的列设置空值。

我有一些要求需要为表中的所有记录设置 null。

在我的存储库中,我写了

@Modifying
@Transactional
@Query("update table_name set column_name = null")
void setNull();

在我的服务中,我写了

myRepository.rsetNull();

但是为了运行这个,我得到了这样的错误。

原因:org.springframework.data.repository.query.QueryCreationException:无法为公共抽象无效创建查询

【问题讨论】:

  • 尝试从您的存储库方法中删除 @Transactional
  • @kerbermeister 同样的错误。

标签: java sql spring spring-boot jpa


【解决方案1】:

我认为原因是你写了一个本机查询在您的 @Query 注释中,但默认情况下 @Query 注释适用于 JPQL 查询,不适用于本机。

正如来自 @Query 注释的文档所建议的那样:

/** Configures whether the given query is a native one. Defaults to {@literal false}. */ boolean nativeQuery() default false;

所以,从JPQL的角度来看,你与, 不与桌子.

使用 JPQL,您的查询将如下所示:

@Query("update Domain d set d.fieldName = null")

如果你想使用原生查询,那么你应该指定标志nativeQuery = true

因此,您的本机查询需要:

@Query(value = "update table_name set column_name = null", nativeQuery = true)

此外,作为补充,您不应在存储库中的方法上方使用@Transactional,正如this article所建议的那样:

此外,我们可以去掉 @Transactional 注释 方法作为 Spring Data JPA 存储库的 CRUD 方法 实现已经用@Transactional 注释了。

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 2017-11-24
    • 2020-12-14
    • 2020-01-20
    • 2017-10-10
    • 2021-03-06
    • 1970-01-01
    • 2019-07-09
    • 2017-04-01
    相关资源
    最近更新 更多