I have a following function:
public Map<Integer, Product> fetchAllProducts() {
Map<Integer, Product> pArr = new HashMap();
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT id, intro, content, price FROM Product");
while (rs.next()) {
pArr.put(rs.getInt("id"), new Product(rs));
}
st.close();
} catch (SQLException ex) {
//...
}
return pArr;
}
which gets all the rows from mySQL table Product and for each row creates a new Product class. Product constructor:
public Product(ResultSet rs) {
try {
price = rs.getInt("price");
content = rs.getString("content");
intro = rs.getString("intro");
} catch (SQLException ex) {
//...
}
}
My question is: is there a better way to assign the result columns to variables in Product? The code price = rs.getInt("price"); and so on seems redundant, doesn’t it? Perfect would be, if I change the query statement to SELECT intro, content, tax, delivery FROM ... the constructuor would automaticlly assign it to the appropriate variables (i.e. intro, content, tax, delivery) in the constructor. Can this be done in Java or am I just dreaming?
First: You really shouldn’t pass the
ResultSetto the constructor ofProduct! You should cleanly divide your database access code from your business logic.So typically I would expect to see this in your code:
But to answer your question: Doing this is a very common practise when dealing with plain JDBC. What you are looking for is an ORM framework like Hibernate.
One thing I’m doing when using JDBC connection is declaring constants for the column names and table names. That way it is a bit cleaner in my opinion.