无法转换类型[java.lang.String]的属性值

时间:2016-11-08 19:13:49

标签: java mysql hibernate spring-mvc

我的春季应用程序存在问题,保存日期"到"数据库"。错在哪里?

enter image description here

错误

  

无法将[java.lang.String]类型的属性值转换为   属性为bornDate的必需类型[java.sql.Date];嵌套异常   是java.lang.IllegalArgumentException:无法解析日期:   无法解释的日期:" 2016-11-02"

MySQL的

use lifecalc;
create table Man (
manId int not null auto_increment primary key,
name varchar(30) not null,
bornDate date,
lastDate date
);
insert into man value
(null, "Pawel Cichon", "1920-11-30", "2000-02-20");

实体

@Entity
@Table(name="Man")
public class Man {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="manId")
    private int manId;

    @Column
    private String name;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @Column
    private java.sql.Date bornDate;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @Column
    private java.sql.Date lastDate;
    //getter end setter

控制器

@Controller
@RequestMapping("/")
public class AppController {

    @Autowired
    private ManService manService;

    @ModelAttribute("man")
    public Man modelToAddMan(){
        return new Man();
    }

    @InitBinder
     public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor( dateFormat, true));
    }

    @RequestMapping(value="/addMan.html", method = RequestMethod.POST)
    public String addManFinish(@Valid @ModelAttribute("man") Man man, BindingResult result) {

        if(result.hasErrors()){
            return "addMan";
        } else{
            manService.addMan(man);
            return "redirect:/index.html";
        }
    }

addMan.html

<form:form method="POST" modelAttribute="man">
    <div class="form-group">
        <label for="name" class="col-sm-2 control-label">name</label>
        <form:input path="name" />
        <form:errors path="name" cssClass="error"/>
    </div>

    <div class="form-group">
        <label for="bornDate" class="col-sm-2 control-label">bornDate</label>
        <form:input   path="bornDate"  />
        <form:errors path="bornDate" cssClass="error"/>
    </div>

    <div class="form-group">
        <label for="lastDate" class="col-sm-2 control-label">lastDate</label>
        <form:input  path="lastDate"  />
        <form:errors path="lastDate" cssClass="error"/>
    </div>

    <div class="form-group">
        <input type="submit" class="btn btn-success" value="save" /> <a
            class="btn btn-danger" role="button"
            href="<spring:url value="/index.html" />">cancel </a>
    </div>
</form:form>

1 个答案:

答案 0 :(得分:1)

而不是:

@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column
private java.sql.Date bornDate;

使用java.util.date:

@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column
private java.util.date bornDate;