maybe anybody could help me out. i’m working with Data access object.
i have a database:
table Receiverz
num name
1 Walmart
2 Target
3 McDonalds
i’ve created a class for this table
public class Receiverz {
private int num;
private String name;
public void setNum(int num) {
this.num = num;
}
public void setName(String name) {
this.name = name;
}
}
then i created Dao interface and passed a method to it:
public interface Dao {
Receiverz getReceiverz(int num);}
Then i created a class ExpensesDao that implements Dao and created a singleton in it(i aslo set up the connection with database but i will skip that part) and overrode getReceivers(int num) method by making it possible to work with database:
public class ExpensesDao implements Dao {
private static Dao thisdao;
public static synchronized Dao getDao() {
if (thisdao==null) {
thisdao = new ExpensesDao();
}
return thisdao;
}
@Override
public Receiverz getReceiverz(int num) {
Receiverz receiver = new Receiverz();
try {
Statement stmt = myConnection.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM receiverz");
while(result.next()){
receiver.setNum(num);
receiver.setName(result.getString(2));
}
}
catch (SQLException e){
System.out.println(e.getMessage());
}
return receiver;
}
when i try to run it in main class:
public class TryDatabase {
public static void main(String[] args) {
Dao ex = ExpensesDao.getDao();
System.out.println(ex.getReceiverz(2));
all i get is:
listexpenses.Receiverz@193499fd
but i have to get
2 Target
(since i passed 2 in the parameters and it refers to Target in my database.
does anyone know what’s going wrong and what i should change in my code. P.S. i hope i made it clear enough.
ex.getReceiverz(2)is returning aReceiverzobject. Thus theSystem.out.println(ex.getReceiverz(2));is using thetoString()method inherited fromjava.lang.Object. Create atoString()method in theReceiverzclass that will output it the way you want.