Delete Not Working with JpaRepository

前端 未结 12 2010
情书的邮戳
情书的邮戳 2020-12-07 11:55

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 impleme         


        
相关标签:
12条回答
  • 2020-12-07 12:47

    If you use an newer version of Spring Data, you could use deleteBy syntax...so you are able to remove one of your annotations :P

    the next thing is, that the behaviour is already tract by a Jira ticket: https://jira.spring.io/browse/DATAJPA-727

    0 讨论(0)
  • 2020-12-07 12:50

    I had the same problem

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

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

    0 讨论(0)
  • 2020-12-07 12:50

    One way is to use cascade = CascadeType.ALL like this in your userAccount service:

    @OneToMany(cascade = CascadeType.ALL)
    private List<Token> tokens;
    

    Then do something like the following (or similar logic)

    @Transactional
    public void deleteUserToken(Token token){
        userAccount.getTokens().remove(token);
    }
    

    Notice the @Transactional annotation. This will allow Spring (Hibernate) to know if you want to either persist, merge, or whatever it is you are doing in the method. AFAIK the example above should work as if you had no CascadeType set, and call JPARepository.delete(token).

    0 讨论(0)
  • 2020-12-07 12:51

    CascadeType.PERSIST and orphanRemoval=true doesn't work together.

    0 讨论(0)
  • 2020-12-07 12:57

    I just went through this too. In my case, I had to make the child table have a nullable foreign key field and then remove the parent from the relationship by setting null, then calling save and delete and flush.

    I didn't see a delete in the log or any exception prior to doing this.

    0 讨论(0)
  • 2020-12-07 12:58
    @Transactional
    int deleteAuthorByName(String name);
    

    you should write @Transactional in Repository extends JpaRepository

    0 讨论(0)
提交回复
热议问题