You could take a look at project Hades. It allows you to simply define an interface and execute queries without the need to implement the execution manually.
Entity:
@Entity
@NamedQuery(id="User.findByLastname" query="from User u where u.lastname = ?1")
public class User implements Persistable<Long> {
@Id
private Long id;
private String username;
private String lastname;
private int age;
}
DAO:
public interface UserDao extends GenericDao<User, Long> {
// Will trigger the NamedQuery due to a naming convention
List<User> findByLastname(String lastname);
// Will create a query from the methodname
// from User u where u.username = ?
User findByUsername(String username);
// Uses query annotated to the finder method in case you
// don't want to pollute entity with query info
@Query("from User u where u.age > ?1")
List<User> findByAgeGreaterThan(int age);
}
Setup:
EntityManager em = Persistence.getEntityManagerFactory().createEntityManager();
GenericDaoFactory factory = GenericDaoFactory.create(em);
UserDao dao = factory.getDao(UserDao.class);
As you see you can choose between different ways to derive the query to be executed from the method. While deriving it directly from the method name is feasible for simple queries you'd probably choose between the @NamedQuery
(JPA standard) or @Query
(Hades annotation) dependening on how much you like to stick with standards.
Hades gives you support in various other corners of data access layer implementation, allows providing custom implementations for methods and nicely integrates with Spring.