2

I'm using Neo4j OGM 2.1.3 with Spring Boot 1.5.9 in the documentation reference of both spring data and neo4j ogm, registration of event listener is explained as the following code.

    class AddUuidPreSaveEventListener implements EventListener {

    void onPreSave(Event event) {
        DomainEntity entity = (DomainEntity) event.getObject():
        if (entity.getId() == null) {
            entity.setUUID(UUID.randomUUID());
        }
    }
    void onPostSave(Event event) {
    }
    void onPreDelete(Event event) {
    }
    void onPostDelete(Event event) {
    }

   EventListener eventListener = new AddUuidPreSaveEventListener();

// register it on an individual session
session.register(eventListener);

// remove it.
session.dispose(eventListener);

// register it across multiple sessions
sessionFactory.register(eventListener);

// remove it.
sessionFactory.deregister(eventListener);

In my code I can't find a way to get an instance of the session.

@SpringBootApplication
@EntityScan("movies.spring.data.neo4j.domain")
public class SampleMovieApplication extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(SampleMovieApplication.class, args);

    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(applicationClass);
    }

    private static Class<SampleMovieApplication> applicationClass = SampleMovieApplication.class;
}

I run the project using the code snippet above.

My question is: how can I get an instance of the session and use it to register the event listener?.

Edit: my code is built using this code example on GitHub

Ali.Wassouf
  • 309
  • 4
  • 21

1 Answers1

2

AFAIK it is not possible to access the current session without opening it manually. But this would not match the idea of SpringData(Neo4j).

You can register the EventListener on the SessionFactory that can be accessed when injected e.g. your application configuration.

Sample:

@SpringBootApplication
public class SdnApplication {

  private final SessionFactory sessionFactory;

  public SdnApplication(SessionFactory sessionFactory) {
      this.sessionFactory = sessionFactory;
  }

  @PostConstruct
  public void registerEventlistener() {
      sessionFactory.register(new EventListenerAdapter() {
        @Override public void onPreSave(Event event) {
            System.out.println("about to save sth");
        }
      });
  }

  public static void main(String[] args) {
    SpringApplication.run(SdnApplication.class, args);
  }

} 
meistermeier
  • 7,942
  • 2
  • 36
  • 45
  • I added the code related to session to my class but i'm getting an exception `java.lang.NoSuchMethodException: social.spring.data.neo4j.SampleMovieApplication.()` – Ali.Wassouf Jan 13 '18 at 19:50