What's the best way to handle recurring tasks like CRUD operations in Java?

335 views Asked by At

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.

3

There are 3 answers

2
Stefaan Neyts On BEST ANSWER

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

1
Marcos Vasconcelos On

Hibernate and the Java Persistence API (hibernate based) does this reflection tricky for you.

1
Alex Rogachevsky On

Look at Spring Data: http://projects.spring.io/spring-data/ Generally instead of questions like this you should ask "How can I do it in Spring?" Spring is already one level above everything - particularly ORMs. It makes most of the tedious programming tasks declarative,