英文:
Generic way to create different pojo objects and persist in db
问题
我正在创建一个使用 Spring Data JPA 进行持久化的项目。我会收到一个 JSON 字符串作为输入,我会将其转换为相应的 POJO 对象,然后保存到数据库中。目前我在使用 if else 来确定使用哪个 POJO 对象以及相应的 Repository。是否有一种通用的方式来处理这个,而不是使用 if else 呢?请提供帮助。提前感谢。
以下是你的代码:
if (designation.equals("Teacher")) {
Teacher teacher = mapper.readValue(jsonString, Teacher.class);
teacherRepository.save(teacher);
} else if (designation.equals("Student")) {
Student student = mapper.readValue(jsonString, Student.class);
studentRepository.save(student);
} else if (designation.equals("Staff")) {
Staff staff = mapper.readValue(jsonString, Staff.class);
staffRepository.save(staff);
}
英文:
I'm creating a project that uses spring data jpa for persistance. I'm receiving a json string as input that I transform to the corresponding pojo to save into the db. Currently I'm using if else to determine the pojo and the corresponding repository. Is there a way to handle this generically instead of using if else.
Please help. Thanks in advance.
here is my code:
if(designation.equals("Teacher"))
{
Teacher teacher= mapper.readValue(jsonString,Teacher.class);
teacherRepository.save(teacher);
}
else if(designation.equals("Student"))
{
Student student= mapper.readValue(jsonString,Student.class);
studentRepository.save(student);
}
else if(designation.equals("Staff"))
{
Staff staff= mapper.readValue(jsonString,Staff.class);
staffRepository.save(staff);
}
答案1
得分: 0
如果您有使用不同存储库的资源,也许应该有不同的REST端点(或者您正在使用的其他内容)和服务类。
摆脱if-else块的一种简单方法是使用Map:
Map<String, Consumer<?>> map = new HashMap<>();
map.put("Teacher", (e) -> teacherRepository.save(mapper.readValue(e, Teacher.class)));
您可以这样使用它:
map.get("Teacher").accept(jsonString);
英文:
If you have resources which use different repositories maybe you should have different REST endpoints (or whatever you are using) and service classes right.
One simple way to get rid of your if-else blocks would be to use a Map
Map<String, Consumer<?>> map = new HashMap<>();
map.put("Teacher", (e) -> teacherRepository.save(mapper.readValue(e,Teacher.class))
});
and you can use it like,
map.get("Teacher").accept(jsonString);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论