How to give a JList an ID and name? - java

I have a simple database with 2 columns (ID, Firstname). Now I display each Firstname from my table as an List Item. That works so far. What I want to do is connect my ID from my db table with the firstname cause if i click on a list item the data will be shown in a textfield.
I've created a helper class that has the Name and ID as fields.
public class ListDataHelper {
private int id;
private String name;
public ListDataHelper(int id, String description) {
this.id = id;
this.name = description;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String toString() {
return name;
}
}
My main class looks like this and it works so far.
private void getAllAccounts(){
listAccounts.removeAll();
try{
String sql="select * from accounts";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
DefaultListModel DLM = new DefaultListModel();
while(rs.next()){
DLM.addElement(new ListDataHelper(rs.getInt("ID"), rs.getString("FirstName")));
}
listAccounts.setModel(DLM);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
rs.close();
pst.close();
}
catch(Exception e) {
}
}
}
But I'm stuck at the point when I want to retrieve data. I don't know how to use my created helper class or how to get the ID from the selectedValue.
private void getAllData() {
String data =listAccounts.getSelectedValue();
String sql="select * from accounts where ID=?";
try{
pst=conn.prepareStatement(sql);
pst.setString(1, data);
rs=pst.executeQuery();
while(rs.next()){
String add1 =rs.getString("ID");
txtID.setText(add1);
String add2 =rs.getString("FirstName");
txtFirstName.setText(add2);
String add3 =rs.getString("LastName");
txtLastName.setText(add3);
String add4 =rs.getString("Cheque");
txtCheque.setText(add4);
String add5 =rs.getString("Savings");
txtSavings.setText(add5);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
rs.close();
pst.close();
}
catch(Exception e) {
}
}
}
When I compile the code I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
ccibank.ListDataHelper cannot be cast to java.lang.String
Thanks already in advance! :)

As always, everything would be simpler by reading the documentation.
As you can see immediately if you click the link (or if you just read the warnings emitted by the compiler), DefaultListModel is a generic class, just like a Collection. So you're supposed to specify the type of objects that you put in such a model. You're not putting Strings inside. You're putting instances of ListDataHelper. So it should be declared as
DefaultListModel<ListDataHelper>
If you browse to the JList documentation, you'll see that it's also a generic type: it contains the elements of the same type as its list model. So it should be declared as
JList<ListDataHelper>
Now, what do you get when you call getSelectedValue() on a JList? Again, read the documentation: You get an object of the generic type E. In this case, the generic tpe E is ListDataHelper. This makes perfect sense, doesn't it? If you store objects of type ListDataHelperin the list, the selected value is not a String. It's a ListDataHelper.
So the code should be:
ListDataHelper selectedAccount = listAccounts.getSelectedValue();
Another thing that strikes me is that, even though your code doesn't compile, you haven't posted the compilation error(s) in your question. Why is that? The compilation errors indicate what is wrong, and where. Reading the error is the first thing you should do when you have an error. Don't ignore errors. Reading (the errors, the documentation), is extremely important whe programming.

Related

How to Insert ArrayList data to the DataBase

Im try to insert data into Database using ArrayList.there is a Erro msg.
That is my Custmer.class method. this is what i got from when i going to pass ArrayList into another class.
incompatible types: ArrayList<String> cannot be converted to ArrayList<Inquiries>
I want to know how to do this using correct Using OOP concept
public void passingMsg(ArrayList<Inquiries> arrlist){
try {
System.out.println("Method "+arrlist);
String sq = "INSERT INTO Inquiries (name,mail,tp,msg)VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for(int i=0;i<arrlist.size();i++){
pr.setString(1,arrlist.get(i).getName());
pr.setString(2,arrlist.get(i).getMail());
pr.setString(3,arrlist.get(i).getTp());
pr.setString(4,arrlist.get(i).getMsg());
}
pr.executeQuery();//executeBatch();
} catch (SQLException ex) {
}
}
and this is how i get values from user
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
Custmer c =new Custmer();
if( c.passingMsg(arrInq)){
try {
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
}
and this is my Inquiries.class :
public class Inquiries {
private String name;
private String mail;
private String tp;
private String msg;
public Inquiries(String name,String mail,String tp,String msg){
this.name = name;
this.mail = mail;
this.tp = tp;
this.msg = msg;
}
//
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTp() {
return tp;
}
public void setTp(String tp) {
this.tp = tp;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Can Some one please explain whats wrong with this. please ?
Reason For Error
This was simply telling you that your types were incompatible for the operation you were trying to perform. In your passingMsg() method, you have its header as: public void passingMsg(ArrayList<Inquiries> arrlist). However, inside your "how i get values from user" area, which I will now refer to as "2nd Snippet", you have your method call declared as: if( c.passingMsg(arrInq)). This means that you are implying that your parameter being passed, arrInq in this case, is of the type ArrayList<Inquiries>, but it's not. It's being initialized in your 2nd Snippet as: ArrayList<String> arrInq = new ArrayList<String>();
Simple Fix
I take no responsibility for this code; use at your own risk. To fix this, you would want to change that entire 2nd Snippet to something similar to the following:
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));
Custmer c = new Custmer();
try {
c.passingMsg(arrInq);
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
You would also want to change the method header to either return a boolean, or fix it up a little bit to actually throw the exception. Such as:
public void passingMsg(ArrayList<Inquiries> arrlist) {
System.out.println("Method " + arrlist);
String sq = "INSERT INTO Inquiries(name,mail,tp,msg) VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for (Inquiries inquiries : arrlist) {
pr.setString(1, inquiries.getName());
pr.setString(2, inquiries.getMail());
pr.setString(3, inquiries.getTp());
pr.setString(4, inquiries.getMsg());
}
pr.executeQuery();//executeBatch();
}
Let's talk in O-O-P way.
Here Inquiries is your model, model is nothing but simple class that has instance members and public methods to get and set value of model's instance variable.
Generally we put all database related operations code in their respective models.
e.g. I have model "Model" which typically maps to database table say it as "TableModel" ,I would do something like this:
public class Model{
private int id;
private String attr;
//other properties of the model
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
//other getters and setters
//here we write methods to performs database operations
public void save(){
//use "this" to get properties of object
//logic to save to this object in database table TableModel as record
}
public void delete(int id){
//logic to delete this object i.e. from database table TableModel
}
public Model get(int id){
//retrieve record from table TableModel with this id
}
//other methods to get data from database.
}
Now question is how I can use this in some another class. Let's say I have list of Model objects and I wish to insert them in to database.I will do it something like this:
public class AnotherClass{
public void someMethod(){
//create list of models objects e.g. get them from user interface
ArrayList<Model> models=new ArrayList<>();
for(int i=0;i<3;i++){
Model model=new Model();
model.setId(i);
model.setAttr("attr"+i);
models.add(model);
}
SomeOtherClass obj=new SomeOtherClass();
obj.insert(models);
}
}
public class SomeOtherClass{
//other code above.....
//my method that inserts each Model object in database
//Note: this is sample method , you should do it in optimized way
// e.g. batch insert
public void insert(ArrayList<Model> models){
for(Model myModel:models){
myModel.save();
}
}
//other code below.....
}
You are using the wrong type parameter for the ArrayList. Instead of ArrayList<String> you need ArrayList<Inquiries>. To fix the problem, you should remove this code ...
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
... and replace it with this code:
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));

Using multiple constructors with ArrayList don't work

I was using multiple constructor from the same class, but a few days ago I got a 'rare' problem. The constructor initializes all the fields =(
I have Ejercicio.java class
public class Ejercicios {
int Id_Ejercicio;
String Descripcion;
String Finalidad;
String Duracion;
//Constructor
public Ejercicios() {
super();
}
//Constructor with 2 fields
public Ejercicios(int id_Ejercicio, String descripcion) {
super();
Id_Ejercicio = id_Ejercicio;
Descripcion = descripcion;
}
//Constructor with 4 fields
public Ejercicios(int id_Ejercicio, String descripcion, String finalidad, String duracion) {
super();
Id_Ejercicio = id_Ejercicio;
Descripcion = descripcion;
Finalidad = finalidad;
Duracion = duracion;
}
}
And the Lista_Ejercicios.java class
public class List_Ejercicios {
ArrayList<Ejercicios> lejer;
public List_Ejercicios() {
super();
}
}
And my principal class where I try to use these differents constructors
public Response Principal(SQLQuery){
List<Ejercicios> listaEJER = new ArrayList<Ejercicios>();
dbCon = new ConexionBD();
ResultSet rslt;
try {
conn = (Connection) ConexionBD.setDBConnection();
rslt = dbCon.getResultSet(SQLQuery, conn);
while(rslt.next()){
listaEJER.add(new Ejercicios( rslt.getInt(1),rslt.getString(2) ));
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//finally block code
return Response.ok(listaEJER.toArray()).build();
}
I was using 'Advanced Rest Client' for Chrome and I don't have an idea why I receive the 4 fields instead 2 like I especified in the constructor
...
{
descripcion: "Jump as high as you can"
id_Ejercicio: 1
finalidad: null
duracion: null
}
...
I have in trouble, these constructors work two weeks ago I don't have any clue why currently its running doesn't work.
They did not work two weeks ago. You've changed something. When you declare a field in your class, that field is always there. If you don't initialise it in your constructor, it will be auto-initialised. For classes, this default value is null, whereas for primitives it is 0, false etc. However, this behaves exactly the same as if you had initialised it to that value in the constructor - myEjercicios.Finalidad (use naming conventions please) will be null, as it is an auto-initialised object of type String.
As for fixing this issue, it shouldn't be hard to write some code to not print values that are null. If you want a different set of fields, however, you must declare two different classes (perhaps one extending the other).

Map query results to POJO constructor in Java

I have a set of SQL queries and a corresponding POJO object with a constructor.
Ex.
Student student = new Student(rs.getString("FNAME"), rs.getString("LNAME"), rs.getString("GRADE"));
Currently I'm mapping the column in result set to a field manually. I would like to make this generic so I can do something like new Student(rs.getRow()) and then I can map it via some kind of configuration file. There could be N number of fields in select query and order doesn't necessarily match with order defined in the constructor.
I would like to have control over the SQL since it could have lot of joins so I am not sure if an ORM would work here. I strictly want something that could map the resultset columns to a field.
I would like to add annotations in my Student class for mapping
public class StudentRowMapper implements RowMapper<YourStudentPojo> {
#Override
public YourStudentPojo mapRow(final ResultSet rs, final int arg1) throws SQLException {
final YourStudentPojo item = new YourStudentPojo();
item.setFName(rs.getString("FNAME"));
return item;
}
Similar to this FName, you can set the other values in your pojo. No need for constructor. Just if you make changes in Pojo then corresponding changes must be done in this method.
This does seem like a textbook example of a place to use JPA or a similar ORM technology.
However, if you are set on just doing this with annotations, you can create your own annotations - http://www.mkyong.com/java/java-custom-annotations-example/ is a pretty good tutorial on doing so.
You'd create your own #DatabaseField annotation that you'd annotate the fields of the object with, specifying the corresponding Database field. You'd then, in the constructor, take your class (Class klass = this.getClass()), get the declared fields on it (klass.getDeclaredFields()), and for each of those, look at the declared annotations (field.getDeclaredAnnotations()). For each of those, if they are your custom databasefield annotation, make a note of the mapping. Once you have gone through all fields, you'll have a map of fields to database columns, which you can then go ahead and set using reflection (the Field object you have has a set method on it, you'll call that with "this" (the object being constructed) and the value you got with the result set.
Might be an interesting exercise, but I still think you'd be better off with JPA or one of the lighter weight ORMs like SimpleORM.
You can do with java reflection .
For example we will take your sql query is like this.
SELECT FirstName 'FNAME', LastName 'LNAME', Grade 'GRADE' FROM Employee
So you will get the output as the following
FNAME LNAME GRADE
John Dan A+
Then in your java code you will need to reflection to achieve the rest
Suppose your Student class is like this
public class Student {
private String LNAME;
private String FNAME;
private String GRADE;
public String getLNAME() {
return LNAME;
}
public void setLNAME(String lNAME) {
LNAME = lNAME;
}
public String getFNAME() {
return FNAME;
}
public void setFNAME(String fNAME) {
FNAME = fNAME;
}
public String getGRADE() {
return GRADE;
}
public void setGRADE(String gRADE) {
GRADE = gRADE;
} }
And you can set the corresponding values in the Student class using the following code.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
try {
//configuring the columns in the sql statement and class
String[] ColumnArray = new String[]{"LNAME","FNAME","GRADE"};
// making a hashmap to emulate the result set of sql
HashMap<String, String> rs = new HashMap<String, String>();
rs.put("FNAME", "John");
rs.put("LNAME", "Dan");
rs.put("GRADE", "A+");
//reflection of the
Class cls = Class.forName("Student");
Object c = cls.newInstance();
Method[] mtd = cls.getMethods();
for (String column : ColumnArray) {
Method method = cls.getMethod("set"+column, String.class);
method.invoke(c, new Object[]{rs.get(column)});
}
//casting the class to employee
Student student = (Student) c;
//Printing the output
System.out.println(student.getFNAME());
System.out.println(student.getLNAME());
System.out.println(student.getGRADE());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}}
Please let me know if your facing any issue. Happy to help you.
It's not perfect but look at this:
public class Student {
private String name;
private Integer age;
//etc.
public Student() {
//default constructor
}
public Student(final ResultSet rs) throws Exception {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i < columnCount + 1; i++ ) {
String name = rsmd.getColumnName(i);
if (Student.getField(name)) {
Student.getField(name).set(rs.getString(name));
}
}
}
}
You should also map field to colum type, in example I used only getString.
If result of your query going to be some domain object like Student (nevermind how many joins in FROM statement) then ORM would work fine and maybe it's good solution. If you are going to extract some complex data structure then you can take a look at some Spring features like RowMapper.
You can make use of GSON serialized object mapping.
refer
Check with HIbernate SQLQuery addScalar() Example here http://www.journaldev.com/3422/hibernate-native-sql-example-addscalar-addentity-addjoin-parameter-example
This will exactly give total result-set as POJO object. You can later iterate through it for data.
Let me know if this helps you.
Assume your STUDENT table is as follows.
__________________________
|STUDENT_ID | AGE | NAME |
--------------------------
| | | |
| | | |
--------------------------
Your have to have a control over your SQL query. It's return columns must be renamed according to POJO class's variable names. So the SQL query would be like as follows.
SELECT AGE AS age, NAME AS name from STUDENT;
Finally, the POJO class's constructor is as follows. It will iterate through all the private variables inside the class, and check whether those columns are available in the ResultSet.
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.ResultSet;
public class Student
{
private int age;
private String name;
public int getAge()
{
return age;
}
public void setAge( int age )
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName( String name )
{
this.name = name;
}
public static void main( String[] args )
{
new Student( null );
}
public Student( ResultSet rs )
{
Field[] allFields = this.getClass().getDeclaredFields();
for ( Field field : allFields )
{
if ( Modifier.isPrivate( field.getModifiers() ) )
{
String fieldName = field.getName();
String methodName = "set" + fieldName.substring( 0, 1 ).toUpperCase() + fieldName.substring( 1 );
try
{
Method setterMethod = this.getClass().getMethod( methodName, field.getType() );
setterMethod.invoke( this, rs.getObject( fieldName ) );
}
catch ( Exception e )
{
e.printStackTrace();
}
}
}
}
}

Loading from a database to a jlist brings errors

I have created a database and every entry from the JList will be added to a table in the database. This work perfectly, but my next task is to get whatever is in the database to load to the JList. I have a function created within the button but it brings up errors. I'm struggling with how to fix this so I hope somebody can resolve it.
Thanks
Here is my code:
JButton btnDb1 = new JButton("J");
btnDb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
ResultSet rs = st.executeQuery("SELECT * FROM patient");
while (rs.next()) {
Patient patient = new Patient(patientname, patientaddress, patientphone, patientid);
patient.setName(rs.getString("patientname"));
patient.setAddress(rs.getString("patientaddress"));
patient.setPhoneNum(rs.getString("patientphone"));
patient.setID(rs.getInt("patientid"));
MainDentist.model.addElement(patient);
}
} catch (Exception e) {
System.out.println(" Error ");
}
}
});
btnDb1.setBounds(200, 393, 120, 23);
contentPane.add(btnDb1);
Here is my patient class:
public class Patient {
public String patientName;
public String patientAddress;
public String patientPhone;
public int patientID;
public Patient(String patientname, String patientaddress, String patientphone,int patientid){
patientName = patientname;
patientAddress = patientaddress;
patientPhone = patientphone;
patientID = patientid;
}
public String setName(String patientname){
return patientName = patientname;
}
public String getName(){
return patientName;
}
public String setAddress(String patientaddress){
return patientAddress = patientaddress;
}
public String getAddress(){
return patientAddress;
}
public String setPhoneNum(String patientphone){
return patientPhone = patientphone;
}
public String getPhoneNum(){
return patientPhone;
}
public int setID(int patientid){
return patientID = patientid;
}
public int getID(){
return patientID;
}
public String toString() { // Printing the patient's details to the scroll pane
return "Patient Name: " + patientName + ", PatientAddress: "
+ patientAddress + ", PatientPhone: " + patientPhone
+ ", patientID: " + patientID +"" ;
}
}
Let me rephrase the actionlistener – posting code in comments isn't really helpfull :)
First I would put the code from your actionPerformed method somewhere else, best would be even to create some class that handles the whole reading and maybe writing of the database. That way you don't mix reading the database with pushing buttons (maybe you want to create another button that reads the database, too. Then you don't have to write all the code again). Anyway, this is an example:
JButton btnDb1 = new JButton("J");
btnDb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
readDatabase();
}
});
public void onActionPerformed(){
try {
// I don't know where you have that part of code, but you didn't create any statement variable. So here an example DB-connection:
String url = "jdbc:mysql://localhost/myDatabase";
Connection connection = DriverManager.getConnection(url, "username", "password");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM patient");
while (rs.next()) {
// read the columns one by one, that way it may be easier to detect errors if one column is wrong
String name = rs.getString("patientname");
String address = rs.getString("patientaddress");
String phone = rs.getString("patientphone");
int id = rs.getInt("patientid");
// now that you have all values, create the patient and add it to the model
// if you have all parameters for the constructor, you don't need to use the setters to set the name and address …
MainDentist.model.addElement(new Patient(name, address, phone, id));
}
} catch (Exception e) {
// as JB Nizet suggested, it is easier to detect errors, when you print the whole stack trace (it will tell you in which line the exception gets thrown
e.printStackTrace();
}
}
This still may not work right away, if you get errors, edit your post and tell us what goes wrong. BTW: I noticed that you have your variables name, address and all this in the patient set to public. This isn't wrong but it is recommended to use getter and setters (as you do) and make the variables private. That way you can control how the variables get accessed from outside.

I want to display all the data in my console from the data base using ArrayList

Hello all i want is to display entire content of my database table on Console. I am trying to fetch record from database first and store in ArrayList but it does not display any thing insted it display this:
[com.suven.java.EmployeeDTO#970c0e]
[com.suven.java.EmployeeDTO#970c0e, com.suven.java.EmployeeDTO#987197]
[com.suven.java.EmployeeDTO#970c0e, com.suven.java.EmployeeDTO#987197, com.suven.java.EmployeeDTO#497904]
I am fully confused to what to do. My code is:
EmployeeDTO java file
public class EmployeeDTO
{
//private properties
private int empNo;
private String eName;
private String jobTitle;
//setters
public void setEmpNo(int val){empNo=val;}
public void setEName(String val){eName=val;}
public void setJob(String val){jobTitle=val;}
// getters
public int getEmpNo(){return empNo;}
public String getEName(){return eName;}
public String getJob(){return jobTitle;}
}
My EmployeeList java code is:
public class EmployeeList
{
public static void main(String argv[])
{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try
{
// Load the JDBC driver
// This can be skipped for Derby, but derbyclient.jar has to be in the CLASSPATH
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "E:/Database/java";
conn=DriverManager.getConnection("jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+accessFileName+".accdb;");
// Build an SQL String
String sqlQuery = "SELECT * from Employee";
// Create a Statement object
stmt = conn.createStatement();
// Execute SQL and get obtain the ResultSet object
rs = stmt.executeQuery(sqlQuery);
ArrayList<EmployeeDTO> employees = new ArrayList<EmployeeDTO>();
// Process the result set - print Employees
while (rs.next())
{
EmployeeDTO currentEmp = new EmployeeDTO();
currentEmp.setEmpNo(rs.getInt("EMPNO"));
currentEmp.setEName(rs.getString("ENAME"));
currentEmp.setJob(rs.getString("JOB_TITLE"));
employees.add(currentEmp);
System.out.println(employees);
}
}
catch( SQLException se )
{
System.out.println ("SQLError: " + se.getMessage ()+ " code: " + se.getErrorCode ());
}
catch( Exception e )
{
System.out.println(e.getMessage());
e.printStackTrace();
}
finally
{
// clean up the system resources
try
{
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
My database is:
Employee
EMPN ENAME JOB_TITLE
1 abc xyz
2 pqr mno
3 lmn hij
Please help me i have posted my full code and database
where am i going wrong how to display it in a console
You have to implement toString() in your EmployeeDTO class. If you are using Eclipse you can generate the method: right click the class -> Source -> Generate toString()...
ArrayList<EmployeeDTO> employees = new ArrayList<EmployeeDTO>();
// Process the result set - print Employees
while (rs.next())
{
EmployeeDTO currentEmp = new EmployeeDTO();
currentEmp.setEmpNo(rs.getInt("EMPNO"));
currentEmp.setEName(rs.getString("ENAME"));
currentEmp.setJob(rs.getString("JOB_TITLE"));
employees.add(currentEmp);
System.out.println(employees);
}
In this code, you are putting Object into ArrayList, not an actual String/Value into it. That's why you are getting as com.suven.java.EmployeeDTO#970c0e
You need to override toString in your EmployeeDTO class. You could use String.format to do the formatting:
#Override
public String toString() {
return String.format("%d\t%s\t%s", empNo, eName, jobTitle);
}
To print each employee on a separate line you could use:
for (EmployeeDTO employee : employees) {
System.out.println(employee);
}
Looks like you need an implementation of toString() in your DTO. You'd implement that such that it returns a string consisting of your employee name, job etc... Here's a link to 10 tips for implementing toString().
I note also that you print the list of employees after you read each employee. I suspect rather that you need to print the employee itself.
System.out.println(employees); // this is the list itself!
You are doing it all right except in the line
System.out.println(employees);
in the while loop.
You cannot display ArrayList like that with out overloading toString() in your EmployeeDTO class.
Instead, to display array list, do this after the while loop
for(EmployeeDTO emp : employees)
{
System.out.println(emp.getEmpNo() + " " + emp.getEName() + " " + emp.getJob());
}

Categories

Resources