Spring Data:支持“删除”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23723025/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:44:35  来源:igfitidea点击:

Spring Data: "delete by" is supported?

springspring-dataspring-data-jpa

提问by curious1

I am using Spring JPA for database access. I am able to find examples such as findByName and countByName, for which I dont have to write any method implementation. I am hoping to find examples for delete a group of records based on some condition.

我正在使用 Spring JPA 进行数据库访问。我能够找到诸如 findByName 和 countByName 之类的示例,我不必为它们编写任何方法实现。我希望找到根据某些条件删除一组记录的示例。

Does Spring JPA support deleteByName-like delete? Any pointer is appreciated.

Spring JPA 是否支持类似 deleteByName 的删除?任何指针表示赞赏。

Regards and thanks.

问候和感谢。

回答by Andrey Atapin

Deprecated answer (Spring Data JPA <=1.6.x):

已弃用的答案(Spring Data JPA <=1.6.x)

@Modifyingannotation to the rescue. You will need to provide your custom SQL behaviour though.

@Modifying解救的注解。不过,您需要提供自定义 SQL 行为。

public interface UserRepository extends JpaRepository<User, Long> {
    @Modifying
    @Query("delete from User u where u.firstName = ?1")
    void deleteUsersByFirstName(String firstName);
}

Update:

更新:

In modern versions of Spring Data JPA (>=1.7.x) query derivation for delete, removeand countoperations is accessible.

在 Spring Data JPA (>=1.7.x) 的现代版本中delete,可以访问,removecount操作的查询派生。

public interface UserRepository extends CrudRepository<User, Long> {

    Long countByFirstName(String firstName);

    Long deleteByFirstName(String firstName);

    List<User> removeByFirstName(String firstName);

}

回答by Christoph Strobl

Derivation of delete queries using given method name is supported starting with version 1.6.0.RC1of Spring Data JPA. The keywords removeand deleteare supported. As return value one can choose between the number or a list of removed entities.

从Spring Data JPA 的1.6.0.RC1版本开始,支持使用给定方法名称派生删除查询。支持关键字removedelete。作为返回值,可以在数字或已删除实体列表之间进行选择。

Long removeByLastname(String lastname);

List<User> deleteByLastname(String lastname);

回答by geoand

If you take a look at the source code of Spring Data JPA, and particularly the PartTreeJpaQueryclass, you will see that is tries to instantiate PartTree. Inside that class the following regular expression

如果您查看 Spring Data JPA 的源代码,尤其是PartTreeJpaQuery该类,您会看到它尝试实例化PartTree. 在该类中,以下正则表达式

private static final Pattern PREFIX_TEMPLATE = Pattern.compile("^(find|read|get|count|query)(\\p{Lu}.*?)??By")

private static final Pattern PREFIX_TEMPLATE = Pattern.compile("^(find|read|get|count|query)(\\p{Lu}.*?)??By")

should indicate what is allowed and what's not.

应该指出什么是允许的,什么是不允许的。

Of course if you try to add such a method you will actually see that is does not work and you get the full stacktrace.

当然,如果您尝试添加这样的方法,您实际上会发现它不起作用,并且您会获得完整的堆栈跟踪。

I should note that I was using looking at version 1.5.0.RELEASEof Spring Data JPA

我应该注意到我正在使用1.5.0.RELEASESpring Data JPA 的版本

回答by P Satish Patro

2 ways:-

2种方式:-

1st one Custom Query

第一个自定义查询

@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);

2nd one JPA Query by method

第二个 JPA 查询方法

List<User> deleteByLastname(String lastname);

When you go with query by method (2nd way) it will first do a get call

当您使用按方法查询(第二种方式)时,它将首先进行 get 调用

select * from user where last_name = :firstName

Then it will load it in a List Then it will call delete id one by one

然后它会在一个List中加载它然后它会一一调用delete id

delete from user where id = 18
delete from user where id = 19

First fetch list of object, then for loop to delete id one by one

先获取对象列表,然后for循环将id一一删除

But, the 1st option (custom query),

但是,第一个选项(自定义查询),

It's just a single query It will delete wherever the value exists.

这只是一个查询,它会在值存在的地方删除。

Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby

也通过此链接https://www.baeldung.com/spring-data-jpa-deleteby

回答by Suneet Khurana

If you will use pre defined delete methods as directly provided by spring JPA then below two queries will be execute by the framework.

如果您将使用 spring JPA 直接提供的预定义删除方法,那么框架将执行以下两个查询。

  • First collect data(like id and other column) using by execute select query with delete query where clause.

  • then after getting resultSet of first query, second delete queries will be execute for all id(one by one)

    Note : This is not optimized way for your application because many queries will be execute for single MYSQL delete query.

  • 首先使用 by execute select query with delete query where 子句收集数据(如 id 和其他列)。

  • 然后在获得第一个查询的结果集后,将对所有 id 执行第二个删除查询(一个一个)

    注意:这不是针对您的应用程序的优化方式,因为将针对单个 MYSQL 删除查询执行许多查询。

This is another optimized way for delete query code because only one delete query will execute by using below customized methods.

这是删除查询代码的另一种优化方式,因为使用以下自定义方法只会执行一个删除查询。



@NamedNativeQueries({

@NamedNativeQuery(name = "Abc.deleteByCreatedTimeBetween",
            query = "DELETE FROM abc WHERE create_time BETWEEN ?1 AND ?2")
    ,

    @NamedNativeQuery(name = "Abc.getByMaxId",
            query = "SELECT max(id) from abc")
})

@Entity
public class Abc implements Serializable {

}

@Repository
public interface AbcRepository extends CrudRepository {

    int getByMaxId();

    @Transactional
    @Modifying
    void deleteByCreatedTimeBetween(String startDate, String endDate);
}

回答by Andrey Ofim

Be carefull when you use derived query for batch delete. It isn't what you expect: DeleteExecution

使用派生查询进行批量删除时要小心。这不是您所期望的:DeleteExecution

回答by amoljdv06

Yes , deleteBy method is supported To use it you need to annotate method with @Transactional

是的,支持 deleteBy 方法要使用它,您需要使用 @Transactional 注释方法