Search code examples
javaspringhibernatespring-bootspring-data-jpa

Is it good idea to use the DAO design pattern with spring Boot, instead of using repository design pattern provided by spring data jpa?


Actually, I'm new on spring Boot but I've been using Spring for a little while. With spring, I used to handle my database(MySQL) through a generic DAO with hibernate/JPA. However all the tutorials I found on spring Boot use spring data jpa making, therefore, configurations easier.

Thus I would like to know whether it is or not a good idea to keep using my old generic DAO, as it allows me to have the full control and to customize my data access as I want. If yes, how can I proceed? If not, what can be the disadvantages?


Solution

  • The DAO pattern is the same as the Repository Pattern that Spring Data supports. At least, it should be. You have one DAO (=Repository) class per entity that provides methods to query or manipulate that entity.

    whether It is or not a good idea to keep using my old generic DAO, as it allows me to have the a full control and to customize my data access as I want.

    Spring Data is flexible enough to allow full control over your queries. You have the following options (code examples copied from the Spring Data reference):

    • Using method names: You can simply name your repository methods like this to let Spring Data auto-generate a query for you:

      List<User> findByEmailAddressAndLastname(String emailAddress, String lastname); 
      
    • Using custom queries per annotation: Provide a custom JPAQL query within a @Query annotation

      @Query("select u from User u where u.emailAddress = ?1")
      User findByEmailAddress(String emailAddress); 
      
    • Using named queries: define a named JPAQL query within an xml file and reference it within the @Query annotation

      <named-query name="User.findByLastname">
        <query>select u from User u where u.lastname = ?1</query>
      </named-query>
      
      @Query(name="User.findbyLastname")
      List<User> findByLastname(String lastname);
      
    • Implement a repository method yourself: provide part of the implementation of a Spring Data repository yourself by accessing the Hibernate session (or that of another JPA provider) yourself.

    So, to answer your question: yes, use Spring Data JPA, especially on new projects! It does so much work for you and you can still control queries as you wish (which should only be necessary for complicated queries, and even for those I would suggest using programmatic Specifications).