This is my first cut at separating the data access layer out of my very old spaghetti codebase.
I have tried to keep this as simple as possible, it is for a small project, so I am not really interested in learning Spring or Hibernate or other framework, and I don't mind writing a bit of SQL.
I basically have a 1-to-1 relation of database table to business object.
This is the Data Access Layer
package dataaccesslayer;
import dbutils.handlers.IgnoreUnderscoreBeanHandler;
import dbutils.handlers.IgnoreUnderscoreBeanListHandler;
import racemanager.businessobjects.Progression;
import org.apache.commons.dbutils.QueryRunner;
import shared.SLDbHelper;
import java.sql.SQLException;
import java.util.List;
public class DalProgression {
private static final String SQL_SELECT_ONE =
" SELECT * "
+ " FROM progressions "
+ " WHERE id=? ";
private static final String SQL_SELECT_ALL =
" SELECT * "
+ " FROM progressions "
+ " ORDER BY name ASC ";
public static Progression selectOne(int id) {
QueryRunner qr;
Progression progression;
try {
qr = new QueryRunner(SLDbHelper.getInstance().getDataSource());
progression = qr.query(SQL_SELECT_ONE, new IgnoreUnderscoreBeanHandler<Progression>(Progression.class), id);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
return progression;
}
public static List<Progression> selectAll() {
QueryRunner qr;
List<Progression> progressions;
try {
qr = new QueryRunner(SLDbHelper.getInstance().getDataSource());
progressions = qr.query(SQL_SELECT_ALL, new IgnoreUnderscoreBeanListHandler<Progression>(Progression.class));
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
return progressions;
}
}
This is the related Business Object
package businessobjects;
import java.util.Date;
public class Progression {
private int id;
private String name;
private Date modified;
private Date created;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
@Override
public String toString() {
return this.getName();
}
}
Usage example
int id = 10;
Progression p = DalProgression.selectOne(id);
List<Progressions> pList = DalProgression.selectAll();
Fire away and shoot holes in my code, so I can improve it.
One thing I am not sure about is when I do joins should I have a separate business object for the result, and as such as corresponding data access layer class to perform those queries?