我正在使用 jpa
和 MySQL
在 spring
中开发一个文档管理应用程序。应用程序当前正在接受来自用户 Web 表单 createOrUpdateDocumentForm.jsp
的文档及其元数据到 Controller DocumentController.java
中。但是,数据并未进入 MySQL
数据库。有人可以告诉我如何更改我的代码,以便将文档及其元数据存储在底层数据库中吗?
数据流(包括pdf文档)似乎要经过以下对象:
createOrUpdateDocumentForm.jsp //omitted for brevity, since it is sending data to controller (see below)
Document.java
DocumentController.java
ClinicService.java
JpaDocumentRepository.java
The MySQL database
我将每个对象的相关部分总结如下:
jsp
触发DocumentController.java
中的如下方法:
@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();
byte[] contents;
Blob blob = null;
try {
contents = file.getBytes();
blob = new SerialBlob(contents);
} catch (IOException e) {e.printStackTrace();}
catch (SerialException e) {e.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
document.setContent(blob);
document.setContentType(file.getContentType());
document.setFileName(file.getOriginalFilename());
System.out.println("----------- document.getContentType() is: "+document.getContentType());
System.out.println("----------- document.getCreated() is: "+document.getCreated());
System.out.println("----------- document.getDescription() is: "+document.getDescription());
System.out.println("----------- document.getFileName() is: "+document.getFileName());
System.out.println("----------- document.getId() is: "+document.getId());
System.out.println("----------- document.getName() is: "+document.getName());
System.out.println("----------- document.getPatient() is: "+document.getPatient());
System.out.println("----------- document.getType() is: "+document.getType());
try {System.out.println("[[[[BLOB LENGTH IS: "+document.getContent().length()+"]]]]");}
catch (SQLException e) {e.printStackTrace();}
new DocumentValidator().validate(document, result);
if (result.hasErrors()) {
System.out.println("result.getFieldErrors() is: "+result.getFieldErrors());
return "documents/createOrUpdateDocumentForm";
}
else {
this.clinicService.saveDocument(document);
status.setComplete();
return "redirect:/patients?patientID={patientId}";
}
}
当我通过 jsp
中的 web 表单向 controller
提交文档时,System.out.println()
命令在controller
代码输出以下内容,表明数据实际上正在发送到服务器:
----------- document.getContentType() is: application/pdf
----------- document.getCreated() is: 2013-12-16
----------- document.getDescription() is: paper
----------- document.getFileName() is: apaper.pdf
----------- document.getId() is: null
----------- document.getName() is: apaper
----------- document.getPatient() is: [Patient@564434f7 id = 1, new = false, lastName = 'Frank', firstName = 'George', middleinitial = 'B', sex = 'Male', dateofbirth = 2000-11-28T16:00:00.000-08:00, race = 'caucasian']
----------- document.getType() is: ScannedPatientForms
[[[[BLOB LENGTH IS: 712238]]]] //This indicates the file content was converted to blob
Document.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;
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);}
}
从DocumentController
调用的ClinicService.java
代码是:
private DocumentRepository documentRepository;
private PatientRepository patientRepository;
@Autowired
public ClinicServiceImpl(DocumentRepository documentRepository, PatientRepository patientRepository) {
this.documentRepository = documentRepository;
this.patientRepository = patientRepository;
}
@Override
@Transactional
public void saveDocument(Document doc) throws DataAccessException {documentRepository.save(doc);}
JpaDocumentRepository.java
中的相关代码为:
@PersistenceContext
private EntityManager em;
@Override
public void save(Document document) {
if (document.getId() == null) {this.em.persist(document);}
else {this.em.merge(document);}
}
最后,创建数据库的SQL代码的相关部分包括:
CREATE TABLE IF NOT EXISTS documenttypes (
id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(80),
INDEX(name)
);
CREATE TABLE IF NOT EXISTS patients (
id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(30),
middle_initial VARCHAR(5),
last_name VARCHAR(30),
sex VARCHAR(20),
date_of_birth DATE,
race VARCHAR(30),
INDEX(last_name)
);
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)
);
我对此代码做了哪些更改,以便它使用 将
?document
保存在 MySQL
数据库的 documents
表中jpa
最佳答案
@CodeMed,我花了一段时间,但我能够重现该问题。可能是配置问题:@PersistenceContext
可能会被扫描两次,它可能会被您的根上下文和您的网络上下文扫描。这会导致 @PersistenceContext
要共享,因此它不会保存您的数据(Spring 不允许这样做)。我觉得奇怪的是没有显示任何消息或日志。如果您在 Save(Document document) 上尝试了下面的此代码段,您将看到实际错误:
Session session = this.em.unwrap(Session.class);
session.persist(document);
要解决此问题,您可以执行以下操作(避免 @PersistenceContext
被扫描两次):
1- 确保您的所有 Controller 都在一个单独的包中,例如 com.mycompany.myapp.controller
,并在您的网络上下文中使用组件扫描作为 <context:component-scan annotation-config="true" base-package="com.mycompany.myapp.controller" />
2- 确保其他组件位于 Controller 包之外的不同包中,例如:com.mycompany.myapp.dao
, com.mycompany.myapp.service
……
然后在您的根上下文中使用组件扫描作为
<context:component-scan annotation-config="true" base-package="com.mycompany.myapp.service, com.mycompany.myapp.dao" />
或者给我看你的spring xml配置和你的web.xml,我会给你指出正确的方向
关于java - 文档未保存在 Spring jpa 文档管理器应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20586865/