Reputation: 369
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.
Here is an example:
POJO:
@Entity
public class User {
@Id
private Long id;
private String username;
}
DAO:
public interface UserDAO extends CrudRepository<User, Long> {
User findOneByUsername(String username);
}
Generic service
public interface GenericService<T, ID extends Serializable> {
<S extends T> S save(S entity);
}
Service
public interface UserService extends GenericService<User, Long> {
User findOneByUsername(String username);
}
Generic service impl.
public class GenericServiceImpl<T, ID extends Serializable> implements GenericService<T, ID> {
@Autowired
private CrudRepository<T, ID> repository;
@Override
public <S extends T> S save(S entity) {
return repository.save(entity);
}
}
Service Impl.
@Service
@Transactional
public class UserServiceImpl extends GenericServiceImpl<User, Long> implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public User findOneByUsername(String username) {
userDAO.findOneByUsername(username);
}
}
Upvotes: 8
Views: 19235
Reputation: 566
Yes, you're providing your own impl that's may do custom things while still reusing the Derived queries from Spring JPA's CrudRepository. I've seen that a lot. :) We need to do that if we want to do our own computation before calling the Derived methods. After all, that computation may very well be part of a repository, so it doesn't make sense to put that logic in the service. But in your scenario, if there are no such custom computations, then this indirection isn't needed. As a commenter mentioned, you should directly use the UserDao interface. :)
Upvotes: 0