为什么第一个查询有效而第二个无效?(Spring 应用程序 JPA)

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

Why is the first Query working and the second not? (Spring application JPA)

问题

我有两个查询,我想在一个Spring项目中使用它们(使用JPA)。第一个查询可以获取一个账户,这个功能正常。对于第二个查询,我希望能够更新数据库中的 'disabled' 字段。代码如下:

// 这是第一个查询(正常工作)
@Query(value = "SELECT * FROM accounts WHERE email = ?1", nativeQuery = true)
Account findByEmailAddress(String emailAddress);

// 这是第二个查询(不工作)
@Modifying
@Query(value = "UPDATE accounts SET disabled = 1 WHERE email= ?1 ", nativeQuery = true)
int disableAccountByEmail(String emailAddress);

我在某个地方读到需要添加 @Modifying,这将返回一个 int 或 void。但是当我尝试测试它是否工作时,我得到一个 TransactionRequiredException 错误,错误信息是:执行了一个更新/删除 查询。

英文:

I have two Query's that I want to use in a Spring project (using JPA). The first one gets an account and this works correctly. For the second one I want it to be able to update the 'disabled' field in the database. The codes look like this:

// This is the first Query (works correctly)
@Query(value = "SELECT * FROM accounts WHERE email = ?1", nativeQuery = true)
Account findByEmailAddress(String emailAddress);

// This is the second Query (doesn't work)
@Modifying
@Query(value = "UPDATE accounts SET disabled = 1 WHERE email= ?1 ", nativeQuery = true)
int disableAccountByEmail(String emailAddress);

I did read somewhere I needed to add @Modifying and this will return an int or void. But when I try to test if it works I get a TransactionRequiredException error that says: Executing an update/delete query

答案1

得分: 2

尝试使用以下内容进行更新查询:

@Transactional
@Modifying(clearAutomatically = true)
英文:

Try using the below for update query

 @Transactional
 @Modifying(clearAutomatically = true)

huangapple
  • 本文由 发表于 2020年9月3日 00:42:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63709986.html
匿名

发表评论

匿名网友

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

确定