2

I want to read from database a pdf, which stores as BLOB and I want to get List<bytes[]>

session.beginTransaction();
final Criteria criteria = session.createCriteria(MyClass.class);
criteria.add(Restrictions.eq("id",id));
final ProjectionList projectionList = Projections.projectionList().add(
        Projections.property("bdoc"));
criteria.setProjection(projectionList);
List<Object[]> list = criteria.list();
List<byte[]> listBytes = new ArrayList<byte[]>();
for (Object[] item : list) {
    listBytes.add((byte[]) item[0]);
}
session.getTransaction().commit();

But I get an error in this line for (Object[] item : list) {

[ERROR] [B cannot be cast to [Ljava.lang.Object;

I've debugged and I do read data from database: my List<Object[]> list = criteria.list() is not empty. But I can not convert from List<Object[]> to List<bytes[]>. What am I doing wrong? Help me please to resolve my problem.

olgacosta
  • 1,008
  • 4
  • 14
  • 32

2 Answers2

3

B cannot be cast to [Ljava.lang.Object;

Means you are indeed getting bytearray and you are trying to convert it into Object array.

SMA
  • 35,277
  • 7
  • 46
  • 71
0

This problem is caused because Criteria.list() returns a raw List. As a result, you are able to write code that causes a ClassCastException. With a properly typed list, the compiler would prevent this.

As explained in the other answer, the text [B cannot be cast to [Ljava.lang.Object means that a byte[] is being cast to an Object[], which is not allowed.

This means that your list contains byte[] objects and you should declare it as such:

List<byte[]> list = criteria.list();

In addition, the contents of your for-loop now look incorrect:

listBytes.add((byte[]) item[0]);

Since item is now a byte[], it's not correct to cast a byte to a byte[]. Perhaps you need to remove the array index [0].

Duncan Jones
  • 63,838
  • 26
  • 184
  • 242