no

How to Convert JPA to Spring Events

Learn how to convert JPA to Spring events. This is normally used in observer pattern when you want to do something after an operation has be...

Learn how to convert JPA to Spring events. This is normally used in observer pattern when you want to do something after an operation has been done on an entity. For example, you want to send an email or initiate an HTTP request after an entity has been created.

1. Introduction

To demonstrate this functionality a Spring Boot project will be created that will have one entity Book. Entity create, update, and delete operations will be observed.

*Lombok will be used to automatically generates getters and setters.

2. Entity Listener, Entity, and Repository

Entity Listener - this component is responsible for listening to JPA events and converting it to Spring. Notice the use of ApplicationEventPublisher.

@Component
public class JpaToSpringEvent {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @PrePersist
    public void created(Object e) {
        applicationEventPublisher.publishEvent(new CreatedJpaEvent(e));
    }

    @PreUpdate
    public void updated(Object e) {
        applicationEventPublisher.publishEvent(new UpdatedJpaEvent(e));
    }

    @PreRemove
    public void removed(Object e) {
        applicationEventPublisher.publishEvent(new RemovedJpaEvent(e));
    }
}
Book Entity - this is a classic book entity example. Note that I'm using Lombok to generate getters and setters
@Entity
@Data
@EntityListeners(JpaToSpringEvent.class)
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
}
Book Repository - again nothing extraordinary here
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

}

3. Event Objects

The event objects can be defined based on requirements. Here, 3 events are created for create, update, and remove.

Let's see an example for create:

@Data
@EqualsAndHashCode(callSuper = false)
public class JpaEvent extends ApplicationEvent {

    private static final long serialVersionUID = -5409982028671451419L;

    public final String eventType;

    public JpaEvent(Object source, String eventType) {
        super(source);
        this.eventType = eventType;
    }

    @Override
    public String toString() {
        return eventType + " " + source;
    }
}

public class CreatedJpaEvent extends JpaEvent {

    private static final long serialVersionUID = -8923264580035968707L;

    public CreatedJpaEvent(Object source) {
        super(source, "CREATED");
    }
}

4. Spring Event Listener

SpringEventListener - This class listens to Spring events. One can argue, why not just put these codes in the entity listener? In some cases that is enough. For example, if you just want to set a field in the entity during an update like updateAt. But it's not recommended for cases wherein the observer needs to perform complex tasks and depends on several components.

@Component
public class SpringEventListener {

    @EventListener
    public void onJpaEntityCreated(CreatedJpaEvent e) {
        System.out.println("create jpa event received " + e);
    }

    @EventListener
    public void onJpaEntityUpdated(UpdatedJpaEvent e) {
        System.out.println("update jpa event received " + e);
    }

    @EventListener
    public void onJpaEntityRemoved(RemovedJpaEvent e) {
        System.out.println("remove jpa event received " + e);
    }
}

5. Testing the Application

To test the events, a test class is created to perform create, update, and remove entity database operations.

@SpringBootTest
class JpaToSpringEventsApplicationTests {

    @Autowired
    private BookRepository bookRepository;

    @Test
    void contextLoads() {
    }

    @Test
    public void whenCreateUpdateRemoveBook_thenOk() {
        Book book = new Book();
        book.setName("Mahouka Koukou");
        bookRepository.save(book);

        book.setName("Gate Jietai");
        bookRepository.save(book);

        bookRepository.delete(book);
    }

}

To run the test, navigate to the project's base directory and execute: mvn test.

6. References:

Related

coding 3668505725509291649

Post a Comment Default Comments

item