I'm using hibernate and JpaRepository + PostgreSQL. I have the following code which listens to any modifications made to the database.
public class PermitEntityListener {
@PrePersist
public void prePersist(Permit target) {
perform(target, INSERTED);
}
@PreUpdate
public void preUpdate(Permit target) {
perform(target, UPDATED);
}
@PreRemove
public void preRemove(Permit target) {
perform(target, DELETED);
}
@Transactional(MANDATORY)
private void perform(Permit target, Action action) {
EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
entityManager.persist(new PermitHistory(target, action));
//Send permitHistory to client via websocket to update changes
PermitUpdates updates = new PermitUpdates();
updates.sendUpdatedPermit(new PermitHistory(target, action));
}
}
In the method perform, it is where changes made would be updated into a new table. At this point, i wish to also send this "PermitHistory" back to the user via a web socket. This is so that when the user is modifying/viewing the table, on the client side he will be able to receive a prompt that new changes have been made to the fields so he can choose to refresh to display the updates.
Edit: I created a new class "PermitUpdates"
public class PermitUpdates {
@Autowired
private SimpMessagingTemplate template;
public void sendUpdatedPermit(PermitHistory permitHistory) {
if (permitHistory != null) {
this.template.convertAndSend("/changes", permitHistory);
}
}
}
I also added a WebSocketConfig class
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/changes");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket").withSockJS();
}
}
With this a new error occured:
Caused by: java.lang.NullPointerException
at com.example.historical.websoc.PermitUpdates.sendUpdatedPermit(PermitUpdates.java:19)
What am i doing wrong?