I am currently programming a three layer architecture banking application as a student project. As I understood the Dao pattern, I implemented it and want to handle the database interaction with it, but I actually can not, because my dao class can not access the database singleton getInstanceDB. The dao class is an implementation of an interface. The classes are all in the same package. It seems to be an visablity problem, because the Singleton is not callable in any other class than itself. Here is the code.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Database {
private static Database instance;
private Connection conn;
private Statement stmt;
private Database() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@oracle.leuphana.de:1521:oradb1", "...", "...");
stmt = conn.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
// Thread-Safe Singleton
public static synchronized Database getInstanceDB() {
if (instance == null) {
instance = new Database();
}
return instance;
}
}
// Select Data by CustomerID
@Override
public ResultSet select(Kunde kunde) {
if (kunde == null)
throw new IllegalArgumentException("given id is null");
if (kunde.getId() < 0)
throw new IllegalArgumentException("given id has an invalid value");
String query = "SELECT * FROM customer WHERE customer_id=" + Integer.toString(kunde.getId());
ResultSet rs = null;
try {
Connection conn = getInstanceDB().getConnection();
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(query);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
I am new to stackoverflow, I hope this thread is ok, if you need more information just ask me ^^
EDIT: Error: The method getInstanceDao() is undefined for the type KundeDao getConnection() see the answer, it's the same except the catch part
Thanks for the quick and helpful answers.