简体   繁体   中英

What is an elegant way to express a query with a Search Bean?

In our project we have a bean, but we also want to express standard CRUD queries on that bean. We want to be able to filter on certain fields (ranges, equalities, exclusions, etc.). Right now we were thinking to use a SearchBean which would represent such a set of filters. However we realize that this search bean is almost identical to our actual bean, and we are having a tough time coming up with a more elegant solution.

What is a good way to approach this problem? We are not looking for any framework-specific solutions.

Assuming you want to handle it in the application server. You might consider using either guava collections

http://scaramoche.blogspot.com/2010/08/googles-guava-library-tutorial-part-4.html

or CollectionUtils

http://commons.apache.org/collections/apidocs/org/apache/commons/collections/CollectionUtils.html#filter%28java.util.Collection,%20org.apache.commons.collections.Predicate%29

and the BeanPredicate from BeanUtils

http://commons.apache.org/beanutils/v1.8.2/apidocs/org/apache/commons/beanutils/BeanPredicate.html

You will have to implement Predicate classes for the type of filters you want to support.

I'm afraid this question is just too open ended to give a good answer. It really depends on what your goals are. Also, you haven't explicitly mentioned that you're using a database (as opposed to searching memory) but I'm assuming you are.

Your approach (findEntitiesLikeMe) sounds like a nice and simple approach.

There are plenty of query languages out there (JPQL/SQL/etc.) that you could implement (either by sanitizing the query and passing it to a lower layer or by parsing the query directly).

If your server structure is sufficiently tree-like you could take in XPath's and return the object space that matches the XPath.

All three of these approaches give you ranges, equalities, and exclusions. My advice would be to keep it simple (what you have sounds fine) until it breaks down (either due to performance, or complicated client side APIs, or lack of flexibility) and then change to something better.

Ultimately a full-fledged query language is probably going to give you the most flexibility but can be the most difficult to implements especially if you're parsing the query and not passing it down to a lower layer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM