【问题标题】:Delete record into table and get the number of deleted rows将记录删除到表中并获取删除的行数
【发布时间】:2019-10-30 04:42:52
【问题描述】:

我想创建一个删除超过 1 小时的记录的 SQL 查询:

@Override
    public List<Cvvs> deleteOldRecordsByDate(LocalDateTime created_at) throws Exception {

        String hql = "delete from " + Records.class.getName() + " e where e.created_at <= :created_at";
        TypedQuery<Records> query = entityManager.createQuery(hql, Records.class).setParameter("created_at", created_at);
        List<Records> records = query.getResultList();
        return records;
    }

但是我怎样才能得到删除记录的数量呢?

【问题讨论】:

    标签: java spring-boot jpa spring-data-jpa spring-data


    【解决方案1】:

    您在批量更新/删除时使用executeUpdate,它的返回值是受影响的行数:

    int records = query.executeUpdate();
    

    【讨论】:

    • 我认为它不会为超过一行提供已删除的 id。
    • @Mak 但 OP 并没有询问已删除记录的 ID,而是询问已删除记录的数量。
    【解决方案2】:

    由于您使用的是 Spring Data JPA,我认为最好使用存储库查询方法,该方法将返回已删除记录的数量,例如:

    public interface RecordRepo extends JpaRepository<Record, Integer> {
    
        @Modifying
        @Query("delete from Record r where r.createdAt <= ?1") 
        int deleteByCreatedAt(LocalDateTime createdAt);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多