I started to learn EJB few weeks ago and I've got question about how to reuse entity class on client and server side. Assume that we've got CRUD application.
Those are my suggestions to solve the problem:
What is the best solution? Are my solutions correct? I would be grateful for any suggestions.
If you trust the client or if you don't care if any JPA annotations leak to the client, you can use the JPA entities as data tranfer objects (DTOs). Caveat: Any lazy managed relationships not fetched by the server will be unavailable to the client, may cause exceptions during serialization, or may query and serialize too many things. (This is your option 1)
Alternatively, you may create DTOs for each entity. There may be many DTOs per entity (e.g. a full DTO containing all fields of a forum post, a summary DTO containing only title, date, author). You may use utilities like Commons BeanUtils to reflectively copy from Entity to DTO without writing lots of boilerplate code (dto.setTitle(entity.getTitle()); dto.setDate(entity.getDate()); ...). In this case the DTOs live in a separate JAR, shared by client and server, but the entities live in their own deployment unit and are private to the server. This was the most adverised practice in the old days of EJB 1/2. (This has some similarities to your option 2, but you will be reusing the DTOs instead of the entities themselves)
Then you may expose the server as WEB services or REST endpoints (JAX-WS and JAX-RS make this very easy). With proper configuration it may even be possible to reuse the JPA beans in the client. This has the extra bonus of being interoperable with other technologies, but will probably be slow.
Your option 2 is also viable, but you will add the overhead of maintaining the XML deployment descriptor (XDoclet may be of help in this case, if it supports JPA - haven't used it for many-many years).
When using remoting of any kind, be aware that communication is generally expensive. Therefore remote calls should be as coarse-grained as possible and data exchanged as little as possible (hence the summary DTO mentioned above).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With