如何使用hibernate从数据库中检索blob值?

时间:2015-09-01 08:26:47

标签: java mysql hibernate hql

我正在开发一个桌面应用程序,我使用Hibernate连接mySql数据库,在该数据库中,表没有主键。所以我得到的pojo类有两个java文件。 pojo类是,

package pojo;
public class Entries implements java.io.Serializable {

    private EntriesId id;

    public Entries() {
    }

    public Entries(EntriesId id) {
        this.id = id;
    }

    public EntriesId getId() {
        return this.id;
    }

    public void setId(EntriesId id) {
        this.id = id;
    }

}

// POJO2

package pojo;

import java.util.Arrays;
import java.util.Date;

public class EntriesId implements java.io.Serializable {

    private String userid;
    private String name;
    private Integer ver;
    private String bexval;
    private String boidval;
    private Integer empid;
    private String fieldname;
    private byte[] fieldvalue;
    private Date lstdatetime;

    public EntriesId() {
    }

    public EntriesId(String userid, String name, Integer ver, String bexval,
            String boidval, Integer empid, String fieldname, byte[] fieldvalue,
            Date lstdatetime) {
        this.userid = userid;
        this.name = name;
        this.ver = ver;
        this.bexval = bexval;
        this.boidval = boidval;
        this.empid = empid;
        this.fieldname = fieldname;
        this.fieldvalue = fieldvalue;
        this.lstdatetime = lstdatetime;
    }}

我将从数据库中检索值

Session session=null;
    Transaction tx=null;
    try{
        session=HibernateUtil.getSessionFactory().openSession();
        tx=session.beginTransaction();
        Query q=session.createQuery("select a.id.fieldvalue,count(a.id.fieldvalue) from Entries as a where a.id.lstdatetime between '2015-08-01' and '2015-08-24' and a.id.fieldname='*NAME' group by a.id.fieldvalue");
        List<Object[]> list=(List<Object[]>) q.list();
        System.out.println("List size :"+list.size());
        for(Object[] obj:list)
        {
            System.out.println(obj[0]);
            System.out.println(obj[1]);

        }
        tx.commit();
        session.close();
    }catch(Exception e)
    {
        System.out.println("Exception found here :"+e);
    }

在检索值时,我会从obj[1]获取值,但在obj[0]中,该对象不是值。我怎样才能获得原始数据?任何人都帮我检索价值。

1 个答案:

答案 0 :(得分:0)

在Hibernate中,fieldvalue列表示为byte[],而检索值i直接打印obj[0],因此我将字节数组作为值。要获取值,需要将obj[0]转换为字符串。

for(Object[] obj:list)
{
    byte ptext[] = (byte[])obj[0];
    String value = new String(ptext);
    System.out.println(obj[1]+" : "+value);
}