Passing values from bean to Collection

Hi,

I'm a newbie to java programming. Just like to ask how to do this stuff. Basically, i have a Bean, say Employee Bean. I populate it with the setter method after issuing a select statement.

I would like to ask how to pass values from a java bean to a collection, example :

Collection<EmployeeBean> method name() , this is how i declared it.

Thanks

[385 byte] By [redver74a] at [2007-11-27 11:38:35]
# 1

Can you be more clear on what you are asking ?

New_Kida at 2007-7-29 17:21:05 > top of Java-index,Java Essentials,Java Programming...
# 2

Basically, i have a method that will return a Collection of Bean.

public Collection<PersonBean> getResults(String query) ,

in which query contains my sql select statement.

then i issued this following commands inside this method,

Statement stmt = cn,createStatement();

Resultset rs = stmt.executeQuery(query);

Then, i put the fetched records in a bean

while (rs.next()) {

personbean.setName(rs.getString("name"));

personbean.setAddress(rs.getString("address"));

}

Assuming i have a personBean and a DBConnection already established.

My question is how can i add each record to a collection, everytime rs.next loops, because the method will return a collection of bean.

Thank you very much. Any reply would much be appreciated

redver74a at 2007-7-29 17:21:05 > top of Java-index,Java Essentials,Java Programming...
# 3

Use the add method.

BigDaddyLoveHandlesa at 2007-7-29 17:21:05 > top of Java-index,Java Essentials,Java Programming...
# 4

and also, don't forget to create a NEW instance of your bean for each record you want to add to the list. Otherwise you end up adding the same element to your collection multiple times, and then editing it.

Collection<personBean> people = new ArrayList();

while (rs.next()) {

EmployeeBean personbean = new EmployeeBean();

personbean.setName(rs.getString("name"));

personbean.setAddress(rs.getString("address"));

people.add(personbean);

}

return people;

evnafetsa at 2007-7-29 17:21:05 > top of Java-index,Java Essentials,Java Programming...
# 5

Thank you very much guys, i will try it right away. :)

redver74a at 2007-7-29 17:21:05 > top of Java-index,Java Essentials,Java Programming...
# 6

if you don't mind, i have a follow -up question related to above topic.

After returning the method as a collection of personBean. How can I put those values, for instance the name into a JLIST.

Thanks again...

redver74a at 2007-7-29 17:21:05 > top of Java-index,Java Essentials,Java Programming...
# 7

> How can I put those values, for instance the name into a JLIST.

Look at the constructors and methods available in the JList class and see if you can come up with an answer on your own first.

~

yawmarka at 2007-7-29 17:21:05 > top of Java-index,Java Essentials,Java Programming...