I'm trying to write classes and methods to minimize recurring tasks.
For instance, I'm planning to write a generic DAO (Database Access Object) class in Java which can do the basic crud operations by accpeting the inputdata.
For example, the following is a method I just started writing which accepts a Bean as a parameter and constructs an insert query.
public boolean insert(Object object) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException, InvalidDataException {
String tableName = object.getClass().getSimpleName().toLowerCase() + "s";
Field[] fields = object.getClass().getDeclaredFields();
ArrayList<String> columnNames = new ArrayList<>();
for (Field field : fields) {
String fieldName = field.getName();
Method method = object.getClass().getMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1));
if ("id".equalsIgnoreCase(fieldName)) {
continue;
}
if (method.invoke(object) != null || "created".equalsIgnoreCase(fieldName) || "modified".equalsIgnoreCase(fieldName)) {
columnNames.add(General.toUnderscore(fieldName));
}
}
String sqlQuery = generateInsertSQLQuery(tableName, columnNames);
System.out.println(sqlQuery);
PreparedStatement ps = this.conn.prepareStatement(sqlQuery);
int index = 1;
for (Field field : fields) {
String fieldName = field.getName();
Method method = object.getClass().getMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1));
if ("created".equalsIgnoreCase(fieldName) || "modified".equalsIgnoreCase(fieldName)) {
ps.setDate(index++, new java.sql.Date((new java.util.Date()).getTime()));
} else {
if (method.invoke(object) != null) {
if (field.getType() == String.class) {
ps.setString(index++, (String) method.invoke(object));
} else if (field.getType() == Integer.class) {
ps.setInt(index++, (Integer) method.invoke(object));
} else if (field.getType() == Long.class) {
ps.setLong(index++, (Long) method.invoke(object));
} else if (field.getType() == java.util.Date.class) {
java.sql.Date date = new java.sql.Date(((java.util.Date) method.invoke(object)).getTime());
ps.setDate(index++, date);
}
}
}
}
ps.executeUpdate();
return true;
}
The bean is a pretty standard class with getters and setters. My question is, is this a right approach to handle things in Java ?
Are there any popular resources which already accomplished this ?
Kindly guide me with your valuable inputs.
I would recommend the Spring Framework with the Spring Data JPA project.
http://projects.spring.io/spring-data-jpa/
You can annotate any JavaBean with the correct JPA annotations. Then create an interface which extends the Spring CrudRepository. Some configuration and add the Hibernate or EclipseLink dependencies. Ready!
http://docs.oracle.com/javaee/6/tutorial/doc/bnbpz.html
A good tutorial:
http://spring.io/guides/gs/accessing-data-jpa