我是Play framework& ebean 并且想要一个通用的util函数来更新我的Model的实例 所以我使用了以下代码:
private static void updateEntity(Class cls, Long id, ObjectNode data){
Object instance = Ebean.find(cls,id);
for (Field field :cls.getFields()){
String fieldName = field.getName();
if (!fieldName.equals("id")){
field.setAccessible(true);
try {
field.set(instance, data.get(fieldName).toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
try {
//not work
cls.getMethod("save").invoke(instance);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
//not work too
//Ebean.save(instance);
}
我通过使用:
来调用它 Long id = 1L;
Class cls = MyEntity.class;
ObjectNode data = Json.newObject();
data.put("name","Hello world");
data.put("id",1L);
updateEntity(cls,id,data);
MyEntity是包含id和name的模型的nomarl实体类 那么,我下一步该怎么办?
答案 0 :(得分:0)
private static void updateEntity(Class cls, Long id, ObjectNode data){
User user = Ebean.find(cls,id); // For example, consider Ebean returns 'User' object. You can mention your Model here.
try{
user.getClass().getDeclaredField("id").set(user, data.get("id").toString());
}
catch(NoSuchFieldException exception){
exception.printStackTrace(); // If no field is found in the name of `id`.
}
catch(NullPointerException exception){
exception.printStackTrace(); // If field name is null
}
catch(Exception exception){
exception.printStackTrace();
}
user.save();
}