如何通过Spring Boot JPA在表的列中设置空值。

huangapple go评论67阅读模式
英文:

How to set null value for a column in table through spring boot JPA

问题

我需要通过Spring Boot JPA在表的列中设置空值。我有一些要求,需要将表中所有记录设置为 null。

在我的存储库中,我已经编写了以下代码:

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

在我的服务中,我编写了:

myRepository.setNull();

但是在运行时,我遇到了如下错误:

Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract void

英文:

How to set null value for a column in table through spring boot JPA.

I have some requirement where I need to set null to all the records in table.

IN My repository I have written

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

In My service I have written

myRepository.rsetNull();

But for running this I am getting error like this.

Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract void

答案1

得分: 1

I think the reason is that you wrote a native query in your @Query annotation, but @Query annotation by default works with JPQL queries, not with native.

As docs from @Query annotation suggests:

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

So, from the perspective of JPQL, you work with domains, not with tables.

With JPQL, your query would look like:

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

If you want to use a native query, then you should specify the flag nativeQuery = true.

So, your native query would look like:

@Modifying
@Transactional
@Query(value = "update table_name set column_name = null", nativeQuery = true)
英文:

I think the reason is that you wrote a native query in your @Query annotation, but @Query annotation by default works with JPQL queries, not with native.

As docs from @Query annotation suggests:

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

So, from perspective of JPQL you work with domains, not with tables.

With JPQL your query would look like:

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

If you want to use native query, then you should specify the flag nativeQuery = true

So, your native query would like:

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

huangapple
  • 本文由 发表于 2023年2月6日 20:06:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361104.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定