在编写CRUD的DAO中,有不少类似的批处理update操作。对多个不同的表这么重复写一次,每次都只是表名有所不同也麻烦。 能否抽象出来统一简化呢?
我经研究给出以下简单的解决方案:
BeanUtil.java:
同时,要在Entity类中的作为identity的那个字段上加上@Id annotation,上述
BeanUtil类才能工作。例如:
这样,在业务逻辑层只写这样的代码就可以了,很简单吧:
很简陋的一个想法,只望能抛砖引玉.
我经研究给出以下简单的解决方案:
/* written by Wooce Yang,2009/10/09
* 执行依据数据库主键的update操作
* */
public void updateByID(String id, String setFieldStr) {
createQuery("update " + entityClass.getSimpleName() + " set " + setFieldStr + " where " + BeanUtil.getFieldByAnnotation(entityClass, Id.class).getName() + "=" + id + ")").executeUpdate();
}
/* written by Wooce Yang,2009/10/09
* 执行依据数据库主键的批处理update操作
* Entity Class须在主键字段处加上@Id的annotation
* */
public void updateByIDs(String[] ids, String setFieldStr) {
String idsStr = "";
for (int i = 0; i < ids.length; i++) {
if (i > 0)
idsStr += ",";
idsStr += ids[i];
}
createQuery("update " + entityClass.getSimpleName() + " set " + setFieldStr + " where " + BeanUtil.getFieldByAnnotation(entityClass, Id.class).getName() + " in (" + idsStr + ")").executeUpdate();
}
BeanUtil.java:
import java.lang.reflect.Field;
/**
* Author: Wooce Yang
* Date: 2009-10-9
* Time: 15:43:33
*/
public class BeanUtil {
public static Field getFieldByAnnotation(Class beanClass, Class annotationClass) {
Field[] fields = beanClass.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(annotationClass)) {
return field;
}
}
return null;
}
}
同时,要在Entity类中的作为identity的那个字段上加上@Id annotation,上述
BeanUtil类才能工作。例如:
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long projectId;
这样,在业务逻辑层只写这样的代码就可以了,很简单吧:
public void deleteProject(String id) {
projectDao.updateByID(id, "deleted=1");
}
public void deleteProjects(String[] ids) {
projectDao.updateByIDs(ids, "deleted=1");
}
很简陋的一个想法,只望能抛砖引玉.