Java Spring 数据 jpa deleteBy 查询不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31346356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring data jpa deleteBy query not working
提问by Alexandru Pirvu
I am trying to create a custom deleteBy method query in my repository. It seems that instead of deleting, hibernate is making a select statement.
我正在尝试在我的存储库中创建自定义 deleteBy 方法查询。似乎 hibernate 没有删除,而是在执行 select 语句。
public interface ContactRepository extends JpaRepository<Contact, Integer> {
Integer deleteByEmailAddress(String emailAddress);
//and this one works
Contact findContactByName(String name);
}
and here is what Hibernate is trying to do:
这就是 Hibernate 正在尝试做的事情:
Hibernate: select contact0_.id as id1_2_, contact0_.emailAddress as >emailAdd2_2_, contact0_.name as name3_2_ from Contact contact0_ where >contact0_.emailAddress=?
休眠:选择 contact0_.id 作为 id1_2_,contact0_.emailAddress 作为 >emailAdd2_2_,contact0_.name 作为 name3_2_ from Contact contact0_ where >contact0_.emailAddress=?
What am I missing? Do I have to make a special configuration in order to make delete work?
我错过了什么?我是否必须进行特殊配置才能使删除工作?
采纳答案by ikumen
Is the delete not working or not working as how you'd expect? Typically an entity has to be managed before it can be deleted, so a JPA provider (hibernate in your case) will load (the query you see) the entity first, then issue the delete.
删除是不起作用还是没有像您期望的那样工作?通常,必须先管理实体,然后才能删除它,因此 JPA 提供程序(在您的情况下处于休眠状态)将首先加载(您看到的查询)实体,然后发出删除。
If you're only seeing the query, but no corresponding delete, then some possibilities are:
如果您只看到查询,但没有相应的删除,那么一些可能性是:
- there's nothing to delete, make sure the record is there in the db
- the delete needs to be part of a transaction. I believe the Spring data CRUD ops are transactional by default, if not just make sure whatever is calling
deleteByEmailAddress
is transactional
- 没有什么可删除的,请确保该记录在数据库中
- 删除需要是事务的一部分。我相信 Spring 数据 CRUD 操作在默认情况下是事务性的,如果不只是确保调用的
deleteByEmailAddress
是事务性的
Note: you can avoid the select when removing an entity using a modifying query delete, example below:
注意:您可以在使用修改查询删除删除实体时避免选择,示例如下:
// NOTE: you have return void
@Modifying
@Transactional
@Query(value="delete from Contact c where c.emailAddress = ?1")
void deleteByEmailAddress(String emailAddress)
回答by Cristian J. Brito
In modern versions of Spring Data JPA (>=1.7.x) query derivation for delete, remove and count operations is accessible.
在 Spring Data JPA (>=1.7.x) 的现代版本中,可以访问用于删除、删除和计数操作的查询派生。
回答by T21
Try to move the delete Query call to an service class exclusive for it:
尝试将 delete Query 调用移动到专属于它的服务类:
@FunctionalInterface
public interface DeleteService {
public int deleteIfExists(Date fechaProceso);
}
and implement it in DeleteServiceImpl.java for example
并在例如 DeleteServiceImpl.java 中实现它