jpadomain-driven-designanemic-domain-model

Adding business logic to JPA entities


Having the next scenario, where I have to apply some static filters with JPA specifications(add WHERE clauses) to a JPA entity to get a list of dogs filtered for example, I receive an id from an entity and I have to apply the same filters but send error messages for each filter not accomplished. For example: having entity Dog, I receive an id, get this entity with JPA and apply some filters like dog age>3 years, etc...

My idea is to reuse the JPA specifications in order to do it but using them will not give me information about why I am not getting the entity and which filter has been not accomplished in order to send the error message.

What I have done is to add methods like isDogOlderThan3Years() to the JPA entity and the entity itself asks for its attributes and so on for each of the filters. I think it has to do with non anemic entities. Is this a good/bad solution? Is there a better one?

Thanks


Solution

  • I think the specification pattern could be useful here.

    You could use the Visitor pattern to translate specification compositions to JPA queries and you could implement the remainderUnsatisfied operation discussed in the above article to find out which criterias were not met by a given candidate.

    If you do not care about separation of concerns, you can implement toJpaFilter, describe, etc. methods directly on the specifications .

    I've used that approach in a project of mine where I managed to reuse the same specifications to do the following and it worked pretty well: