使用JPA数据绑定的Spring MVC [英] Spring MVC with JPA databinding

查看:108
本文介绍了使用JPA数据绑定的Spring MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是让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)
私人住宅;

@NotNull()
@Past()
@Column(name =birthday)
私人日期生日;

@Column(name =graduation_date)
私人日期graduationDay;


我在属性编辑器中试过以下几行为no avail

  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请求,
@Valid @ModelAttribute(value =child)Child child,
BindingResult结果)
}

这就是我从BindingResult类获得的消息

  09:01:36.006 [http-thread-pool-28081(5)] INFO simple  -  Found fieldError:graduationDay,
无法将java.lang.String类型的属性值转换为属性graduationDay所需的类型java.util.Date;
嵌套异常是org.springframework.core.convert.ConversionFailedException:
无法从类型java.lang.String转换为类型@ javax.persistence.Column java.util.Date for value';
嵌套异常是java.lang.IllegalArgumentException


解决方案

Spring会自动绑定像String和Number这样的简单对象类型,但对于像 java.util.Date 之类的复杂对象或您自己定义的类型,您将需要使用称为 PropertyEditors 转换器,都可以解决您的问题。

Spring已经有一个预定义的 PropertyEditors 转换器 @ NumberFormat @ DateTimeFormat

您可以直接在您的字段中使用它们,如

  public class Child {

@DateTimeFormat (图案=DD / M M / YYYY)
私人日期生日;

@DateTimeFormat(iso = ISO.DATE)
私人日期graduationDay;

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

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


$ / code>

Spring也允许你定义你自己的类型转换器,必须结合使用Spring ConversionService



例如,如果您有一个 Color code> class like this

  public class Color {
private String colorString;

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




$ b你可以定义颜色转换器,例如像

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

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

//等等

返回null;
}
}

要查看更多关于转换器的信息,请查看这个,同时检查这个知道 Converters 之间的区别。 PropertyEditors


My problem is with having Spring bind the data I get from a form to a JPA entity. The wierd part is, it works just fine if I do not look at the BindingResults. The BindingResults says there were binding errors when an empty string is passed in for the field graduation, but I know it does bind them correctly because when I don't check Hibernate updates the database perfectly. Is there a way to not have to write logic to circumnavigate the wrongly fired binding errors?

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

    }

I have tried the following lines in a property editor to no avail

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

Here is the method signature for the controller method Handling the request

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

This is what I get from the BindingResult class as a message

    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 automatically binds simple object types like String and Number, but for complex objects like java.util.Date or your own defined types, you will need to use what is called a PropertyEditors or Converters, both could solve your problem.

Spring already has a predefiend PropertyEditors and Converters like @NumberFormat and @DateTimeFormat

You can use them directly on your fields like this

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 also allows you to define your own type converters which you must use it combined with Spring ConversionService

For example if you have a Color class like this

public class Color {
  private String colorString;

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

You would define the color converter for example like this

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

To check more about converters check this, also check this to know the difference between Converters and PropertyEditors

这篇关于使用JPA数据绑定的Spring MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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