2

I am struggling with this problem :

org.hibernate.PropertyAccessException: could not set a field value by reflection setter of fr.mypackage.MyClass.data

Caused by: java.lang.IllegalArgumentException: Can not set [B field fr.mypackage.MyClass.data to java.lang.String

The problem above is about MyClass which is an entity with two attributes :

@Entity
@Table(name = "TG_CLASS")
public class MyClass {

    @Id
    @Column(name = "ID")
    private long id;

    @Lob
    @Type(type = "org.hibernate.type.TextType")
    @Column(name = "DATA")
    private byte[] data;

...

}

It looks pretty simple, the only tricky thing is the column DATA which is a bytea (I am working in PostgreSQL), and that the problem comes from Hibernate struggling with converting bytea to String. How can I resolve this problem ?

Community
  • 1
  • 1
CommonPeople
  • 700
  • 1
  • 6
  • 16

1 Answers1

2

If you're working with BYTEA column and your entity has a byte[], you shouldn't be using org.hibernate.type.TextType. It's for c(haracter)lobs, you're working with bytes not characters.

Additionally there are many ways to convert bytes to characters and vice versa, these are called encodings. I wouldn't trust silent conversions where I don't know which encoding is being used. You could end up with corrupt data without realizing it.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • Indeed, the problem came from org.hibernate.type.TextType. I changed it to org.hibernate.type.BinaryType and it works pretty well now ! Thank you ! – CommonPeople Feb 08 '18 at 09:00
  • Do you need the annotation at all? What type is inferred if you leave it out completely? – Kayaman Feb 08 '18 at 09:14
  • Without any annotation, I have an exception org.postgresql.util.PSQLException: bad value for type long – CommonPeople Feb 08 '18 at 10:12
  • Ah alright, so it's this problem: https://stackoverflow.com/questions/12647755/bad-value-for-type-long-postgresql-hibernate-spring – Kayaman Feb 08 '18 at 10:23
  • Exactly, that's how I came up trying @Type(type = "org.hibernate.type.TextType"), thank you ! – CommonPeople Feb 08 '18 at 10:37