带有JPA数据绑定的Spring MVC

Mif*_*tis 3 java spring hibernate jpa

我的问题是将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;

    }
Run Code Online (Sandbox Code Playgroud)

我在属性编辑器中尝试了以下几行无济于事

    SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
    registry.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
Run Code Online (Sandbox Code Playgroud)

以下是处理请求的控制器方法的方法签名

    @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)
    }
Run Code Online (Sandbox Code Playgroud)

这是我从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
Run Code Online (Sandbox Code Playgroud)

fuj*_*ujy 7

Spring会自动绑定简单的对象类型,如String和Number,但是对于复杂对象java.util.Date或者您自己定义的类型,您需要使用所谓的a PropertyEditors或者Converters两者都可以解决您的问题.

Spring已经有一个prefiend PropertyEditors,Converters就像@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;

}
Run Code Online (Sandbox Code Playgroud)

Spring还允许您定义自己的类型转换器,您必须将它与Spring结合使用 ConversionService

例如,如果你有这样的Color

public class Color {
  private String colorString;

  public Color(String color){
     this.colorString = color;
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以像这样定义颜色转换器

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

要查看更多关于转换器检查这个,还要检查知道的区别ConvertersPropertyEditors