英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论