方式一:使用JPA
方式二:使用EntityManager
方式三:原生SQL
private Object mergeExt(Object o) {String tableName = o.getClass().getSimpleName();StringBuffer sb = new StringBuffer();String sqlHeader = "update " + tableName + " set ";sb.append(sqlHeader);Field[] fields = o.getClass().getDeclaredFields();//遍历拼接update语句for (Field field : fields) {String fieldName = field.getName();// update 语句中不更新分库key字段if (!"TENANTID".equals(fieldName.toUpperCase())) {Object value = getFieldValueByName(fieldName, o);// if (null != value) {String column = fieldName + "=:" + fieldName+",";sb.append(column);// }}}//去除最后一个,int last=sb.lastIndexOf(",");sb.delete(last,last+1);//拼接where 条件sb.append( " WHERE id = :id and tenantid= :tenantid");Query query = em.createQuery(sb.toString());//遍历拼接参数for (Field field : fields) {Object value = getFieldValueByName(field.getName(), o);// if (null != value) {query.setParameter(field.getName(),value);// }}query.setParameter("id", getFieldValueByName("id", o));query.setParameter("tenantid", getFieldValueByName("tenantid", o));query.executeUpdate();return o;
}private Object getFieldValueByName(String fieldName, Object o) {try {String firstLetter = fieldName.substring(0, 1).toUpperCase();String getter = "get" + firstLetter + fieldName.substring(1);Method method = o.getClass().getMethod(getter, new Class[]{});Object value = method.invoke(o, new Object[]{});return value;} catch (Exception e) {return null;}
}
mergeExt(实体对象);