可以将 Hibernate 实体类用作 GSON 的 POJO 吗?

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

Is it possible to use hibernate entity classes as POJOs for GSON?

问题

我正在处理一个项目,其中我们有一个使用Spring Boot应用程序,该应用程序使用Spring Data和Hibernate。现在我想使用GSON库来处理JSON文件。我阅读了一个教程,清楚地表明可以创建POJO类并将JSON文件转换为这些类的对象。同样的事情也适用于Hibernate。

现在我的问题是:是否可以设计POJO(或实体)类,使它们既适用于Hibernate又适用于GSON?如果可能,并且我以这种方式实现,是否会出现问题?

提前感谢!

编辑:这是我阅读有关GSON的POJO的教程:tutorials point - GSON

英文:

I'm working on a project where we have a spring boot application that uses spring data and hibernate. Now I want to use the GSON library to work with JSON files. I've read a tutorial where it becomes clear that it is possible to create POJO classes and convert JSON files into objects from those classes. The same thing happens with hibernate.

Now my question: is it possible to design the POJO (or entity) classes in a way that they work both for hibernate and GSON. Can problems arise, if it is possible and I do it it that way?

Thanks in advance!

Edit: Here is the tutorial where I read about POJOs for GSON: tutorials point - GSON

答案1

得分: 4

可以做到,但这不是一个好的设计。例如,如果您使用它来序列化 REST 接口数据,那么它将使您的 REST 端点与数据库紧密耦合,或者可能导致安全问题(序列化敏感数据)等。因此,它可能会导致紧密耦合,并且以后要将其解耦会更加困难。最好是为数据库和其他接口创建单独的模型。您可以使用映射库(例如 MapStruct)在模型之间进行映射。

英文:

It is possible, but it is not a good design. If you use it for example serialize rest interface data, then it will hard couple your rest endpoint with database or it can lead for security issues (serialize sensitive data) etc. So it can lead hard coupling, and will be harder to decouple it latter. It is always good to create separate model to db and other interfaces. You can use mapping libraries (for example mapstuct) to mapping between the models easily.

答案2

得分: 1

你实际上不应该根据我们使用的库(GSON 或 Jackson API)来设计实体类或 POJO 类。

你可以在这里查阅详细的解释。
https://www.geeksforgeeks.org/convert-java-object-to-json-string-using-jackson-api/

英文:

You actually should not design Entity or POJO class based on which library we use ( GSON or Jackson API).

You can refer here for a clear explanation.
https://www.geeksforgeeks.org/convert-java-object-to-json-string-using-jackson-api/

huangapple
  • 本文由 发表于 2020年6月29日 16:24:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/62633990.html
匿名

发表评论

匿名网友

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

确定