Getting almost double length when reading bytes [] from postgres with jpa

I have an Image class that has a byte [] to contain the actual image data. I can upload and paste the image just fine in my webapp. When I try to display an image after reading it from JPA, the length of my byte [] is always 2x-1 or 2x-2, where x is the length of the bytea field in postgres 9. Obviously, the image that it ruined will not be displayed by the browser. I could use some help figuring out why I get what I expect twice. Here is a mapping of my image class. Using eclipselink with JPA 2 hitting postgres 9 on mac.

When I select from a database with

select *, length(bytes) from image;

I get a length of 9765. At the breakpoint in my controller, the byte length [] is 19529, which is one byte, which is half the size of 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 shows me the following for an 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
);
+3
source share
5 answers

In PostgreSQL 9, bytes [] are sent to the client using hexadecimal encoding.

If this is the cause of the error, you need to find an update for JPA. Or you can change the database server configuration, but the previous one is better.

+3
source

"bytea_output = escape" is just a workaround, Postgres 8.0 changed the bytea encoding to hex.

Use the current JDBC driver with 9.0-dev800 (9.0 Build 801 is currently being updated) and the problem will be resolved.

+4
source

GlassFish 3.x ( )

, JDBC PostgreSQL. , DataSource - (, EJB) :

System.out.println(ds.getConnection().getMetaData().getDriverVersion());

8.3, , 9.1.

, :

System.out.println(Class.forName("org.postgresql.Driver").getProtectionDomain().getCodeSource().getLocation());

, lib GlassFish. , - GlassFish, , , , .

+2
source

Try looking at the data you receive. This may give you an idea of ​​what is going on.

0
source

Check if you have an old postgresql jar. I ran into the same problem and found both 8.3 postgresql jar and 9.1 postgresql jar in my lib. After uninstalling 8.3 postgresql, byte [] works fine.

0
source

All Articles