弹簧数据休息场转换器 [英] Spring Data Rest Field converter

查看:75
本文介绍了弹簧数据休息场转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难在 spring数据REST项目(控制器免费应用程序和严格的java配置)上使用我的自定义转换器。

我有两个实体,一个员工和一个州。这种关系是@ManyToOne,我相信大家都知道。无论如何,问题是将 state 字段(字段名称是状态)从 String 转换为状态对象和 setState() Employee 类中,用于数据库的持久性。

I have two Entities, an Employee and a State. The relationship is @ManyToOne, I am sure we all know that. Anyway, the problem is converting the state field (field name is state) from String to a State object and setState() in the Employee class for persistence to a database.

package com.hr.domain;

@Entity
public class Employee implements Serializable {

   private static final long serialVersionUID = 1L;

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Column(name = "state_id", nullable = true)
   private Long id;
   private String firstname;
   private State state;

   @StateConverter
   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "employee_state_id_fk", nullable = false, insertable = true, updatable = true)
   private State state;

   //GETTERS AND SETTERS
   public String getFirstname() {
      return firstname();
   }

   public void setFirstname(String firstname) {
      this.firstname = firstname;
   }

   public String getState() {
    return state();
   }

   public void setState(State state) {
     this.state = state;
   }

   //HASHCODES AND EQUALS

}


package com.hr.domain;

@Entity
public class State implements Serializable {

   private static final long serialVersionUID = 1L;

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Column(name = "state_id", nullable = true)
   private Long id;
   private String state_name;

   //GETTERS AND SETTERS

  //TO STRING
  @Override
  public String toString() {
    return "State [id=" + id + ", state_name=" + state_name + "]";
  }       

}

我已经注册了我的转换器转换服务,但仍然无法将String转换为表单提交上的State对象。

I have registered my converter with the conversion service but still cant get the String to be converter to State object on form submit.

@Bean//(name="conversionService")
public ConversionService getConversionService() {       
    ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
    bean.setConverters(getConverters());
    bean.afterPropertiesSet();
    ConversionService object = bean.getObject();
    System.out.println(object);
    return object;
}

private Set<Converter> getConverters() {    
    Set<Converter> converters = new HashSet<Converter>();
    converters.add(new StringToStateTypeConverter());
    return converters;      
}

这是我的StateConverter

This is my StateConverter

@Component
@StateConverter
public class StringToStateTypeConverter implements Converter<String, State> {

    @Autowired
    StateRepository repository;

    public State convert(String source) {
        return repository.findOne(new Long(source));
    }

}

提交时,我收到此错误:

On submission, I get this error:


引起:org.springframework.core.convert.ConversionFailedException:无法从类型java.net.URI转换为com类型。 hr.domain.State表示值'AB';

Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.net.URI to type com.hr.domain.State for value 'AB';

任何形式的帮助都将受到赞赏。

Any form of help will be appreciated.

力量可以跟你一起
问候。

May the force be with you Regards.

这是错误跟踪

17:21:29,975 ERROR [org.springframework.data.rest.webmvc.AbstractRepositoryRestController] (default task-13) Could not read JSON: Failed to convert from type java.net.URI to type com.hr.domain.State for value 'AB'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI AB. Is it local or remote? Only local URIs are resolvable. (through reference chain: com.hr.domain.Employee["State"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to convert from type java.net.URI to type com.hr.domain.State for value 'AB'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI AB. Is it local or remote? Only local URIs are resolvable. (through reference chain: com.hr.domain.Employee["State"]): org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Failed to convert from type java.net.URI to type com.hr.domain.State for value 'AB'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI AB. Is it local or remote? Only local URIs are resolvable. (through reference chain: com.hr.domain.Employee["State"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to convert from type java.net.URI to type com.hr.domain.State for value 'AB'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI AB. Is it local or remote? Only local URIs are resolvable. (through reference chain: com.hr.domain.Employee["State"])
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:228) [spring-web-4.0.5.RELEASE.jar:4.0.5.RELEASE]

...........
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Failed to convert from type java.net.URI to type com.hr.domain.State for value 'AB'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI AB. Is it local or remote? Only local URIs are resolvable. (through reference chain: com.hr.domain.Employee["State"])
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232) [jackson-databind-2.3.3.jar:2.3.3]
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197) [jackson-databind-2.3.3.jar:2.3.3]

Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.net.URI to type com.hr.domain.State for value 'AB'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI AB. Is it local or remote? Only local URIs are resolvable.
    at org.springframework.data.rest.core.UriToEntityConverter.convert(UriToEntityConverter.java:106) [spring-data-rest-core-2.1.0.RELEASE.jar:]
    at org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$UriStringDeserializer.deserialize(PersistentEntityJackson2Module.java:359) [spring-data-rest-webmvc-2.1.0.RELEASE.jar:]

Caused by: java.lang.IllegalArgumentException: Cannot resolve URI AB. Is it local or remote? Only local URIs are resolvable.
    ... 94 more


推荐答案

你是注册新的 ConversionService 。它取代了弹簧在默认情况下注册的默认值,通常假定存在许多转换器。并且您创建了一个新的转换器,而不是使用您配置的bean。你应该改为:

You a registering a new ConversionService. It replaces the default one that spring registers by default with a lot of converters that are generally assumed to be present. And you create a new converter instead of using your configured bean. You should instead :


  • 注册spring的默认转换服务及其所有默认转换器

  • add转换为这个

您的转换服务初始化可能如下所示:

Your conversion service initialization could look like :

private @Autowired StringToStateTypeConverter stringToStateTypeConverter;

@Bean//(name="conversionService")
public ConversionService getConversionService() {       
    ConversionServiceFactoryBean bean = new DefaultFormattingConversionService();
    bean.addConverter(String.class, State.class, stringToStateTypeConverter);
    return bean;
}

编辑

由于错误来自从 URI 转换为 State 的问题,您可以尝试从URI添加转换器状态(假设您的存储库有一个 findByName 方法,以名称 c> c>来查找 code>:

As the error come from a problem of conversion from URI to State, you could try to add a converter from URI to State (assuming your repository has a method findByName to find a State by its name:

@Component
@StateConverter
public class URIToStateTypeConverter implements Converter<URI, State> {
    @Autowired
    StateRepository repository;

    public State convert(URI uri) {
        String source = uri.toString();
        try {
            long id = Long.valueOf(source);
            return repository.findOne(id);
        } catch (NumberFormatException e) { // should be a name ??
            return repository.findByName(source);
        }
    }
}

转换服务初始化将变为:

And the conversion service initialization would become :

private @Autowired StringToStateTypeConverter stringToStateTypeConverter;
private @Autowired URIToStateTypeConverter uriToStateTypeConverter;

@Bean//(name="conversionService")
public ConversionService getConversionService() {       
    ConversionServiceFactoryBean bean = new DefaultFormattingConversionService();
    bean.addConverter(String.class, State.class, stringToStateTypeConverter);
    bean.addConverter(URI.class, State.class, uriToStateTypeConverter);
    return bean;
}

但我不确定它是否会被spring-data使用 - 休息

But I'm not sure if it will be used by spring-data-rest

这篇关于弹簧数据休息场转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆