重用多个存储库标准的最佳方法是什么? [英] What is the best approach to reuse multiple repository criterias?

查看:233
本文介绍了重用多个存储库标准的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储库层,它有许多方法组合,以匹配搜索标准。重用此标准的最佳方法是什么?我认为像findByNameAndIdAndBirthdayAndAccounaNumber这样的方法名称并不是一个好主意!谢谢!

I have an repository layer that have many methods combination, to match search criterias.. What is the best approach to reuse this criterias? I think that methods name like findByNameAndIdAndBirthdayAndAccounaNumber is not a good idea ! Thanks !

public Order findByIdAndName(String orderId) {
List<OrderEntity> list = entityManager.createNamedQuery(OrderEntity.QUERY_FIND_BY_ORDERID_AND_NAME,     OrderEntity.class)
     .setParameter("orderId", orderId)
     .setParameter("name", name).getResultList();
if (list.isEmpty()) {
    return null;
}

OrderEntity orderEntity = list.get(0);

return toOrder(orderEntity);

}

推荐答案

听起来你可能正在寻找规范模式,它允许你编写一个方法,如:

Sounds like you may be looking for the Specification pattern which would allow you write a method like:

public Order findOrderBySpecification(Specification specification) {

}

然后使用a调用一个或多个规范的组合,例如按帐号,帐号和姓名等。

and then call this using a combination of one or more specifications e.g. by account number, by account number and name etc.

这里有一个使用Criteria API的例子:

There is an example here using the Criteria API:

http://java.dzone.com/articles/java-using-specification

另请参阅下面的文章,该文章引用了Spring Data项目,但即使您不使用Spring,也可能值得一读。

See also the article below which refers to the Spring Data project but which is probably worth a read anyway even if you are not using Spring.

http://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

此外,您可以更简单地使用上面文章中引用的QueryDSL库而不是使用Straight JPA的相当冗长的Criteria API(即没有Spring)来实现这一点。

Also, you can achieve this more simply using the QueryDSL library referenced in the article above rather than the rather verbose Criteria API with Straight JPA (i.e. without Spring).

http://blog.mysema .com / 2010/04 / querydsl-as-alternative-to-jpa-2.html
http://www.querydsl.com/static/querydsl/2.1.0/reference/html/ch02s02.html

这篇关于重用多个存储库标准的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆