rkarwayun
rkarwayun

Reputation: 23

Select a single column from single Row Hibernate

I am developing an application using Java and Hibernate.

Now, there is a Table Empdata and let's say two among its many columns are uid(primary key) and effort.

Now using Hibernate, I want to extract effort for a specific uid.

How will I do so using Hibernate?

Upvotes: 1

Views: 30900

Answers (3)

Ibz.Shaikh
Ibz.Shaikh

Reputation: 325

using uniqueResult() you can get single object.Here is single line java statement.

HQ:- it should contain Empdata as entity class

public Effort getEffort(int uid){
return  session.createQuery("SELECT e.effort FROM Empdata e WHERE e.uid=:uid").setParameter("uid", uid).uniqueResult();
}

SQL:- No entity class required

public Effort getEffort(int uid){
return session.createSQLQuery("SELECT column1 FROM EMP e WHERE e.uid=:uid").setParameter("uid", uid).uniqueResult();
}

Upvotes: 2

Faraz
Faraz

Reputation: 6265

In HQL you can use list() function to get a list of Object[] array that contains result rows:

Query query = session.createQuery("select e.uid from Empdata  e");
List<Object[]> rows = query.list();

in returned array 1-st element will be id, second - name.

for (Object[] row: rows) {
    System.out.println(" ------------------- ");
    System.out.println("id: " + row[0]);        
}

Edit: Another answer to another question:

String hql = "from Empdata where firstname= :fn";    
Query query = session.createQuery(hql);
query.setParameter("fn", "Saad");
query.setMaxResults(1);
Effort ef = (Effort) query.uniqueResult(); 

Upvotes: 3

AJA
AJA

Reputation: 596

Create a method that takes uid as argument and returns an effort.

public Effort getEffort(Integer uid){
    Query query = session.createQuery("SELECT e.effort FROM Empdata e WHERE e.uid=:uid");
    query.setParameter("uid", uid);
    return query.uniqueResult();
}

Here I took the assumption that effort is of type Effort and uid is of type Integer

Upvotes: 6

Related Questions