long 类型的错误值:- Postgresql、Hibernate、Spring

新手上路,请多包涵

我想使用 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 许可协议

阅读 1.7k
2 个回答

当我创建表时,“名称”列恰好是第一列。这不好。 Id 必须是第一列。如果我改变列的顺序它工作正常……

原文由 Sanyifejű 发布,翻译遵循 CC BY-SA 3.0 许可协议

我有一个类似的问题,但它与数据库中 ID 字段的顺序无关。

经过一番搜索后,我发现 表明 Hibernate 中的 Lob 被视为 OID,除非另有说明。

这意味着 Hibernate 将尝试将 Lob 放入 Long 中,因此会产生该异常 PSQLException: Bad value for type long

指定 Lob 被视为文本的方法是通过注释字段

@Lob
@Type(type = "org.hibernate.type.TextType")

原文由 Tšeliso Molukanele 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题