我想使用 Spring MVC 和 Hibernate 在 PostgresQL 中存储一个实体(一个字符串 + 一个图像)这是我的表。图像应该是oid的类型。
CREATE TABLE document
(
name character varying(200),
id serial NOT NULL,
content oid, // that should be the image
CONSTRAINT document_pkey PRIMARY KEY (id )
)
WITH (
OIDS=FALSE
);
这是我要存储的实体。
@Entity
@Table(name = "document")
public class Document {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name="content")
private Blob content; //this is the image
//getters- setters
你可以看到变量“name”是一个String,而不是Long。仍然当我提交一个值不是数字的表单时它会抛出 org.postgresql.util.PSQLException: Bad value for type long : x
这是表格:
<form:form method="post" action="save.html" commandName="document" enctype="multipart/form-data">
<form:errors path="*" cssClass="error"/>
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="content">Document</form:label></td>
<td><input type="file" name="file" id="file"></input></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Document"/>
</td>
</tr>
</table>
</form:form>
如果我输入一个数值并提交,OK。但是任何非数字值都会触发上述异常……我读到它可能是由于我没有正确使用 OID 但我不知道我应该怎么做才能消除这个异常。其实我也不明白这个词的名字。它说“类型 long 的错误值”。但是谁想要 type long 呢? 变量“name”的类型是 String!!!!
最后,这是控制器
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("document") Document document, @RequestParam("file") MultipartFile file) {
try {
Blob blob = Hibernate.createBlob(file.getInputStream());
document.setContent(blob);
documentDao.save(document);
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/index.html";
}
任何建议都适用。
原文由 Sanyifejű 发布,翻译遵循 CC BY-SA 4.0 许可协议
当我创建表时,“名称”列恰好是第一列。这不好。 Id 必须是第一列。如果我改变列的顺序它工作正常……