SDN4 枚举到字符串转换失败

SDN4 Enum to String conversion fails

我有一个实体class:

@Data
@JsonIdentityInfo(generator=JSOGGenerator.class)

@NodeEntity(label="Person")
public class PersonNode  {
    @GraphId                       private @NonNull Long id;
    @Property(name="neo_ID")    private @NonNull Long ID;
    @Property(name="neo_name")     private @NonNull String name;
    @Property(name="neo_surname")  private @NonNull String surname;
    @Property(name="neo_spec")     private @NonNull String specialization;
    @Property(name="neo_gender")   private @NonNull @Convert(graphPropertyType = String.class)
                                                    Gender sex;
    @Property(name="neo_age")      private @NonNull Byte age;

    public PatientNode() {
    }

Gender 类型:

public enum Gender {
    MALE("M"), 
    FEMALE("F"), 
    UNKNOWN("");

    private final String gender;

    Gender(String sex){
        if (sex.toUpperCase().equals("F") || sex.toUpperCase().equals("M") )
            this.gender = sex.toUpperCase();
        else
            this.gender="";
    }

    String getGender(){
        return this.gender;
    }

    public static Gender toGender(String str){
        try {
            return valueOf(str.toUpperCase(Locale.ENGLISH));
        }
        catch (Exception ex) {
            return UNKNOWN;
        }
    }

    public String toString(){
        return this.gender;
    }
}

我添加了:

@Bean
public ConversionService conversionService() {
    return new MetaDataDrivenConversionService(getSessionFactory().metaData());
}

给我的 public class MyNeo4jConfiguration extends Neo4jConfiguration 现在的问题是,当我尝试使用 GrpahRepositry<person> 默认 findAll() 方法从 Neo4j 读取时,出现错误:

产生错误:

No converter found capable of converting from type java.lang.String to type .server.infrastructure.persistence.utils.Gender

1.有什么问题吗?

2。由于 Neo4j 不支持枚举类型,如何为 SDN4 提供这种简单的转换?

编辑:

问题依然存在。根据@Luanne 提示更改我的 Neo4jConfiguration 后,它看起来如下:

package server.infrastructure.repositories.neo4j.config;

import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.*;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.conversion.MetaDataDrivenConversionService;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.server.Neo4jServer;
import org.springframework.data.neo4j.server.RemoteServer;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableNeo4jRepositories(basePackages = "server.infrastructure.repositories.neo4j")

@EnableTransactionManagement
@ComponentScan(basePackages = "server.services.neo4j")


public class MyNeo4jConfiguration extends Neo4jConfiguration {

    public static final int NEO4J_PORT=7474;
    public static final String USER_NAME="neo4j";
    public static final String USER_PASS="aaa";

    @Bean
    public Neo4jServer neo4jServer() {

        return new RemoteServer("http://localhost:"+NEO4J_PORT, USER_NAME, USER_PASS);
    }

    @Bean
    public SessionFactory getSessionFactory() {
        // with domain entity base package(s)
        return new SessionFactory("server.infrastructure.persistence.neo4j");
    }

    // needed for session in view in web-applications
    @Bean
    @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public Session getSession() throws Exception {
        return super.getSession();
    }

    // For enum / date / biginteger etc types in entities conversion
    @Bean
    public ConversionService conversionService() {
        ConversionService conversionService = new MetaDataDrivenConversionService(getSessionFactory().metaData());
        DefaultConversionService.addDefaultConverters((GenericConversionService) conversionService);

        return conversionService;
    }


}

我正在使用以下 pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>testing</groupId>
  <artifactId>serverT</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>serverMR</name>
  <url>http://maven.apache.org</url>

  <properties>

      <!-- Generic properties -->
      <java.version>1.8</java.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

      <!-- Spring -->
      <spring.version>4.2.1.RELEASE</spring.version>
      <spring-data.version>Gosling-RELEASE</spring-data.version>
      <spring-data-neo4j.version>4.0.0.RELEASE</spring-data-neo4j.version>

      <!-- Logging -->
      <logback.version>1.1.3</logback.version>
      <jcl.slf4j.version>1.7.12</jcl.slf4j.version>
  </properties>


    <build>
        <plugins>
            <!-- To run application with tomcat7:run -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/</path>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>


        </plugins>
    </build>


  <dependencyManagement>
      <dependencies>

          <!-- For spring framework dependencies version compatibility -->
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-framework-bom</artifactId>
              <version>${spring.version}</version>
              <scope>import</scope>
              <type>pom</type>
          </dependency>

          <!-- For spring-data  dependencies version compatibility -->
          <dependency>
              <groupId>org.springframework.data</groupId>
              <artifactId>spring-data-releasetrain</artifactId>
              <version>${spring-data.version}</version>
              <scope>import</scope>
              <type>pom</type>
          </dependency>


    </dependencies>

  </dependencyManagement>


  <dependencies>

      <!-- hypermedia-driven REST web services on top of Spring Data infrastructure
            - version from spring-data-releasetrain
       -->
      <dependency>
          <groupId>org.springframework.data</groupId>
          <artifactId>spring-data-rest-webmvc</artifactId>
      </dependency>

      <!-- Force newer version than spring-data-releasetrain -->
      <dependency>
          <groupId>org.springframework.data</groupId>
          <artifactId>spring-data-neo4j</artifactId>
          <version>${spring-data-neo4j.version}</version>
      </dependency>


      <!-- For autogeneration of getter/setter-->
      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.14.8</version>
      </dependency>

      <!-- JUnit -->
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
      </dependency>

      <!--To run application with tomcat7:run force servlet 3.1 version to be used-->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
          <scope>provided</scope>
      </dependency>

      <!--To avoid circular JSON generation, the JSOGGenerator is used as id-generator in entities-->
      <dependency>
          <groupId>com.voodoodyne.jackson.jsog</groupId>
          <artifactId>jackson-jsog</artifactId>
          <version>1.0.1</version>
      </dependency>



  </dependencies>

</project>

然而,枚举仍然无法使用 运行 mvn tomcat7:run 进行转换并使用控制器进行引用:

@RestController
@RequestMapping("/per")
public class PersonController {

    @Autowired
    PersonService personService;

    @RequestMapping(value = "/list",
                    method = RequestMethod.GET,
                    produces = MediaType.APPLICATION_JSON_VALUE
                    )
    public List<PersonNode> getPersons){

        return personService.getList();
    }

}

和服务:

@Service

@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PersonService implements FinderService<PersonNode> {

    private final @NonNull PersonNeo4JRepository personNeo4JRepository;

    public List<PersonNode> getList(){

        Iterable<PersonNode> iterablePer = personNeo4JRepository.findAll();
        List<PersonNode> perList =
                new ArrayList<>(IteratorUtil.asCollection(iterablePer));


        return  perList;
    }

和 PersonRepository

@Repository
public interface PersonNeo4JRepository extends GraphRepository<PersonNode>

http://localhost:8080/rest/per/list:

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building serverMR 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] >>> tomcat7-maven-plugin:2.2:run (default-cli) @ serverMR >>>
[INFO] 
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ serverMR ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 3 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.3:compile (default-compile) @ serverMR ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] <<< tomcat7-maven-plugin:2.2:run (default-cli) @ serverMR <<<
[INFO] 
[INFO] --- tomcat7-maven-plugin:2.2:run (default-cli) @ serverMR ---
[INFO] Running war on http://localhost:8080/
[INFO] Creating Tomcat server configuration at /home/mc/Dropbox/Projekty/Robocze/serverMR/target/tomcat
[INFO] create webapp with contextPath: 
gru 17, 2015 2:46:26 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
gru 17, 2015 2:46:26 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Tomcat
gru 17, 2015 2:46:26 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
gru 17, 2015 2:46:33 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
gru 17, 2015 2:46:33 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
14:46:33.960 [localhost-startStop-1] INFO  o.s.web.context.ContextLoader - Root WebApplicationContext: initialization started
14:46:34.035 [localhost-startStop-1] INFO  o.s.w.c.s.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Thu Dec 17 14:46:34 CET 2015]; root of context hierarchy
14:46:34.071 [localhost-startStop-1] INFO  o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [spring/ApplicationContext.xml]
14:46:34.150 [localhost-startStop-1] INFO  o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [spring/Neo4j-DataSources.xml]
14:46:34.521 [localhost-startStop-1] INFO  o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'myNeo4jConfiguration' of type [class server.infrastructure.repositories.neo4j.config.MyNeo4jConfiguration$$EnhancerBySpringCGLIB$30c4f2] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
14:46:34.523 [localhost-startStop-1] INFO  o.s.d.n.config.Neo4jConfiguration - Initialising PersistenceExceptionTranslationPostProcessor
14:46:34.818 [localhost-startStop-1] INFO  o.n.o.m.info.ClassFileProcessor - Starting Post-processing phase
14:46:34.818 [localhost-startStop-1] INFO  o.n.o.m.info.ClassFileProcessor - Building annotation class map
14:46:34.818 [localhost-startStop-1] INFO  o.n.o.m.info.ClassFileProcessor - Building interface class map for 6 classes
14:46:34.818 [localhost-startStop-1] INFO  o.n.o.m.info.ClassFileProcessor - Registering default type converters...
14:46:34.823 [localhost-startStop-1] INFO  o.n.o.m.info.ClassFileProcessor - Post-processing complete
14:46:34.823 [localhost-startStop-1] INFO  o.n.o.m.info.ClassFileProcessor - 6 classes loaded in 16 milliseconds
14:46:35.094 [localhost-startStop-1] INFO  o.s.d.n.mapping.Neo4jMappingContext - Neo4jMappingContext initialisation completed
14:46:35.211 [localhost-startStop-1] INFO  o.s.d.n.config.Neo4jConfiguration - Initialising PersistenceExceptionTranslator
14:46:35.214 [localhost-startStop-1] INFO  o.s.d.n.config.Neo4jConfiguration - Initialising PersistenceExceptionTranslationInterceptor
14:46:35.217 [localhost-startStop-1] INFO  o.s.d.n.config.Neo4jConfiguration - Initialising Neo4jTransactionManager
14:46:35.255 [localhost-startStop-1] INFO  o.s.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1293 ms
14:46:35.285 [localhost-startStop-1] INFO  o.s.web.servlet.DispatcherServlet - FrameworkServlet 'MR.rest.api': initialization started
gru 17, 2015 2:46:35 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'MR.rest.api'
14:46:35.290 [localhost-startStop-1] INFO  o.s.w.c.s.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'MR.rest.api-servlet': startup date [Thu Dec 17 14:46:35 CET 2015]; parent: Root WebApplicationContext
14:46:35.291 [localhost-startStop-1] INFO  o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/SpringMVC/SpringMVC-RESTContext.xml]
14:46:35.519 [localhost-startStop-1] INFO  o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/per/list],methods=[GET],produces=[application/json]}" onto public java.util.List<server.infrastructure.persistence.neo4j.nodes.PersonNode> server.api.rest.controller.PersonController.getPersons()
14:46:35.701 [localhost-startStop-1] INFO  o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: WebApplicationContext for namespace 'MR.rest.api-servlet': startup date [Thu Dec 17 14:46:35 CET 2015]; parent: Root WebApplicationContext
14:46:35.758 [localhost-startStop-1] INFO  o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: WebApplicationContext for namespace 'MR.rest.api-servlet': startup date [Thu Dec 17 14:46:35 CET 2015]; parent: Root WebApplicationContext
14:46:35.857 [localhost-startStop-1] INFO  o.s.web.servlet.DispatcherServlet - FrameworkServlet 'MR.rest.api': initialization completed in 572 ms
gru 17, 2015 2:46:35 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
14:46:42.928 [http-bio-8080-exec-1] INFO  o.s.d.n.config.Neo4jConfiguration - Initialising Neo4jSession
14:46:43.143 [http-bio-8080-exec-1] INFO  o.s.d.n.config.Neo4jConfiguration - Intercepted exception
gru 17, 2015 2:46:43 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [MR.rest.api] in context with path [] threw exception [Request processing failed; nested exception is org.neo4j.ogm.metadata.MappingException: Error mapping GraphModel to instance of server.infrastructure.persistence.neo4j.nodes.PersonNode] with root cause
java.lang.IllegalArgumentException: No enum constant server.infrastructure.persistence.utils.Gender.M
    at java.lang.Enum.valueOf(Enum.java:238)
    at org.springframework.core.convert.support.StringToEnumConverterFactory$StringToEnum.convert(StringToEnumConverterFactory.java:59)
    at org.springframework.core.convert.support.StringToEnumConverterFactory$StringToEnum.convert(StringToEnumConverterFactory.java:45)
    at org.springframework.core.convert.support.GenericConversionService$ConverterFactoryAdapter.convert(GenericConversionService.java:425)
    at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:35)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:192)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:176)
    at org.springframework.data.neo4j.conversion.MetaDataDrivenConversionService.convert(MetaDataDrivenConversionService.java:102)
    at org.neo4j.ogm.typeconversion.ProxyAttributeConverter.toEntityAttribute(ProxyAttributeConverter.java:43)
    at org.neo4j.ogm.entityaccess.FieldWriter.write(FieldWriter.java:64)
    at org.neo4j.ogm.mapper.GraphEntityMapper.writeProperty(GraphEntityMapper.java:164)
    at org.neo4j.ogm.mapper.GraphEntityMapper.setProperties(GraphEntityMapper.java:129)
    at org.neo4j.ogm.mapper.GraphEntityMapper.mapNodes(GraphEntityMapper.java:110)
    at org.neo4j.ogm.mapper.GraphEntityMapper.mapEntities(GraphEntityMapper.java:94)
    at org.neo4j.ogm.mapper.GraphEntityMapper.map(GraphEntityMapper.java:69)
    at org.neo4j.ogm.session.response.SessionResponseHandler.loadAll(SessionResponseHandler.java:181)
    at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:69)
    at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:99)
    at org.neo4j.ogm.session.Neo4jSession.loadAll(Neo4jSession.java:119)
    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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
    at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy36.loadAll(Unknown Source)
    at org.springframework.data.neo4j.repository.GraphRepositoryImpl.findAll(GraphRepositoryImpl.java:123)
    at org.springframework.data.neo4j.repository.GraphRepositoryImpl.findAll(GraphRepositoryImpl.java:118)
    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:475)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:460)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:432)
    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.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.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy48.findAll(Unknown Source)
    at server.services.neo4j.PersonService.getList(PersonService.java:30)
    at server.api.rest.controller.PersonController.getPersons(PersonController.java:31)
    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:111)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
    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:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

由于要使用Spring提供的转换器,还需要向ConversionService注册。

例如,

 @Bean
    public ConversionService conversionService() {
        ConversionService conversionService = new MetaDataDrivenConversionService(getSessionFactory().metaData());
        DefaultConversionService.addDefaultConverters((GenericConversionService) conversionService);

        return conversionService;
    }

然后它会被捡起来使用。

根据提供的附加信息进行更新

堆栈跟踪显示正在调用转换器。但它试图找到一个值为 "M" 的枚举,但找不到。请注意,StringToEnumConverterFactory 在您的枚举上调用 valueOf(请参阅 class javadoc Converts from a String to a {@link java.lang.Enum} by calling {@link Enum#valueOf(Class, String)}.) 存储在图表中的值将是您的枚举名称 MALE,它将很好地转换回来。

那么,这是否意味着您的图表中有 neo_gender=M 的数据?如果是这样,也许您需要清理它,或者提供一个能够处理这两种情况的自定义转换器。

我有一个类似的问题,枚举 属性 没有被转换并且在加载对象时被设置为 null。

我的修复有两个方面,

  1. 添加接受的答案中提到的 ConversionService 配置,并且
  2. 将包含枚举的包添加到 SessionFactory 配置中。

    @Override
    @Bean
    public SessionFactory getSessionFactory()
    {
        // With domain entity base package(s) which must include enums 
        // that are referenced by @NodeEntity classes.
        return new SessionFactory("package.containing.node.entities", 
                                  "package.containing.enum.classes");
    }