簡體   English   中英

彈簧數據休息場轉換器

[英]Spring Data Rest Field converter

我很難在spring數據REST項目(控制器免費應用程序和嚴格的java配置)上使用我的自定義轉換器

我有兩個實體,一個員工和一個州。 這種關系是@ManyToOne,我相信大家都知道。 無論如何,問題是轉換state的字段(字段名為狀態) StringState目標和setState()Employee類持久化到數據庫。

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對象。

@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

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

    @Autowired
    StateRepository repository;

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

}

提交時,我收到此錯誤:

由以下原因引起:org.springframework.core.convert.ConversionFailedException:無法從類型java.net.URI轉換為輸入值為'AB'的com.hr.domain.State;

任何形式的幫助將不勝感激。

願力量與你同在。

這是錯誤跟蹤

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。 你應該改為:

  • 使用其所有默認轉換器注冊spring的默認轉換服務
  • 將轉換器添加到此

您的轉換服務初始化可能如下所示:

private @Autowired StringToStateTypeConverter stringToStateTypeConverter;

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

編輯

由於錯誤來自從URIState的轉換問題,您可以嘗試將URI轉換為State(假設您的存儲庫有一個方法findByName以按name查找State

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

轉換服務初始化將變為:

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-rest使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM