Nikolai
Nikolai

Reputation: 83

The best way to translate Entity Objects to POJO and vice versa?

That's what I have seen on one project: JPA Entity classes are used to persist objects to DB. But when we create Jersey endpoints, we normally consume and produce JSON. So, some kind of POJO's are used to represent the data we want send or receive.

So, every time a Jersey request is processed, "assembler" class is used to assemble a POJO from an entity object (or vice versa). So, the flow is something like this. Entity Object -> assembler service -> JSON.

Now I am starting a new project, and I am not sure if this approach is the best one. From one point of view, it allows to control what I want to return as a JSON and separates these representations from the persistence classes. On the other hand, it looks like an extra layer to me which can be avoided.

Is there a way to make this translation easier (maybe automatically)?

UPDATE: Thanks for answers. But POJO to JSON mapping is done by Jersey automatically. What I really wanted to know, is if there is a good way to map entity class (Java classes with JPA/Hibernate annotations) to JSON without using intermediate POJOs?

Upvotes: 6

Views: 9420

Answers (1)

jhyot
jhyot

Reputation: 3955

You can use what are sometimes called Projections. If there are fields on the entities that you don't want to expose on the REST API, you can implement an interface in the entity which only has a subset of the getters, and you then serialize only those parts to json.

You can have a look at Spring Data REST and how it's done there.

Upvotes: 3

Related Questions