修改数据库时通过websocket发送对象+消息

时间:2019-01-31 08:45:41

标签: spring postgresql hibernate websocket spring-data-jpa

我正在使用hibernate和JpaRepository + PostgreSQL。我有以下代码,侦听对数据库所做的任何修改。

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

在perform方法中,将所做的更改更新到新表中。在这一点上,我也希望通过Web套接字将此“ PermitHistory”发送回给用户。这样,当用户修改/查看表时,在客户端,他将能够收到提示,要求您对字段进行新更改,以便他可以选择刷新以显示更新。

编辑:我创建了一个新类“ PermitUpdates”

public class PermitUpdates {

    @Autowired
    private SimpMessagingTemplate template;

    public void sendUpdatedPermit(PermitHistory permitHistory) {
        if (permitHistory != null) {
            this.template.convertAndSend("/changes", permitHistory);
        }
    }
}

我还添加了一个WebSocketConfig类

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

}

与此发生一个新的错误:

Caused by: java.lang.NullPointerException
    at com.example.historical.websoc.PermitUpdates.sendUpdatedPermit(PermitUpdates.java:19)

我在做什么错了?

0 个答案:

没有答案