What design pattern should be used to save objects that have similar save shapes?

3

I'm wondering if I'm not mistaken, I've read, seen, or even implemented something like this but I can not remember it, it's the following:

I have here an EJB project with several entities, some of them have very similar ways of saving, for example the Contract and Financial Aid entity, these two (and more others) will implement a list of Competencies and save other basic attributes. The issue is that so I do not have to implement multiple services and multiple DAOs with the same save methods by changing a little thing here or there I think I could have something like a generic service or dao that took the object from any entity and the entity itself was in charge of saving itself.

We try to do with a Factory that creates the dao corresponding to the type of object passed through but I think it is not there yet ... I do not know for sure but maybe even using dependency injection would be much more elegant ... Someone could give a light?

    
asked by anonymous 26.07.2014 / 05:24

1 answer

3

I do not know a project pattern that does this directly. However, there are several techniques to achieve this goal.

Aspect-Oriented Programming (AOP)

The Spring Data JPA project, quoted by @AnthonyAccioly, is an example of using AOP. It allows automatic "generation" of Repositories to interface with the database based on interfaces.

Basically, you declare an interface that extends the JPARepository interface of Spring. All right, Spring does the rest.

By example :

public interface UserRepository extends JpaRepository<User, Long> {

  List<User> findByLastname(String lastname);

  User findByEmailAddress(String emailAddress);
}

Only through the above signatures will Spring be able to provide method implementation and inject a concrete bean wherever you need it.

In addition, the JPARepository interface already comes with several basic methods for CRUDs.

Note that Repository is the name of a project pattern . It is analogous to DAO, the difference is that the DAO interface follows the pattern of a database while the Repository follows the pattern of a Collection .

Generics

This Java language feature is great for this type of task. If there are several classes that are used in almost equal operations and it is not possible or it is not desirable to use polymorphism for this, it is enough to declare a class that performs these operations with the parameterized type.

I will not detail the implementation here, because it would be an extremely long answer. But just search for some already existing implementations.

    
28.07.2014 / 22:47