title: Crud methods in service layer using Spring Data JPA
body: <p>I'm building a small application using Spring and Spring Data JPA and I need to use the CrudRepository methods in the service layer, so I made 2 classes: GenericService and GenericServiceImpl. But I don't know if this is the right or even the best approach.</p>
  
  <p>Here is an example:</p>
  
  <p>POJO:</p>
  
  <pre><code>@Entity
  public class User {
  
    @Id
    private Long id;
  
    private String username;
  }
  </code></pre>
  
  <p>DAO:</p>
  
  <pre><code>public interface UserDAO extends CrudRepository&lt;User, Long&gt; {
    User findOneByUsername(String username);
  }
  </code></pre>
  
  <p>Generic service</p>
  
  <pre><code>public interface GenericService&lt;T, ID extends Serializable&gt; {
    &lt;S extends T&gt; S save(S entity);
  }
  </code></pre>
  
  <p>Service</p>
  
  <pre><code>public interface UserService extends GenericService&lt;User, Long&gt;  {
    User findOneByUsername(String username);
  }
  </code></pre>
  
  <p>Generic service impl.</p>
  
  <pre><code>public class GenericServiceImpl&lt;T, ID extends Serializable&gt; implements GenericService&lt;T, ID&gt; {
  
      @Autowired
      private CrudRepository&lt;T, ID&gt; repository;
  
      @Override
      public &lt;S extends T&gt; S save(S entity) {
          return repository.save(entity);
      }
  }
  </code></pre>
  
  <p>Service Impl.</p>
  
  <pre><code>@Service
  @Transactional
  public class UserServiceImpl extends GenericServiceImpl&lt;User, Long&gt; implements UserService {
  
    @Autowired
    private UserDAO userDAO;
  
    @Override
    public User findOneByUsername(String username) {
      userDAO.findOneByUsername(username);
    }
  }
  </code></pre>