问题描述
我尝试像这样在 spring-data-jdbc 存储库中声明和使用 deleteBy 方法
public interface TokenRepository extends CrudRepository<OpToken,Long> {
void deleteByBreed(Long breed);
}
private TokenRepository tokenRepository;
...
...
tokenRepository.deleteByBreed(123L);
我得到异常:MethodNotFoundException:
java.lang.NoSuchMethodException: void.()
我决定,删除方法应该返回它处理的行数。所以,我像这样重写我的存储库界面
public interface TokenRepository extends CrudRepository<OpToken,Long> {
long deleteByBreed(Long breed);
}
但现在我有另一个例外: org.springframework.jdbc.IncorrectResultSetColumnCountException:列数不正确:预期为 1,实际为 4
它看起来像方法返回实体或它尝试删除的实体列表。但我不需要它们。 在我的情况下,如何声明此方法?
按实体看起来像这样:
@Data
public class OpToken implements Persistable<Long> {
@Transient
private boolean newEntity;
@Id
@Column("jti")
private Long jti;
@Column("breed")
private Long breed;
@Column("id_account")
private Long idAccount;
@Column("exp")
private Date exp;
@Override
public Long getId() {
return jti;
}
@Override
public boolean isNew() {
return newEntity;
}
}
解决方法
只有一个成功
@Modifying
@Query("delete from account.op_token t where t.breed = :breed")
Long(or void) deleteByBreed(@Param("breed") Long breed);
,
当前版本尚不支持派生删除查询。观看 https://github.com/spring-projects/spring-data-jdbc/issues/771 以在此更改时收到通知。
@MadMax 提供的解决方案是正确的:使用了专用查询:
@Modifying
@Query("delete from account.op_token t where t.breed = :breed")
void deleteByBreed(@Param("breed") Long breed);
,
但查询仅在您的实体没有值对象(不是@Embedded)时才有效。我有一个带有值对象的 Customer 实体,所以我在我的服务中使用了这个方法(customerId 是唯一的):
@Transactional
public void deleteByCustomerId(final String customerId) {
customerRepository.findByCustomerId(customerId).ifPresent(customerRepository:delete);
}