I have the below MyBatis Mapper with an insertion method:
String INSERT =SQLUtil.getFields(Consumer.class);
String INSERT_WITH_BRACE = SQLUtil.GetFieldsWithBrace(Consumer.class);
@Insert("INSERT INTO Consumer("+ INSERT +") " +
" VALUES " + INSERT_WITH_BRACE)
public int insert(Consumer consumer);
The idea is to generate boiler-plate code using SQLUtil
; a utility class which has two static methods.
@Component
public class SQLUtil {
private static StringBuilder stringBuilder;
public static String getFields(Class clazz) {
stringBuilder = new StringBuilder();
Field[] declaredFields = clazz.getDeclaredFields();
int pos = 0;
for(Field field: declaredFields){
stringBuilder.append(field.getName());
if(pos++ < declaredFields.length-1)
stringBuilder.append(",");
}
return stringBuilder.toString();
}
public static String GetFieldsWithBrace(Class clazz) {
int i=0;
stringBuilder = new StringBuilder();
Field[] declaredFields = clazz.getDeclaredFields();
for(Field field: declaredFields){
stringBuilder.append("#{");
stringBuilder.append(field.getName());
stringBuilder.append("}");
if(i++ < declaredFields.length-1)
stringBuilder.append(",");
}
return stringBuilder.toString();
}
}
Here I utilize reflection to retrieve all properties from a specific class returning the boiler-plate mapper. But I have the error message "attribute must be Constant". I really don't want to write those properties on my own. How can I solve this?
Aucun commentaire:
Enregistrer un commentaire