Soumen Dey Soumen Dey - 2 months ago 6
Java Question

How to Update table after retrieving and returning the result to the method head in hibernate?

public ArrayList<Task> getTaskDao(Contributor contributor , Task task) {

getConnection();
query = session.createQuery("Select t.taskId,t.task from Task t where status='NOTALLOCATED'");
ArrayList<Task> tasklist = (ArrayList<Task>) query.list();
logger.info(tasklist.size());
List list = new ArrayList();
list.add(tasklist.get(0));
return (ArrayList<Task>) list;


Now I want to update
status = 'ALLOCATED'
in the task table inside same method.

Answer

You need to dynamically allocate the status, for this you can pass the status as a parameter and later in query update as the below code.

public ArrayList getTaskDao(Contributor contributor, Task task, String status) 
{  
    getConnection();

    Query query = session.createQuery("Select t.taskId,t.task from Task t where status='"+status+"'");
    ArrayList tasklist = (ArrayList) query.list();
    logger.info(tasklist.size());
    List list = new ArrayList();
    list.add(tasklist.get(0));
    return (ArrayList) list;
}

Hence, the query will work for both the status i.e, 'ALLOCATED' and 'NOTALLOCATED' by calling the below code:

getTaskDao(contributor, task,"ALLOCATED") ;
getTaskDao(contributor, task,"NOTALLOCATED") ;

If the status is a property of task then you can use the below query.

public ArrayList getTaskDao(Contributor contributor, Task task) 
{  
    getConnection();

    Query query = session.createQuery("Select t.taskId,t.task from Task t where status='"+task.getStatus()+"'");
    ArrayList tasklist = (ArrayList) query.list();
    logger.info(tasklist.size());
    List list = new ArrayList();
    list.add(tasklist.get(0));
    return (ArrayList) list;
}