使用jpa从postgres读取byte []时,其长度几乎增加了一倍 [英] Getting nearly double the length when reading byte[] from postgres with jpa

查看:152
本文介绍了使用jpa从postgres读取byte []时,其长度几乎增加了一倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Image类,该类具有一个byte []来包含实际的图像数据.我可以在我的Web应用程序中上传并插入图像.当我尝试从JPA读取图像后显示图像时,我的byte []的长度始终为2x-1或2x-2,其中x是postgres 9中bytea字段的长度.显然,浏览器不会显示图片已损坏.我可以使用一些帮助来弄清楚为什么我得到的期望值是我预期值的两倍.这是我的图像类的映射.结合使用eclipselink和JPA 2,使其在Mac上达到Postgres 9的要求.

I have an Image class that has a byte[] to contain the actual image data. I'm able to upload and insert the image just fine in my webapp. When I attempt to display the image after reading it from JPA the length of my byte[] is always either 2x-1 or 2x-2, where x is the length of the bytea field in postgres 9. Obviously the browser won't display the image saying it's corrupted. I could use some help figuring out why I'm getting (about) twice what I expect. Here's the mapping of my image class. Using eclipselink with JPA 2 hitting postgres 9 on a mac.

当我使用

select *, length(bytes) from image;

我的长度为9765.在控制器的一个断点中,byte []的长度为19529,比数据库的两倍少一个字节.

I get a length of 9765. In a breakpoint in my controller the byte[] length is 19529 which is one byte shy of twice what's in the database.

@Entity
@Table( name = "image" )
@SequenceGenerator( name = "IMAGE_SEQ_GEN", sequenceName = "IMAGE_SEQUENCE" )
public class Image
        extends DataObjectAbstract<Long>
{
    @Id
    @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "IMAGE_SEQ_GEN" )
    private Long key;

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

    @Lob
    @Basic( optional=false )
    @Column( name="bytes" )
    private byte[] bytes;

    // constructor and getters and setters

}

pgadmin向我显示了图像表的以下内容

pgadmin shows me the following for the image table

CREATE TABLE image
(
  "key" bigint NOT NULL,
  bytes bytea,
  content_type character varying(255),
  "version" integer,
  CONSTRAINT image_pkey PRIMARY KEY (key)
)
WITH (
  OIDS=FALSE
);

推荐答案

在PostgreSQL中,使用16进制编码将9字节[]发送给客户端.

In PostgreSQL 9 byte[] is sent to client using hex encoding.

如果这是错误的原因,则必须查找JPA的更新. 或者,您可以更改数据库服务器的配置,但以前的版本更好.

If this is reason for error you have to find update for JPA. Or you may change config of DB server but previous is better.

这篇关于使用jpa从postgres读取byte []时,其长度几乎增加了一倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆