I am working on a project with database access. Here is the outline of the classes i have implemented
public class Foo {
private String id;
private String name;
private int x;
private String y;
private String z;
...
public Foo(String id) throws SQLException {
this.id=id;
try (Statement stmt = MyConnectionManager().getConnection().createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM " + TABLE_NAME
+ " WHERE(id='" + this.id + "')");
if (!rs.next()) {
throw new NoExistException();
}
this.name = rs.getString("Name");
this.x = ...
...
} catch (SQLException ex) {
throw ex;
}
}
public int getId() {
return this.id;
}
public String getName() {
.
.
.
But when i looked at most oop samples i have found that most people use an additional class for database access. I don't know what im going to say is a blunder. Those codes access database for initializing each member variable. But in my code database is accessed only once to initialize my object. Should i change this approach. If i change will it affect the speed of my application when it wants to initialize more objects together (may be hundreds). I think this might be a duplication question. But i didn't find any satisfactory answer for my particular problem.