【问题标题】:using jpa entity manager to import blob into mysql in spring application在spring应用程序中使用jpa实体管理器将blob导入mysql
【发布时间】:2014-01-01 21:18:16
【问题描述】:

我正在修改 spring petclinic 应用程序以将文档从用户的计算机导入 MySQL。我正在使用 petclinic 应用程序中的 jpa 架构,它在存储库文件中使用 EntityManager 对象。我知道我需要使用以下语法从 EntityManager 公开会话对象,然后创建一个要插入数据库的 blob:

Session session = em.unwrap(Session.class);//em is an EntityManager
Blob blob = (blob)Hibernate.getLobCreator(session).createBlob(document.getFile().getInputStream(), document.getFile().getSize());

按照petclinic jpa架构,我使用了五个java文件:

View/JSP: CreateOrUpdateDocument.jsp
Model: Document.java
Controller: DocumentController.java
Repository: JpaDocumentRepository.java
Service: ClinicServiceImpl.java  

我的问题是把它放在哪里以及如何设置它。现在,我的代码抛出了以下异常,我认为这与 Document.java 的文件属性没有给出任何注释有关:

org.hibernate.MappingException: Could not determine type for:  
org.springframework.web.multipart.MultipartFile, at table:  
documents, for columns: [org.hibernate.mapping.Column(file)

我将在下面包含每个文件的相关部分、堆栈跟踪和文档表的 sql 定义。为了使文档成功地从用户的计算机进入服务器上 MySQL 数据库的文档表,我需要进行哪些更改?

CreateOrUpdateDocument.jsp:

<html lang="en">
<jsp:include page="../fragments/headTag.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}" enctype="multipart/form-data"
               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="file" id="file"></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>
</html>

文档.java:

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

    private MultipartFile file;

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

    public MultipartFile getFile(){return file;}
    public void setFile(MultipartFile f){file=f;}

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

这里是 DocumentController.java。注意 processCreationForm() 方法处理来自 jsp 的表单:

@Controller
@SessionAttributes("document")
public class DocumentController {
    private final ClinicService clinicService;

    @Autowired
    public DocumentController(ClinicService clinicService) {this.clinicService = clinicService;}

    @ModelAttribute("types")
    public Collection<DocumentType> populateDocumentTypes() {return this.clinicService.findDocumentTypes();}

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {dataBinder.setDisallowedFields("id");}

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

    //THIS IS THE METHOD THAT HANDLES THE FORM
    @RequestMapping(value = "/patients/{patientId}/documents/new", headers = "content-type=multipart/*", method = RequestMethod.POST)
    public String processCreationForm(@ModelAttribute("document") Document document, BindingResult result, SessionStatus status, @RequestParam("file") final MultipartFile file) {
        document.setCreated();
        document.setFile(file);
        new DocumentValidator().validate(document, result);
        if (result.hasErrors()) {return "documents/createOrUpdateDocumentForm";}
        else {
            this.clinicService.saveDocument(document);
            status.setComplete();
            return "redirect:/patients?patientID={patientId}";
        }
    }

    @RequestMapping(value = "/patients/*/documents/{documentId}/edit", method = RequestMethod.GET)
    public String initUpdateForm(@PathVariable("documentId") int documentId, Map<String, Object> model) {
        Document document = this.clinicService.findDocumentById(documentId);
        model.put("document", document);
        return "documents/createOrUpdateDocumentForm";
    }

    @RequestMapping(value = "/patients/{patientId}/documents/{documentId}/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public String processUpdateForm(@ModelAttribute("document") Document document, BindingResult result, SessionStatus status) {
        new DocumentValidator().validate(document, result);
        if (result.hasErrors()) {return "documents/createOrUpdateDocumentForm";}
        else {
            this.clinicService.saveDocument(document);
            status.setComplete();
            return "redirect:/patients/{patientId}";
        }
    }
}

JpaDocumentRepository.java。注意 save() 方法应该处理 blob 文档:

@Repository
public class JpaDocumentRepositoryImpl implements DocumentRepository {
    @PersistenceContext
    private EntityManager em;

    @Override
    @SuppressWarnings("unchecked")
    public List<DocumentType> findDocumentTypes() {
        return this.em.createQuery("SELECT dtype FROM DocumentType dtype ORDER BY dtype.name").getResultList();
    }

    @Override
    public Document findById(int id) {return this.em.find(Document.class, id);}

    @Override
    public void save(Document document) {
        try {
            Session session = em.unwrap(Session.class);
            Blob blob = (Blob) Hibernate.getLobCreator(session).createBlob(document.getFile().getInputStream(), document.getFile().getSize());
            document.setFileName(document.getFile().getOriginalFilename());
            document.setContent(blob);
            document.setContentType(document.getFile().getContentType());
        } catch (IOException e) {e.printStackTrace();}      
        if (document.getId() == null) {this.em.persist(document);}
        else {this.em.merge(document);}
    }

    @Override
    public List<Document> list() throws DataAccessException {
       return this.em.createQuery("SELECT doc FROM Document doc ORDER BY doc.name").getResultList();
    }

    @Override
    public void remove(Integer id) throws DataAccessException {
        Document thisdoc = em.find(Document.class, id);
        em.remove(thisdoc);
    }

}

ClinicServiceImpl.java:

@Service
public class ClinicServiceImpl implements ClinicService {
    private DocumentRepository documentRepository;
    private PatientRepository patientRepository;

    @Autowired
    public ClinicServiceImpl(DocumentRepository documentRepository, PatientRepository patientRepository) {
        this.documentRepository = documentRepository;
        this.patientRepository = patientRepository;
    }

    //Other methods

    @Override
    @Transactional
    public void saveDocument(Document doc) throws DataAccessException {documentRepository.save(doc);}
}

这是堆栈跟踪:

ERROR ContextLoader - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in class path resource [spring/business-config.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring/business-config.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: petclinic] Unable to build EntityManagerFactory  

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:741) ~[spring-context-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) ~[spring-context-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389) ~[spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294) ~[spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939) [catalina.jar:7.0.42]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434) [catalina.jar:7.0.42]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:7.0.42]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) [catalina.jar:7.0.42]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) [catalina.jar:7.0.42]
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) [na:1.6.0_29]
    at java.util.concurrent.FutureTask.run(FutureTask.java:138) [na:1.6.0_29]
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [na:1.6.0_29]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [na:1.6.0_29]
    at java.lang.Thread.run(Thread.java:662) [na:1.6.0_29]  

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring/business-config.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: petclinic] Unable to build EntityManagerFactory  

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:438) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:277) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:79) ~[spring-tx-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:71) ~[spring-tx-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:85) ~[spring-tx-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1532) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1500) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    ... 20 common frames omitted  

Caused by: javax.persistence.PersistenceException: [PersistenceUnit: petclinic] Unable to build EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:923) ~[hibernate-entitymanager-4.2.1.Final.jar:4.2.1.Final]
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:898) ~[hibernate-entitymanager-4.2.1.Final.jar:4.2.1.Final]
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:76) ~[hibernate-entitymanager-4.2.1.Final.jar:4.2.1.Final]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:288) ~[spring-orm-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310) ~[spring-orm-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509) ~[spring-beans-3.2.5.RELEASE.jar:3.2.5.RELEASE]
    ... 35 common frames omitted  
Caused by: org.hibernate.MappingException: Could not determine type for: org.springframework.web.multipart.MultipartFile, at table: documents, for columns: [org.hibernate.mapping.Column(file)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:314) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:292) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
    at org.hibernate.mapping.Property.isValid(Property.java:239) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:469) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
    at org.hibernate.mapping.RootClass.validate(RootClass.java:270) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
    at org.hibernate.cfg.Configuration.validate(Configuration.java:1296) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1752) ~[hibernate-core-4.2.1.Final.jar:4.2.1.Final]
    at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96) ~[hibernate-entitymanager-4.2.1.Final.jar:4.2.1.Final]
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:913) ~[hibernate-entitymanager-4.2.1.Final.jar:4.2.1.Final]
    ... 41 common frames omitted  
Dec 13, 2013 8:38:54 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in class path resource [spring/business-config.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring/business-config.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: petclinic] Unable to build EntityManagerFactory  

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:741)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring/business-config.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: petclinic] Unable to build EntityManagerFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:438)
    at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:277)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:139)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:79)
    at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:71)
    at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:85)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1532)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1500)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    ... 20 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: petclinic] Unable to build EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:923)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:898)
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:76)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:288)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
    ... 35 more
Caused by: org.hibernate.MappingException: Could not determine type for: org.springframework.web.multipart.MultipartFile, at table: documents, for columns: [org.hibernate.mapping.Column(file)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:314)
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:292)
    at org.hibernate.mapping.Property.isValid(Property.java:239)
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:469)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
    at org.hibernate.cfg.Configuration.validate(Configuration.java:1296)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1752)
    at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:913)
    ... more  

在数据库中创建文档表的 SQL。与 Document.java 中的注解比较:

CREATE TABLE IF NOT EXISTS documents (
  id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  client_id int(4) UNSIGNED NOT NULL,
  type_id INT(4) UNSIGNED, 
  name varchar(200) NOT NULL,
  description text NOT NULL,
  filename varchar(200) NOT NULL,
  content mediumblob NOT NULL, 
  content_type varchar(255) NOT NULL,
  created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (client_id) REFERENCES patients(id),
  FOREIGN KEY (type_id) REFERENCES documenttypes(id)
);

编辑:

当我将@Transient 放在 MultipartFile 文件属性声明的前面时,我得到了可以下载的堆栈跟踪at this file sharing link。

可以读取堆栈跟踪中引用的 business-config.xml at this file sharing site。

【问题讨论】:

  • 您当前是否在调用 JpaDocumentRepositoryImpl.save() 方法时遇到错误?如果是这样,您能否包括堆栈跟踪。
  • @drembert 它不会编译,因为JpaDocumentRepositoryImpl.save() 中的file 实例没有被填充。请参阅代码中的注释。 file 来自DocumentController.java,一个问题是我不知道如何将它放入JpaDocumentRepositoryImpl.save()。你有什么具体的建议可以吗?我现在在线,可以尝试并报告。
  • @drembert 我通过向 Document.java 类添加一个名为 file 的 MultipartFile 类型的属性,然后在 DocumentController.java 中设置它并在 JpaDocumentRespositoryImpl.java 中检索它来消除 eclipse 错误。但是当我尝试启动应用程序时,它给了我一个与 PersistenceExceptionTranslationPostProcessor 相关的错误。我现在将在编辑中添加代码。这会给你带来什么新想法吗?
  • 我不确定该特定异常指的是什么错误。我可以在今晚或明天早上看看某个时间点,如果我能弄清楚,请告诉你
  • @drembert 谢谢。我刚刚发布了更多代码和堆栈跟踪来帮助您弄清楚。我认为问题在于我添加到 Document.java 的 MultipartFile 文件属性缺少注释。但我想还有其他问题,我会很感激你的帮助。

标签: java spring jsp spring-mvc jpa


【解决方案1】:

注释

@Transient
private MultipartFile file;

更新

来自您的堆栈跟踪:

 Caused by: org.hibernate.MappingException: Could not determine type for: org.springframework.web.multipart.MultipartFile, at table: documents, for columns: [org.hibernate.mapping.Column(file)]

错误是明确的,JPA 不知道如何将MultipartFile 映射为列。

使用@Transient,我们说根本不映射。

所以删除您的数据库并重新创建它,清理并重新编译您的代码,因为此错误表明您的代码尚未使用@Transient 编译。

并确保@Transient 是@javax.persistence.Transient

【讨论】:

    【解决方案2】:

    当您使用@Entity 注释一个类时,默认情况下该类中的所有字段都会在您持久化实体时插入到数据库中。

    除非您在每个字段上提供注释,否则持久性提供程序将采用“默认”方法来使字段持久化(默认值究竟是什么可能由 JPA 规范指导,我不确定)。对于类型为原始类型的字段或其他易于映射的字段类型(如字符串和枚举),这不是问题。

    如果字段的类型是对象或不容易映射,则会遇到问题。本质上,您的持久性提供者不知道您希望如何将字段存储到数据库中,并且无法采取合理的默认操作。最好的办法是抛出一个异常告诉你,让你更具体地知道你想如何在数据库中存储数据。

    这就是您的 MultipartFile 字段正在发生的事情。 Hibernate 不知道你想如何将它持久化到数据库中。

    要解决这个问题,您有几个选择:

    1:您可以使用@Transient 注释明确告诉您的持久性提供程序忽略某些字段。在您的情况下,您可以将其添加到您的 Document 实体中的 file 字段中。但要清楚,当您从数据库加载 Document 实体时,file 字段将始终为空。您需要确保您的业务逻辑与此一致。

    2:在file 字段上使用@Lob 注释。这将依赖 Java 的内置序列化将 MulitpartFile 存储在您的数据库中

    3:提供一个Hibernate User Type,它本质上指示Hibernate 应该如何尝试持久化MultipartFile 类型的任何字段

    哪一个适合您完全取决于您的应用程序的要求。

    【讨论】:

    • +1 谢谢。当我在 Document.java 中的 MultipartFile 文件声明前面添加 at_Transient 时,我得到一个引用 business-config.xml 的堆栈跟踪。在我上面的原始帖子末尾的编辑中,我已将堆栈跟踪和 business-config.xml 包含在指向文件共享站点的链接中。您能否查看它们并告诉我如何解决错误以便应用程序编译?
    猜你喜欢
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    相关资源
    最近更新 更多