107

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
}

I have a JpaRepository interface defined:

public interface TokenRepository extends JpaRepository<Token, Long> {

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

}

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

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.


Edit

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?

userspaced
  • 1,273
  • 2
  • 10
  • 9
  • 4
    did you ever find a solution to this? same problem in very latest spring version also. according to mysql log table, no deletion statement is ever issued, no error message available. – phil294 Aug 07 '18 at 13:50
  • 1
    Unfortunately no. I no longer had a need to do it here anymore and the other places I had to do it seemed to work fine. I don't know what was so special about this case. – userspaced Aug 07 '18 at 17:04
  • you should consider posting that @Modifying delete statement as an answer. It was the only way I could resolve it as well. I upvoted the question, but I'd upvote that answer as well. – Taugenichts Jul 15 '19 at 21:27
  • 2
    overriding the delete method(s) solved it for me as well, not sure why this happened (upgrading from spring boot 2.1.5 to 2.1.6) – Brunaldo Jun 23 '20 at 15:53
  • Same problem here on a most simple entity using no relations. save then delete in one transaction, e.g. test method works no longer with Spring 2.1.6. We use Spring 2.4.1 now, but downgrade spring-data to 2.1.8.RELEASE to overcome it. Hibernate remains unchanged 5.4.25. – JRA_TLL Jun 07 '21 at 08:39

14 Answers14

98

Most probably such behaviour occurs when you have bidirectional relationship and you're not synchronizing both sides WHILE having both parent and child persisted (attached to the current session).

This is tricky and I'm gonna explain this with the following example.

@Entity
public class Parent {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "parent")
    private Set<Child> children = new HashSet<>(0);

    public void setChildren(Set<Child> children) {
        this.children = children;
        this.children.forEach(child -> child.setParent(this));
    }
}
@Entity
public class Child {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;

    public void setParent(Parent parent) {
        this.parent = parent;
    }
}

Let's write a test (a transactional one btw)

public class ParentTest extends IntegrationTestSpec {

    @Autowired
    private ParentRepository parentRepository;

    @Autowired
    private ChildRepository childRepository;

    @Autowired
    private ParentFixture parentFixture;

    @Test
    public void test() {
        Parent parent = new Parent();
        Child child = new Child();

        parent.setChildren(Set.of(child));
        parentRepository.save(parent);

        Child fetchedChild = childRepository.findAll().get(0);
        childRepository.delete(fetchedChild);

        assertEquals(1, parentRepository.count());
        assertEquals(0, childRepository.count()); // FAILS!!! childRepostitory.counts() returns 1
    }
}

Pretty simple test right? We're creating parent and child, save it to database, then fetching a child from database, removing it and at last making sure everything works just as expected. And it's not.

The delete here didn't work because we didn't synchronized the other part of relationship which is PERSISTED IN CURRENT SESSION. If Parent wasn't associated with current session our test would pass, i.e.

@Component
public class ParentFixture {
    ...
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void thereIsParentWithChildren() {
        Parent parent = new Parent();
        Child child = new Child();
        parent.setChildren(Set.of(child));

        parentRepository.save(parent);
    }
} 

and

@Test
public void test() {
    parentFixture.thereIsParentWithChildren(); // we're saving Child and Parent in seperate transaction

    Child fetchedChild = childRepository.findAll().get(0);
    childRepository.delete(fetchedChild);

    assertEquals(1, parentRepository.count());
    assertEquals(0, childRepository.count()); // WORKS!
}

Of course it only proves my point and explains the behaviour OP faced. The proper way to go is obviously keeping in sync both parts of relationship which means:

class Parent {
    ...
     public void dismissChild(Child child) {
         this.children.remove(child);
     }

     public void dismissChildren() {
        this.children.forEach(child -> child.dismissParent()); // SYNCHRONIZING THE OTHER SIDE OF RELATIONSHIP 
        this.children.clear();
     }

}

class Child {
    ...
    public void dismissParent() {
        this.parent.dismissChild(this); //SYNCHRONIZING THE OTHER SIDE OF RELATIONSHIP
        this.parent = null;
    }
}

Obviously @PreRemove could be used here.

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
pzeszko
  • 1,989
  • 18
  • 29
  • 3
    Real good job on the explanation here. I had the same issue and the same apparent "workaround" - delete through a custom query, but I didn't want to use it as it was obviously a hack. The @PreRemove hook really did wonders here. Thanks! – Ognjen Mišić Oct 31 '19 at 10:17
  • Glad I could help! – pzeszko Oct 31 '19 at 15:29
  • I had a similar issue with @OneToOne relation and your explanation helped me to resolve it. Very nice! Thank you. – driversti Mar 15 '21 at 12:05
  • kind of late to this, but what do you mean by synchronizing in this context? – kelsanity Aug 30 '21 at 13:54
49

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

Davi Arimateia
  • 717
  • 6
  • 15
  • 1
    This worked for me as well. Specifically I played around and was able to keep these cascade types: [CascadeType.PERSIST,CascadeType.REFRESH] and still get the delete to work through child repository. What made no sense to me is that I made the owner entity the child via "mappedBy" on the parent – GameSalutes Apr 05 '16 at 22:36
  • 19
    This solution seems to work but does not give any explanation . – Ivan Matavulj May 08 '17 at 15:51
  • Would you like to share any explanation? It has helped me as well. – gromyk Sep 11 '22 at 23:03
20

You need to add PreRemove function ,in the class where you have many object as attribute e.g in Education Class which have relation with UserProfile Education.java

private Set<UserProfile> userProfiles = new HashSet<UserProfile>(0);

@ManyToMany(fetch = FetchType.EAGER, mappedBy = "educations")
public Set<UserProfile> getUserProfiles() {
    return this.userProfiles;
}

@PreRemove
private void removeEducationFromUsersProfile() {
    for (UsersProfile u : usersProfiles) {
        u.getEducationses().remove(this);
    }
}
Taimur
  • 559
  • 11
  • 24
9

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

venge
  • 177
  • 1
  • 9
4

This is for anyone coming from Google on why their delete method is not working in Spring Boot/Hibernate, whether it's used from the JpaRepository/CrudRepository's delete or from a custom repository calling session.delete(entity) or entityManager.remove(entity).

I was upgrading from Spring Boot 1.5 to version 2.2.6 (and Hibernate 5.4.13) and had been using a custom configuration for transactionManager, something like this:

@Bean
public HibernateTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    return new HibernateTransactionManager(entityManagerFactory.unwrap(SessionFactory.class));
}

And I managed to solve it by using @EnableTransactionManagement and deleting the custom transactionManager bean definition above.

If you still have to use a custom transaction manager of sorts, changing the bean definition to the code below may also work:

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    return new JpaTransactionManager(entityManagerFactory);
}

As a final note, remember to enable Spring Boot's auto-configuration so the entityManagerFactory bean can be created automatically, and also remove any sessionFactory bean if you're upgrading to entityManager (otherwise Spring Boot won't do the auto-configuration properly). And lastly, ensure that your methods are @Transactional if you're not dealing with transactions manually.

Toribio
  • 3,963
  • 3
  • 34
  • 48
4

I was facing the similar issue.

Solution 1:

The reason why the records are not being deleted could be that the entities are still attached. So we've to detach them first and then try to delete them.

Here is my code example:

User Entity:

@Entity
public class User {
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
    private List<Contact> contacts = new ArrayList<>();
}

Contact Entity:

@Entity
public class Contact {
    @Id
    private int cId;
    
    @ManyToOne
    private User user;
}

Delete Code:

user.getContacts().removeIf(c -> c.getcId() == contact.getcId());
this.userRepository.save(user);
this.contactRepository.delete(contact);

Here we are first removing the Contact object (which we want to delete) from the User's contacts ArrayList, and then we are using the delete() method.

Solution 2:

Here we are using the orphanRemoval attribute, which is used to delete orphaned entities from the database. An entity that is no longer attached to its parent is known as an orphaned entity.

Code example:

User Entity:

@Entity
public class User {
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user", orphanRemoval = true)
    private List<Contact> contacts = new ArrayList<>();
}

Contact Entity:

@Entity
public class Contact {
    @Id
    private int cId;
    
    @ManyToOne
    private User user;
}

Delete Code:

user.getContacts().removeIf(c -> c.getcId() == contact.getcId());
this.userRepository.save(user);

Here, as the Contact entity is no longer attached to its parent, it is an orphaned entity and will be deleted from the database.

3

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.

Lucas Holt
  • 3,826
  • 1
  • 32
  • 41
  • I had the same problem and came across this thread. I don't know if I would call this a solution or a workaround, but this is how to delete the child objects. – Brian Kates Nov 18 '15 at 15:59
2

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

Eruvanos
  • 670
  • 7
  • 13
2
@Transactional
int deleteAuthorByName(String name);

you should write @Transactional in Repository extends JpaRepository

M Shafaghi
  • 61
  • 5
1

Your initial value for id is 500. That means your id starts with 500

@SequenceGenerator(name = "seqToken", sequenceName = "SEQ_TOKEN",
initialValue = 500, allocationSize = 1)

And you select one item with id 1 here

 Token deleted = tokenRepository.findOne(1L);

So check your database to clarify that

Bitman
  • 1,996
  • 1
  • 15
  • 18
  • I don't think that's the issue here because when I seed the test with test data I'm specifying the id to be 1. – userspaced Mar 28 '14 at 12:47
1

I've the same problem, test is ok but on db row isn't deleted.

have you added the @Transactional annotation to method? for me this change makes it work

0

In my case was the CASCADE.PERSIST, i changed for CASCADE.ALL, and made the change through the cascade (changing the father object).

Sham Fiorin
  • 403
  • 4
  • 16
0

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

Dejan
  • 353
  • 2
  • 12
0

Try calling deleteById instead of delete on the repository. I also noticed that you are providing an Optional entity to the delete (since findOne returns an Optional entity). It is actually strange that you are not getting any compilation errors because of this. Anyways, my thinking is that the repository is not finding the entity to delete.

Try this instead:

@Test
public void testDeleteToken() {
    assertThat(tokenRepository.findAll().size(), is(2));

    Optional<Token> toDelete = tokenRepository.findOne(1L);
    toDelete.ifExists(toDeleteThatExists -> tokenRepository.deleteById(toDeleteThatExists.getId()))

    tokenRepository.flush();
    assertThat(tokenRepository.findAll().size(), is(1));
}

By doing the above, you can avoid having to add the @Modifying query to your repository (since what you are implementing in that @Modifying query is essentially the same as calling deleteById, which already exists on the JpaRepository interface).