Spring Data JPA是一个很棒的项目,可以为您生成DAO,甚至更多!你只需要创建一个接口(没有任何实现):
interface PaymentMethodsDao extends JpaRepository<PaymentMethods, Integer> {}
这个接口(通过继承的JpaRepository
)将自动为您提供:
PaymentMethod save(PaymentMethod entity);
Iterable<PaymentMethod> save(Iterable<? extends PaymentMethod> entities);
PaymentMethod findOne(Integer id);
boolean exists(Integer id);
Iterable<PaymentMethod> findAll();
long count();
void delete(Integer id);
void delete(PaymentMethod entity);
void delete(Iterable<? extends PaymentMethod> entities);
void deleteAll();
Iterable<PaymentMethod> findAll(Sort sort);
Page<PaymentMethod> findAll(Pageable pageable);
List<PaymentMethod> findAll();
List<PaymentMethod> findAll(Sort sort);
List<PaymentMethod> save(Iterable<? extends PaymentMethods> entities);
void flush();
PaymentMethod saveAndFlush(PaymentMethods entity);
void deleteInBatch(Iterable<PaymentMethods> entities);
该接口是强类型(泛型)并自动为您实现的。对于每个实体,您所要做的就是创建一个扩展的接口。JpaRepository<T,Integer extends Serializable>
但是等等,还有更多!假设您有和持久字段。如果将以下方法添加到接口中:PaymentMethod
name
validSince
interface PaymentMethodsDao extends JpaRepository<PaymentMethods, Integer> {
Page<PaymentMethod> findByNameLikeAndValidSinceGreaterThan(
String name, Date validSince, Pageable page
);
}
框架将解析方法名称:
findBy
(名称 like) (有效大于)And
创建 JPA QL 查询,应用分页和排序 () 并为您运行它。无需实现:Pageable page
paymentMethodsDao.findByNameLikeAndValidSinceGreaterThan(
"abc%",
new Date(),
new PageRequest(0, 20, Sort.Direction.DESC, "name"
);
结果查询:
SELECT * //or COUNT, framework also returns the total number of records
FROM PaymentMethods
WHERE name LIKE "abc%"
AND validSince > ...
并应用了分页。
唯一的缺点是该项目相当新,并且相对容易击中但是(但它非常积极地开发)。