通用的方法来创建不同的POJO对象并在数据库中持久化存储。

huangapple go评论62阅读模式
英文:

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&lt;String, Consumer&lt;?&gt;&gt; map = new HashMap&lt;&gt;();
 map.put(&quot;Teacher&quot;, (e) -&gt; teacherRepository.save(mapper.readValue(e,Teacher.class))
});

and you can use it like,

map.get(&quot;Teacher&quot;).accept(jsonString);

huangapple
  • 本文由 发表于 2020年9月21日 22:44:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63994654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定