删除无法使用JpaRepository的内容 [英] Delete Not Working with JpaRepository

查看:333
本文介绍了删除无法使用JpaRepository的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring 4应用程序,我试图从数据库中删除实体的实例.我有以下实体:

I have a spring 4 app where I'm trying to delete an instance of an entity from my database. I have the following entity:

@Entity
public class Token implements Serializable {

    @Id
    @SequenceGenerator(name = "seqToken", sequenceName = "SEQ_TOKEN", initialValue = 500, allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqToken")
    @Column(name = "TOKEN_ID", nullable = false, precision = 19, scale = 0)
    private Long id;

    @NotNull
    @Column(name = "VALUE", unique = true)
    private String value;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "USER_ACCOUNT_ID", nullable = false)
    private UserAccount userAccount;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "EXPIRES", length = 11)
    private Date expires;

    ...
    // getters and setters omitted to keep it simple
}

我定义了一个JpaRepository接口:

I have a JpaRepository interface defined:

public interface TokenRepository extends JpaRepository<Token, Long> {

    Token findByValue(@Param("value") String value);

}

我有一个与内存数据库(H2)一起使用的单元测试设置,我正在用两个令牌预填充数据库:

I have a unit test setup that works with an in memory database (H2) and I am pre-filling the database with two tokens:

@Test
public void testDeleteToken() {
    assertThat(tokenRepository.findAll().size(), is(2));
    Token deleted = tokenRepository.findOne(1L);
    tokenRepository.delete(deleted);
    tokenRepository.flush();
    assertThat(tokenRepository.findAll().size(), is(1));
}

第一个断言通过,第二个断言失败.我尝试了另一种更改令牌值并将其保存到数据库的测试,它确实可以正常工作,所以我不确定为什么删除不起作用.它也不会引发任何异常,只是不会将其持久化到数据库中.它也不适用于我的oracle数据库.

The first assertion passes, the second fails. I tried another test that changes the token value and saves that to the database and it does indeed work, so I'm not sure why delete isn't working. It doesn't throw any exceptions either, just doesn't persist it to the database. It doesn't work against my oracle database either.

仍然有此问题.通过将其添加到我的TokenRepository接口中,我能够将其删除保存到数据库中:

Still having this issue. I was able to get the delete to persist to the database by adding this to my TokenRepository interface:

@Modifying
@Query("delete from Token t where t.id = ?1")
void delete(Long entityId);

但是,这不是理想的解决方案.在没有这种额外方法的情况下,我需要做什么才能使它工作?

However this is not an ideal solution. Any ideas as to what I need to do to get it working without this extra method?

推荐答案

我遇到了同样的问题

也许您的UserAccount实体具有@OneToMany,并且在某些属性上具有Cascade.

Perhaps your UserAccount entity has an @OneToMany with Cascade on some attribute.

我刚刚删除了级联,删除时它可能会持续下去...

I've just remove the cascade, than it could persist when deleting...

这篇关于删除无法使用JpaRepository的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆