簡體   English   中英

帶有JPA數據綁定的Spring MVC

[英]Spring MVC with JPA databinding

我的問題是將Spring從表單中獲取的數據綁定到JPA實體。 奇怪的是,如果我不看BindingResults,它的工作正常。 BindingResults說當為字段分度傳入一個空字符串時會出現綁定錯誤,但我知道它確實正確綁定它們,因為當我不檢查Hibernate時,它會完美地更新數據庫。 有沒有辦法不必編寫邏輯來繞過錯誤觸發的綁定錯誤?

    @Entity
    @Table(name="child")
    public class Child {

        @Id
        @Column(name="id")
        private Integer childId;

        @ManyToOne(fetch=FetchType.EAGER )
        @JoinColumn(name="house", referencedColumnName="house")
        private House house;

        @NotNull()
        @Past()
        @Column(name="birthday")
        private Date birthday;

        @Column(name="graduation_date")
        private Date graduationDay;

    }

我在屬性編輯器中嘗試了以下幾行無濟於事

    SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
    registry.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

以下是處理請求的控制器方法的方法簽名

    @Controller
    @SessionAttributes(value="child")
    @RequestMapping(value="child")
    public class ChildModController {

    @RequestMapping(value="save-child.do", params="update", method = RequestMethod.POST)
    public @ResponseBody Map<String,?> updateChild(

        HttpServletRequest request,
        @Valid @ModelAttribute(value="child")Child child,
        BindingResult results)
    }

這是我從BindingResult類中獲取的消息

    09:01:36.006 [http-thread-pool-28081(5)] INFO  simple - Found fieldError: graduationDay, 
    Failed to convert property value of type java.lang.String to required type java.util.Date for property graduationDay; 
    nested exception is org.springframework.core.convert.ConversionFailedException: 
    Failed to convert from type java.lang.String to type @javax.persistence.Column java.util.Date for value '; 
    nested exception is java.lang.IllegalArgumentException

Spring會自動綁定簡單對象類型,如String和Number,但對於像java.util.Date這樣的復雜對象或您自己定義的類型,您需要使用所謂的PropertyEditorsConverters ,兩者都可以解決您的問題。

Spring已經有一個預定義的PropertyEditorsConverters@NumberFormat@DateTimeFormat

您可以直接在您的字段上使用它們

public class Child {

  @DateTimeFormat(pattern="dd/MM/yyyy")
  private Date birthday;

  @DateTimeFormat(iso=ISO.DATE)
  private Date graduationDay;

  @NumberFormat(style = Style.CURRENCY)
  private Integer myNumber1;

  @NumberFormat(pattern = "###,###")
  private Double myNumber2;

}

Spring還允許您定義自己的類型轉換器,您必須將它與Spring ConversionService結合使用

例如,如果您有這樣的Color

public class Color {
  private String colorString;

  public Color(String color){
     this.colorString = color;
  }
}

您可以像這樣定義顏色轉換器

public class StringToColor implements Converter<String, Color> {
  public Color convert(String source) {
    if(source.equal("red") {
       return new Color("red");
    }

    if(source.equal("green") {
       return new Color("green");
    }

    if(source.equal("blue") {
       return new Color("blue");
    }

    // etc

    return null;
  }
}

要查看有關轉換器的更多信息,請檢查此項 ,同時檢查此項以了解ConvertersPropertyEditors之間的區別

暫無
暫無

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

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