当前位置: 首页 > 知识库问答 >
问题:

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

越学博
2023-03-14

我的spring应用程序无法将“日期”保存到“数据库”。错误在哪里?

错误

无法将类型为[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";
        }
    }

艾德曼。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个答案

米景辉
2023-03-14

而不是:

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

使用java。util。日期:

@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column
private java.util.date bornDate;
 类似资料: