如何使用 spring-data-neo4j-cross-store 在 neo4j 和 postgres 之间的部分 NodeEntity 上支持跨存储持久性?

Posted

技术标签:

【中文标题】如何使用 spring-data-neo4j-cross-store 在 neo4j 和 postgres 之间的部分 NodeEntity 上支持跨存储持久性?【英文标题】:How can I support cross-store persistence on a partial NodeEntity between neo4j and postgres with spring-data-neo4j-cross-store? 【发布时间】:2015-09-04 09:27:10 【问题描述】:

我想在我的应用程序中同时使用 Postgres 和 Neo4j。我能够配置它们,但是,我很难持久化部分节点实体(跨存储持久性)。

鉴于以下配置和实体。似乎我能够将传统的 RDBMS JPA 实体持久化到 postgres 数据库和将 NodeEntity 持久化到 neo4j 数据库,但是,当尝试通过跨存储持久性将部分实体持久化到两者时,我得到了下面的堆栈跟踪。它抱怨 java.lang.ClassCastException 说我的 PartialEntity 不能转换为 NodeBacked。我相信它一定与跨商店配置有关,但我无法找到根本问题。

我在 github 上创建了一个示例项目来演示我面临的问题。请随时在这里查看https://github.com/StevenGall/***-question-spring-data-neo4j-cross-store

部分节点实体

@Entity
@Table(name = "partial_entity")
@NodeEntity(partial = true)
public class PartialEntity extends AbstractEntity

  @GraphId Long graphId;

  /**
   * A free form text description.
   */
  @Column(name = "description")
  @Graphproperty
  private String description;

  /**
   * The name given by the User
   */
  @Column(name = "name", nullable = false)
  @GraphProperty
  private String name;

 //getters and setters omitted

全节点实体

@NodeEntity
public class FullNodeEntity


  @GraphId Long graphId;

  /**
   * A free form text description   */

  private String description;

  /**
   * The name given by the User
   */
  private String name;
//getters and setters omitted


用户(一个 JPA 实体)

@Entity
@Table(name = "user_profile")
public class User extends AbstractEntity

  private static final long serialVersionUID = 53887647670812546L;

  /**
   * The first name of the user.
   */
  @Column(name = "first_name", nullable = false)
  @NotEmpty

  protected String firstName;

  /**
   * The last name of the user.
   */
  @Column(name = "last_name", nullable = false)
  @NotEmpty
  protected String lastName;

  /**
   * The email address of the user. This is used as a username.
   */
  @Column(name = "email", nullable = false, unique = true)
  @NotEmpty
  protected String email;

  /**
   * The role of the user.
   */
  @Column(name = "role", nullable = false)
  @Enumerated(EnumType.STRING)
  @NotNull
  protected Role role;

//getters and setters omitted

AbstractEntity(提供 id 和审计资料)

@EntityListeners(AuditingEntityListener.class)
  @MappedSuperclass
  public abstract class AbstractEntity 

    /**
     * The class logger.
     */
    private static final Logger LOG = LogManager.getLogger(AbstractEntity.class);

    /**
     * The entity id.
     */
    @Column(name = "id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonIgnore
    @NotNull
    private long id;

    /**
     * The date the entity was created.
     */
    @CreatedDate
    @Column(name = "created_date", updatable = false)
    private Calendar createdDate;

    /**
     * The last time the entity was modified.
     */
    @LastModifiedDate
    @Column(name = "modified_date")
    private Calendar modifiedDate;

//getters and setters omitted

堆栈跟踪

java.lang.ClassCastException: com.example.entity.graph.PartialEntity cannot be cast to org.springframework.data.neo4j.aspects.core.NodeBacked
    at org.springframework.data.neo4j.cross_store.support.node.CrossStoreNodeEntityStateFactory.getEntityState(CrossStoreNodeEntityStateFactory.java:55)
    at org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.copyPropertiesTo(SourceStateTransmitter.java:95)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.write(Neo4jEntityConverterImpl.java:170)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.write(Neo4jEntityPersister.java:179)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:247)
    at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:235)
    at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:365)
    at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:354)
    at org.springframework.data.neo4j.repository.AbstractGraphRepository.save(AbstractGraphRepository.java:91)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:414)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:399)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:371)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy113.save(Unknown Source)
    at com.example.api.controller.UserController.test(UserController.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:291)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:155)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:102)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Neo4jConfig

@Configuration
@EnableTransactionManagement(mode=AdviceMode.ASPECTJ)
@EnableNeo4jRepositories(basePackages = "com.example.repository.graph")
public class Neo4jConfig extends CrossStoreNeo4jConfiguration

  Neo4jConfig()
    setBasePackage("com.example.entity.graph");
  

  @Bean(destroyMethod = "shutdown")
  public GraphDatabaseService graphDatabaseService()
      return new SpringCypherRestGraphDatabase("http://localhost:7474/db/data","neo4j", "neo4j");

  


SpringDataConfig

@Configuration
@EnableJpaAuditing
@EnableTransactionManagement(mode=AdviceMode.ASPECTJ)
@EnableJpaRepositories(basePackages = "com.example.repository.rdbms", entityManagerFactoryRef="entityManagerFactory", transactionManagerRef="transactionManager")
public class SpringDataConfig 

  // @Bean
  // public AuditorAware<AuditableUser> auditorProvider() 
  // return new AuditorAwareImpl();
  // 

SpringSecurityConfig

@EnableWebSecurity
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter 

  /**
   * Environment configuration properties.
   */
  @Autowired
  private Environment env;

  /**
   * User Service to encode passwords.
   */
  @Autowired
  private UserService userService;

  /*
   * (non-Javadoc)
   * 
   * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.
   * springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder)
   */
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception 
    auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
  

  /*
   * (non-Javadoc)
   * 
   * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.
   * springframework.security.config.annotation.web.builders.HttpSecurity)
   */
  @Override
  protected void configure(HttpSecurity http) throws Exception 
    http.httpBasic().and().authorizeRequests().antMatchers("/resources/**", "/signup", "/users", "/users/test").permitAll()
        .anyRequest().authenticated().and().formLogin().usernameParameter("email").permitAll().and().logout()
        .logoutUrl("/logout").logoutSuccessUrl("/").permitAll().and().csrf().disable();
  

应用配置

@SpringBootApplication
public class ApiConfiguration 

  /**
   * Main entry point for the REST API of the application.
   * 
   * @param args Command line arguments.
   */
  public static void main(String[] args) 
    SpringApplication.run(ApiConfiguration.class, args);
  

  @Bean
  @Profile("local")
  public EmbeddedServletContainerFactory servletContainer() 
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();

    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();

    try 
      File keystore = new ClassPathResource("config/local/local.keystore").getFile();
      connector.setScheme("https");
      connector.setSecure(true);
      connector.setPort(8443);
      protocol.setSSLEnabled(true);
      protocol.setKeystoreFile(keystore.getAbsolutePath());
      protocol.setKeystorePass("changeit");
      protocol.setKeyAlias("tomcat");
     catch (IOException ex) 
      throw new IllegalStateException("Unable to access keystore", ex);
    

    tomcat.addAdditionalTomcatConnectors(connector);
    return tomcat;
  

一些测试代码

@Autowired
PartialEntityRepository partialEntityRepository;

@Autowired
FullNodeEntityRepository fullNodeEntityRepository;

@Autowired
UserService userService;

@RequestMapping("/test")
public void test() 
    User owner = new User();
    owner.setFirstName("Tiny");
    owner.setLastName("Tim");
    owner.setEmail("tiny.tim@test.com");
    owner.setRole(Role.USER);
    UserDetails userDetails = new UserDetails();
    userDetails.setPassword("test");
    Optional<User> ownerOpt = userService.create(owner, userDetails); /this persists to postgres

    FullNodeEntity fullNodeEntity = new FullNodeEntity();
    fullNodeEntity.setName("Test Name");
    fullNodeEntity.setDescription("Test Description");
    fullNodeEntityRepository.save(fullNodeEntity); //this persists to neo4j

    PartialEntity partialEntity = new PartialEntity();
    partialEntity.setName("Test Name");
    partialEntity.setDescription("Test Description");
    partialEntityRepository.save(partialEntity); //This throws the exception


【问题讨论】:

相关! ***.com/questions/30920503/… 【参考方案1】:

根据 Michael Hunger 和 Oliver Gierke 的说法,跨存储持久性是一个没有成功的实验(请参阅 https://twitter.com/mesirii/status/611659457291026432 )。对于多语言持久性,您似乎必须自己动手;)

【讨论】:

是否有任何关于如何滚动我们自己的教程或示例?我们在哪里可以学习做到这一点?我问是因为我想在我的应用程序中同时使用 JPA 和 Neo4J ***.com/questions/32296676/… 不幸的是,没有滚动您自己的示例,但是有一些公认的方法可以实现最终的一致性。第一个是像 Atomikos 或 Bitronix(更多信息 javaworld.com/article/2077714/java-web-development/…)这样的全局事务管理器,使用 SQS、RabbitMQ 等消息传递系统建立最终一致性。或者使用链式事务管理器使用尽力而为的方法(更多信息***.com/questions/15817909/…) 另见以下 SO ***.com/questions/30920503/… @simonl 也很有用,javaworld.com/article/2077963/open-source-tools/…

以上是关于如何使用 spring-data-neo4j-cross-store 在 neo4j 和 postgres 之间的部分 NodeEntity 上支持跨存储持久性?的主要内容,如果未能解决你的问题,请参考以下文章

未知的持久性实体错误

spring boot 2.0 neo4j 使用

在 Spring Boot 应用程序中使用 API 网关时,HATEOAS 路径无效

我想在我的neo4j属性中设置(updatable = false)

Neo4j与springdata集成

有没有办法像 Hibernate 一样在 Neo4J 上记录查询?