你可以看看Spring Data JPA。它允许您简单地定义一个接口并执行查询,而无需手动实现执行。
实体:
@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;
}
存储 库:
public interface UserRepository extends CrudRepository<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);
}
设置:
EntityManager em = Persistence.getEntityManagerFactory().createEntityManager();
JpaRepositoryFactory factory = new JpaRepositoryFactory(em);
UserRepository repository = factory.getRepository(UserRepository.class);
如您所见,您可以选择不同的方法来派生要从该方法执行的查询。虽然直接从方法名称派生它对于简单的查询是可行的,但你可能会在(JPA标准)或(Spring Data JPA注释)之间进行选择,这取决于你喜欢坚持标准的程度。@NamedQuery
@Query
Spring Data JPA在数据访问层实现的各个其他方面为您提供支持,允许为方法提供自定义实现,并与Spring很好地集成。