javajpaejbentity-bean

Is it a good practice to embed behavior into Entity Beans?


While my Java apps were small and did simple things, I was quite happy using plain SQL, all the more that application servers like Glassfish make connection management really easy. After I learned about JPA and EJB, I decided to refactor my projects to make them use these cool things, but faced an issue that is more about design than programming:

Is it a good practice to embed behavior into Entity Beans, or they should only hold data?

I've read many manuals and tutorials, but they mostly answer how I can use them, not how I should, to meet good-design requirements.

For example, given 2 classes: User and Location, they are both entity beans. A user can store collection of locations, and it's OK and easy to implement using JPA. But if I want to populate these classes with some functionality, such as methods for calculating distance to another user or location, finding their paths intersections, calculating distance that a user ran over a day, and so on. Would it be a "good design" if I implement such functionality in beans themselves or I should use special decorators and helper classes with plenty of static methods to achieve my goal?


Solution

  • You are trying to implement a Domain Driven (DD) approach. It is useful for some applications, but tends to be opposed to SOA architectures. SOA concepts are widespread, highly proven and even it's a hot topic right now, see also microservices (a.k.a SOA v2.0)

    If you are using Java EE, you can use a Gateway pattern to implement DD or Boundary-Control-Entity for SOA.

    Now some points:

    I hate how bad endemic models looks, but well, at least works.