在spring mvc hibernate应用程序中将错误从字符串转换为blob

时间:2013-12-11 00:56:50

标签: java spring hibernate jsp spring-mvc

在使用hibernate和jpa的spring mvc应用程序中,我有一个表单需要存储一个文档,其中包含有关文档的元数据,例如提交表单时的当前日期。我已经设置了模型,控制器和jsp,但是当它运行时,当用户单击按钮将文档提交到数据库时,将返回create或add jsp。该错误表明问题是代码没有处理从String到Blob的转换。我已经注意到processCreationForm()方法中的位置在createOrUpdateDocumentForm.jsp返回<body> <script> $(function () { $("#created").datepicker({ dateFormat: 'yy/mm/dd'}); }); </script> <div class="container"> <jsp:include page="../fragments/bodyHeader.jsp"/> <c:choose> <c:when test="${document['new']}"> <c:set var="method" value="post"/> </c:when> <c:otherwise> <c:set var="method" value="put"/> </c:otherwise> </c:choose> <h2> <c:if test="${document['new']}">New </c:if> Document </h2> <form:form modelAttribute="document" method="${method}" class="form-horizontal"> <div class="control-group" id="patient"> <label class="control-label">Patient </label> <c:out value="${document.patient.firstName} ${document.patient.lastName}"/> </div> <petclinic:inputField label="Name" name="name"/> <petclinic:inputField label="Description" name="description"/> <div class="control-group"> <petclinic:selectField name="type" label="Type " names="${types}" size="5"/> </div> <td><input type="file" name="content" id="content"></input></td> <div class="form-actions"> <c:choose> <c:when test="${document['new']}"> <button type="submit">Add Document</button> </c:when> <c:otherwise> <button type="submit">Update Document</button> </c:otherwise> </c:choose> </div> </form:form> <c:if test="${!document['new']}"> </c:if> <jsp:include page="../fragments/footer.jsp"/> </div> </body> 重定向列表JSP并且我已经包含了此帖子底部的错误消息。

如何更改下面的代码,以便在用户点击提交按钮时将文档保存到数据库?

这是我的createOrUpdateDocumentForm.jsp:

@RequestMapping(value = "/patients/{patientId}/documents/new", method = RequestMethod.GET)
public String initCreationForm(@PathVariable("patientId") int patientId, Map<String, Object> model) {
    Patient patient = this.clinicService.findPatientById(patientId);
    Document document = new Document();
    patient.addDocument(document);
    model.put("document", document);
    return "documents/createOrUpdateDocumentForm";
}

@RequestMapping(value = "/patients/{patientId}/documents/new", method = RequestMethod.POST)
public String processCreationForm(@ModelAttribute("document") Document document, BindingResult result, SessionStatus status) {
    document.setCreated();
    //THE FOLLOWING LINE PRINTS OUT A VALID DATE FOR document.getCreated()
    System.out.println("document.getCreated() is: "+document.getCreated());
    new DocumentValidator().validate(document, result);
    if (result.hasErrors()) {
        System.out.println("result.getFieldErrors() is: "+result.getFieldErrors());
        //THIS IS BEING RETURNED BECAUSE result.getFieldErrors() RETURNS WHAT IS BEING  
        //SHOWN AT THE BOTTOM OF THIS POSTING, BELOW  
        return "documents/createOrUpdateDocumentForm";
    }
    else {
        this.clinicService.saveDocument(document);
        status.setComplete();
        return "redirect:/patients?patientID={patientId}";
    }
}

以下是控制器的相关部分:

@Entity
@Table(name = "documents")
public class Document {
    @Id
    @GeneratedValue
    @Column(name="id")
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "client_id")
    private Patient patient;

    @ManyToOne
    @JoinColumn(name = "type_id")
    private DocumentType type;

    @Column(name="name")
    private String name;

    @Column(name="description")
    private String description;

    @Column(name="filename")
    private String filename;

    @Column(name="content")
    @Lob
    private Blob content;

    @Column(name="content_type")
    private String contentType;

    @Column(name = "created")
    private Date created;

    public Integer getId(){return id;}
    public void setId(Integer i){id=i;}

    protected void setPatient(Patient patient) {this.patient = patient;}
    public Patient getPatient(){return this.patient;}

    public void setType(DocumentType type) {this.type = type;}
    public DocumentType getType() {return this.type;}

    public String getName(){return name;}
    public void setName(String nm){name=nm;}

    public String getDescription(){return description;}
    public void setDescription(String desc){description=desc;}

    public String getFileName(){return filename;}
    public void setFileName(String fn){filename=fn;}

    public Blob getContent(){return content;}
    public void setContent(Blob ct){content=ct;}

    public String getContentType(){return contentType;}
    public void setContentType(String ctype){contentType=ctype;}

    public void setCreated(){created=new java.sql.Date(System.currentTimeMillis());}
    public Date getCreated() {return this.created;}

    @Override
    public String toString() {return this.getName();}
    public boolean isNew() {return (this.id == null);}

}

这是模型,它是Document.java的一部分:

[
Field error in object 'document' on field 'content': 
rejected value [mydocname.txt]; 
codes [typeMismatch.document.content,typeMismatch.content,typeMismatch.java.sql.Blob,typeMismatch]; 
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: 
codes [document.content,content]; 
arguments []; default message [content]]; 
default message 
[
Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Blob' for property 'content'; 
nested exception is java.lang.IllegalStateException: 
Cannot convert value of type [java.lang.String] to required type [java.sql.Blob] for property 'content': 
no matching editors or conversion strategy found
]
]

上面的代码编译,但是当用户在输入上传文档的信息后按下提交按钮时,将返回相同的添加或更新表单,而不是重定向到摘要页面。这从上面的控制器方法指示result.haserrors为true,即使system.out.println检查的错误都不为真。 eclipse控制台没有显示错误。但是result.getFieldErrors()打印出以下内容:

{{1}}

1 个答案:

答案 0 :(得分:2)

首先,您的表单缺少标记enctype="multipart/form- data", 如果它仍然无法正常工作,您可以考虑使用MultipartFile界面

<强>更新

你可以阅读spring documentation,这非常简单。 现在,要在您的情况下应用它,您可以按照本教程:Saving/Retreving BLOB object in Spring 3 MVC and Hibernate