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

时光毁灭记忆、已成空白 提交于 2019-12-11 11:06:52

问题


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.


回答1:


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




回答2:


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,




回答3:


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



来源:https://stackoverflow.com/questions/30718824/whats-the-best-way-to-handle-recurring-tasks-like-crud-operations-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!