PS Kumar
PS Kumar

Reputation: 2446

Retrieve the value from database using hql?

I have a database,i want to retrieve value from table whose id match with some id. My sample code is `

        public String getName() {SessionFactory sessionfactory=new Configuration().configure().buildSessionFactory();
        Session session=sessionfactory.openSession();
        session.beginTransaction();
        Query qry=session.createQuery("select personaldetails.fname,personaldetails.lname from Personaldetails as personaldetails where refId=1001");
        List l=(List)qry.list();
        session.getTransaction().commit();
        session.close();
        for(int i=0;i<l.size();i++)
        {
            s=s+l.get(i).toString();
        }

        name=s;
        return name;
    }`

if i run this program it returns

[Ljava.lang.Object;@4b26fc[Ljava.lang.Object;@107ac1d[Ljava.lang.Object;@112d16

has output. But my database table contains 'David' 'billa'

Upvotes: 2

Views: 323

Answers (2)

Serhii Shevchyk
Serhii Shevchyk

Reputation: 39456

By default toString() method of Object gets invoked.

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

That's why you get [Ljava.lang.Object;@4b26fc[Ljava.lang.Object;@107ac1d[Ljava.lang.Object;@112d16

You need to overwrite toString() method in Personaldetails entity in order to see David' & 'billa'. Should look like this:

@Override
public void String toString(){
    return this.firstName + " " + this.lastName;  
}

And you have to cast collection to appropriate list of entities

List<EntityType> list=(List<EntityType>)qry.list();

EntityType is a type of your entity.

Upvotes: 1

Joe Taras
Joe Taras

Reputation: 15399

IMHO, I define, in your case, an object formed by fname and lname. So your output isn't a List but a List, so you can manage better your information.

public class MyObject {
    public var lname;
    public var fname;

    public MyObject(String lName, String fName) {
        this.lname = lName;
        this.fname = fName;
    }
}


public String getName() {
    SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
    Session session=sessionfactory.openSession();
    session.beginTransaction();
    Query qry=session.createQuery("select new MyObject(personaldetails.fname,personaldetails.lname) from Personaldetails as personaldetails where refId=1001");
    List<MyObject> l=(List<MyObject>)qry.list();
    session.getTransaction().commit();
    session.close();
    for(MyObject curr : l)
    {
        // Here you can extract using property of MyObject
        s += curr.lname + " - " + curr.fname;
    }

    name=s;
    return name;
}

Upvotes: 1

Related Questions