Home arrow static arrow Java Programming [Archive] - Using Lists
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Using Lists
This topic has 14 replies on 1 page.

Posts:65
Registered: 7/13/04
Using Lists  
Jul 19, 2004 11:41 AM



 
How does one populate a list from a database query. I'm using the following and I'm not sure if it should work or not because I don't quite get the idea of using a list. I'm used to arrays in PHP, but not lists.

if (con != null) {			Statement statement = con.createStatement();			List result =null;			result.addAll((Collection) statement.executeQuery(query));			//set the local datamemeber to the			//query result			this.rs = result;		} else {			this.rs = null;		}
 

Posts:37,103
Registered: 3/30/99
Re: Using Lists  
Jul 19, 2004 11:52 AM (reply 1 of 14)



 
statement.executeQuery returns a ResultSet. ResultSet does not implement Collection, so you can't do that cast.

What you probably want here is to define a class that corresponds to one row in the database (e.g. if you have id, first_name, last_name columns, create a class with id, firstName, lastName fields). You need to iterate over the result set, (while rs.next()) and then for each row, populate a new instance of your class.

AFAIK, the standard APIs don't give you a way to shortcut this--you'll need to do the row-by-row iterations and the column-by-column field assignments.

You coud look at something like [url http://hibernate.org/]hibernate[/url] to hide some of the mechanics for you, but that's a non-trivial learning curve.
 

Posts:65
Registered: 7/13/04
Re: Using Lists  
Jul 19, 2004 12:02 PM (reply 2 of 14)



 
Yeah, I looked into Hibernate and OJB, but they look pretty complex. I do have a set of value objects that correspond to my database tables. I'll try to do as you say and populate the value objects. Anyone have experience with SimpleORM? Is that a good means of ORM?
 

Posts:24,036
Registered: 2/3/03
Re: Using Lists  
Jul 19, 2004 12:25 PM (reply 3 of 14)



 
Hibernate defnitely has a learning curve, but it sure is a heap sweeter (and easier) than rolling your own data layer, IMHO.
 

Posts:65
Registered: 7/13/04
Re: Using Lists  
Jul 19, 2004 12:33 PM (reply 4 of 14)



 
Well, I'm so far along now, that I'll just keep going. I have set up the value object new and I iterate throught the resultset assinging a new object and the values in to the object, but how do I access the objects. Is there a way to be able to index them, or create an array of objects? Here's where I'm at so far.

if (rs != null) {				while (rs.next()) { 					UserVO user = new UserVO();					user.setFirstName(rs.getString("first_name"));					user.setLastName(rs.getString("username"));					user.setSecLevel(rs.getInt("security_level"));					user.setSecDesc(rs.getString("security_desc"));					user.setEmail(rs.getString("email"));					return user;				}


Seems like this will just overwriet each prevouis object with the latest one since there's no collection.
 

Posts:24,517
Registered: 98-02-27
Re: Using Lists  
Jul 19, 2004 12:49 PM (reply 5 of 14)



 
...since there's no collection.

So add your UserVo object to your own Collection

This [url http://forum.java.sun.com/thread.jsp?forum=57&thread=497641]example[/url] isn't exactly what your looking for, but you should get the idea.
 

Posts:37,103
Registered: 3/30/99
Re: Using Lists  
Jul 19, 2004 12:52 PM (reply 6 of 14)



 
Well, I'm so far along now, that I'll just keep going.
I have set up the value object new and I iterate
throught the resultset assinging a new object and the
values in to the object, but how do I access the
objects. Is there a way to be able to index them, or
create an array of objects? Here's where I'm at so
far.

if (rs != null) {while (rs.next()) { UserVO user = new UserVO();user.setFirstName(rs.getString("first_name"));user.setLastName(rs.getString("username"));user.setSecLevel(rs.getInt("security_level"));user.setSecDesc(rs.getString("security_desc"));user.setEmail(rs.getString("email"));return user;}


Seems like this will just overwriet each prevouis
object with the latest one since there's no
collection.

You've got a logic problem here. The first time through your loop, you return from the method. Do you expect exactly one row to come back? If so, then skip the while loop and just call rs.next() to create the one object you'll return. (You could do an if rs.next() after that as a sanity check to make sure you didn't get another row when you weren't supposed to, and throw an exception if it returns true).

Or, if you expect multiple rows, then you need to build a List and return that. Where you've got your return now, you need to instead put list.add(user). Then, after the loop, return the list.
 

Posts:65
Registered: 7/13/04
Re: Using Lists  
Jul 19, 2004 1:12 PM (reply 7 of 14)



 
Okay, that totally makes sense about using the list. I want to return multiple objects so the list is what I'm after. Here is the current code.

if (rs != null) {								List userList = null;								while (rs.next()) {										UserVO user = new UserVO();					user.setFirstName(rs.getString("first_name"));					user.setLastName(rs.getString("username"));					user.setSecLevel(rs.getInt("security_level"));					user.setSecDesc(rs.getString("security_desc"));					user.setEmail(rs.getString("email"));					userList.add(user);									}				return userList;


Its seems to work, but now I'm not sure how to iterate throught the List in my test servlet. I curently have a null pointer exception. I'll be hitting the JavaDocs and figuring that out now. Sorry for the ultra-novice issues, but I'm used to a weekly typed, non-OO language (PHP), so a lot of this sutff is foreign to me.
 

Posts:65
Registered: 7/13/04
Re: Using Lists  
Jul 19, 2004 1:23 PM (reply 8 of 14)



 
Fixed that last exaple to include an index. Oops.

if (rs != null) {								List userList = null;								while (rs.next()) {										UserVO user = new UserVO();					user.setFirstName(rs.getString("first_name"));					user.setLastName(rs.getString("username"));					user.setSecLevel(rs.getInt("security_level"));					user.setSecDesc(rs.getString("security_desc"));					user.setEmail(rs.getString("email"));					userList.add(rs.getRow(), user);									}				return userList;
 

Posts:6,750
Registered: 1/25/04
Re: Using Lists  
Jul 19, 2004 1:32 PM (reply 9 of 14)



 
Sorry for the ultra-novice
issues, but I'm used to a weekly typed, non-OO
language (PHP), so a lot of this sutff is foreign to
me.

Yeah, Java is typed daily so that's different. ;-) BTW you shouldn't have to do this, your original should work fine:
userList.add(rs.getRow(), user);
 

Posts:37,103
Registered: 3/30/99
Re: Using Lists  
Jul 19, 2004 1:55 PM (reply 10 of 14)



 
change
List userList = null; 
to
List useList = new ArrayList(); // or new LinkedList()


The NPE stack trace should have told you exactly where the problem was occurring--namely, the first time you tried to do userList.something after having set userList to null, rather than pointing it at an instance of List.
 

Posts:65
Registered: 7/13/04
Re: Using Lists  
Jul 19, 2004 2:50 PM (reply 11 of 14)



 
Almost got it working. I have two questions: can Struts logic tags interate through a List? How does one get the values out of an iterator? Here's what I've got: (user is a List)

if(user.size() > 0) {												while(((Iterator) user).hasNext())				{				    //iterate over all the objects in the list				    out.println("values" + user.iNeedTheValueHere());				    //do something with that object				}							}
 

Posts:37,103
Registered: 3/30/99
Re: Using Lists  
Jul 19, 2004 3:10 PM (reply 12 of 14)



 
Almost got it working. I have two questions: can
Struts logic tags interate through a List?

Yes. It's the iterate tag. In this case, you don't write the java code, you just supply a tag body to be evaluated for each iteration.

How does
one get the values out of an iterator?

With the id attribute

http://struts.apache.org/doc-1.0.2/struts-logic.html#iterate
 

Posts:98
Registered: 11/6/01
Re: Using Lists  
Jul 19, 2004 3:55 PM (reply 13 of 14)



 
This is the way I have been handling this exact problem.

I have a couple of custom Exception that I have written. So ignore those. But this is how I grab the data. Your best bet is to use a UseCase for the Client to access the data.

     Collection list = new ArrayList() ;     StringBuffer sql = new StringBuffer() ;      //some code for query in here        ValueObject vo = new ValueObject() ;        try {          //costom utility to store Resources           DataSource ds = Resource.getDataSource() ;                      if(ds != null) {               conn = ds.getConnection() ;                      }           if(conn == null) {               throw new SQLException("Unable to get Work Flow database Connection, ProjectUsers") ;           }           //prepare statement and execute query           PreparedStatement ps = conn.prepareStatement(sql.toString()) ;           ResultSet rs = ps.executeQuery() ;                      while(rs.next()) {                              vo.setProjectName(rs.getString("pu_project_name")) ;               vo.setProjectID(rs.getString("pu_project_id")) ;               list.add(vo) ;                          }               }       catch(SQLException e){           e.printStackTrace() ;           throw new DataException("error accessing data: " + e.getMessage()) ;       }       catch(ResourceException e){           e.printStackTrace() ;           throw new DataException("error accessing data: " + e.getMessage()) ;       }              finally{     try {             if(conn != null) {            conn.close() ;      }     }     catch(SQLException e) {              e.printStackTrace() ;     }    }     return list ; }}


That is part of the method I use in the DAO then post to a VO and return the collection in a UseCase. I then call the data from the UseCase in an ActionServlet and populate in a Form(Where I lose it, but I will figure that out, hopefully). From the form I call in a JSP within the session and parse.
Hope this helps
 

Posts:65
Registered: 7/13/04
Re: Using Lists  
Jul 19, 2004 4:04 PM (reply 14 of 14)



 
Cool, this helps. Thanks.
 
This topic has 14 replies on 1 page.