Spring Data: “delete by” is supported?

后端 未结 9 2276
长情又很酷
长情又很酷 2020-11-28 20:57

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 hopi

9条回答
  •  盖世英雄少女心
    2020-11-28 21:20

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

    • 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.

    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);
    }
    
    

提交回复
热议问题