0

I'm trying to retrieve data from db and displaying it in a table form using JSP.

The problem is when I do query.list() it is returning null.

There are 10 records in the db.

How do I retrieve all the records ?

Below is my DTO

public class TaskDAO {
    @SuppressWarnings("unchecked")
    public List<Task> getUserTasks(String userName) {
        // Task task = getTasksByUserName(userName);
        Configuration configuration = new Configuration().configure();
        SessionFactory sessionFactory = configuration.buildSessionFactory();

        Session session = sessionFactory.openSession();
        Transaction transaction = null;
        List<Task> task = new LinkedList<Task>();
        try {
             transaction = session.getTransaction();
            transaction.begin();
            Query query = session.createQuery("select id, taskDescription from Task where USERNAME='"
                    + userName + "'");
            task = query.list();
            transaction.commit();

        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }

        return task;

    }

}

Below is my JSP

<%@page import="java.util.Iterator"%>
<%@page import="com.sk.app.dto.Task"%>
<%@page import="java.util.List"%>
<%@page import="com.sk.app.controller.Success"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home Page</title>
</head>
<body>
<h2>Tasks</h2>
<table>
<%
List tasks =  (List)request.getAttribute("taskList");
Iterator iterator = tasks.iterator();
while (iterator.hasNext()){
    Task currentTask = (Task) iterator.next();%>

    <tr>
        <td> <%=currentTask.getId()%></td>
        <td> <%=currentTask.getTaskDescription()%></td>
    </tr>
    <%} %>
</table>

Below is my Servlet

public class Success extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");
        try {
            TaskDAO taskDAO = new TaskDAO();

            List<Task> taskList = taskDAO.getUserTasks(userName);

            request.setAttribute("taskList", taskList);
            Iterator<Task> iterator = taskList.iterator();
            int count = 0;
            while (iterator.hasNext()){
                count ++;
            }
            System.out.println(count);
            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("task.jsp");

            requestDispatcher.forward(request, response);
        } catch (Exception e) {

            e.printStackTrace();
        }

    }
}

Below is my Task dto

public class Task {
    private int id;
    private String taskDescription;
    private String USERNAME;
    public String getUserName() {
        return USERNAME;
    }
    public void setUserName(String userName) {
        this.USERNAME = userName;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getTaskDescription() {
        return taskDescription;
    }
    public void setTaskDescription(String taskDescription) {
        this.taskDescription = taskDescription;
    }
    @Override
    public String toString() {
        return "Task [id=" + id + ", taskDescription=" + taskDescription
                + ", USERNAME=" + USERNAME + "]";
    }


}

When I debugged the program this is the result I get on inspecting task = query.list(); debug

The below image is the table structure, the username column is foreign key to user table. table

2
  • This is a giant collection of "don't do that"s. Don't use scriptlets, don't use string pasting to generate queries, don't hand-write transaction management or DAOs, and don't write servlets by hand. I can replace your entire code with about 10 lines in Spring and 10 lines of HTML template. Commented Mar 16, 2016 at 9:05
  • @chrylis I'm new to this, learning from scratch. Trying to implement what I learnt. Commented Mar 16, 2016 at 9:14

1 Answer 1

1

Obviously, that you don't get any data from the database, because of your HQL is incorrect. You need to get all Task

Query query = session.createQuery("from Task where USERNAME='"
                    + userName + "'");

Check your property USERNAME. It has to be a persistent class property, not a database column!

Just use transaction = session.beginTransaction(); in place of

transaction = session.getTransaction();
transaction.begin();

use List<Task> task = null; in place of

List<Task> task = new LinkedList<Task>();
Sign up to request clarification or add additional context in comments.

10 Comments

Still the same, returns null.
@ShashiKiran Do this System.out.println(session.createQuery("from Task where username='3'").list());
This is output I got for that ' [com.sk.app.dto.Task@7a87274f, com.sk.app.dto.Task@3f25f261, com.sk.app.dto.Task@544bdeaa, com.sk.app.dto.Task@41079622, com.sk.app.dto.Task@5911b388] ' This not correct right ?
I Created toString method, and this is the output after that - '[Task [id=1, taskDescription=null, USERNAME=null], Task [id=3, taskDescription=null, USERNAME=null], Task [id=7, taskDescription=null, USERNAME=null], Task [id=9, taskDescription=null, USERNAME=null], Task [id=10, taskDescription=null, USERNAME=null]]'
@ShashiKiran Looks like, you get data from the database. Please, add Task to your question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.