0

I have a POJO managed by JPA that creates an external resource (via an HTTP message) inside a @PostConstruct annotated method. When that Entity is deleted like so em.delete(instance) I'd like for the cleanUp method to be called. I was thinking this could likely be done with an annotation provided by JPA but my search has turned up nothing. Below is an example entity.

@Entity
public class ExampleEntity {

    // Constructors and Fields

    @JpaAnnotation
    public void cleanUp() {
        // Performs clean up
    }

    // Methods

}

An additional example displaying how I'm using the cleanUp method.

@Entity
@Component
public class ExampleEntity {

    // Id and managed columns
    private String externalResourceId;

    @Transient
    private static CustomHttpService service;

    // Constructors

    @Autowired
    public void setCustomHttpService(CustomHttpService service) {
        ExampleEntity.service = service;
    }

    // Methods

    @PostConstruct
    public void createExternalResource() {
        if (externalResourceId == null || externalResourceId.isEmpty()) {
            externalResourceId = service.createExternalResource();
        }
    }

    @JpaAnnotation
    public void deleteExternalResource() { // This is my example of the cleanUp method
        service.deleteExternalResource(externalResourceId);
    }

}
Alex Malcolm
  • 529
  • 1
  • 7
  • 18

2 Answers2

2

Pojo managed by JPA is called Entity.

Entity has lifecycle callback methods:

@PrePersist/@PostPersist
@PreRemove/@PostRemove
@PreUpdate/@PostUpdate
@PostLoad

@PostConstruct, @PostRemove is callback method for Spring beans. It will be never called, because entities are not created by Spring. Entity represents table row data, they are managed by JPA. You create them using new keyword when inserting data. When reading from DB they are created by JPA.

Peter Šály
  • 2,848
  • 2
  • 12
  • 26
1

You could use an EntityListener to track entity states, you can check the hibernate documentation.

First you need to create an EntityListener using annotations:

public class UserListener {
    @PreRemove
    public void userPreRemove(User ob) {
        System.out.println("Listening User Pre Remove : " + ob.getName());
    }

    @PostRemove
    public void userPostRemove(User ob) {
        System.out.println("Listening User Post Remove : " + ob.getName());
    }
} 

Then you indicate what entity should audit:

@Entity
@EntityListeners(UserListener.class)
@Table(name="user")
public class User {
   private String name;

   // Attributes, getters and setters

}
Cristian Colorado
  • 2,022
  • 3
  • 19
  • 24