Exposing Hibernate criteria via service API

前端 未结 6 1159
鱼传尺愫
鱼传尺愫 2021-02-04 14:14

This is more of a design than implementation question and it\'s going to be long so bear with me. It\'s best explained with an example:

Let\'s say I have a business

6条回答
  •  青春惊慌失措
    2021-02-04 15:03

    The actual solution I've implemented uses a hybrid approach.

    Methods that use well-defined queries (e.g. methods that are used internally by other services, predefined reports, etc.) have signature similar to HibernateTemplate's findBy methods:

    public List findEntities(String queryName, QueryParameters parameters);
    

    where QueryParameters is a convenience class for specifying named parameters explicitly or taking them from a bean. Sample usage is:

    List products = findProducts("latestUpdates",
     new QueryParameters()
      .add("vendor", "Oracle")
      .add("price", "50.0")
    );
    

    or

    List products = findProducts("latestUpdates",
     new QueryParameters(product, "vendor", "price"));
    

    Access to such methods is limited to "trusted" code; queries used obviously must obviously be defined in Hibernate mappings. Filters are built into query or defined as session filters. The benefits are cleaner code (no Criteria-like stuff spread across half a page) and clearly defined HQL (easier to optimize and deal with cache if necessary).


    Methods that are exposed to UI or otherwise need to be more dynamic use Search interface from Hibernate-Generic-DAO project. It's somewhat similar to Hibernate's DetachedCriteria but has several advantages:

    1. It can be created without being tied to particular entity. It's a big deal for me because entity interface (part of API visible to users) and implementation (POJO mapped in Hibernate) are two different classes and implementation is not available to user at compile time.

    2. It's a well thought out open interface; quite unlike DetachedCriteria from which it's nearly impossible to extract anything (yes, I know DC wasn't designed for that; but still)

    3. Built-in pagination / results with total count / bunch of other little niceties.

    4. No explicit ties to Hibernate (though I personally don't really care about this; I'm not going to suddenly drop Hibernate and go with EclipseLink tomorrow); there are both Hibernate and generic JPA implementations available.

    Filters can be added to Search on service side; that's when entity class is specified as well. The only thing's missing is quick-fail on client side if invalid property name is specified and that can be resolved by writing my own ISearch / IMutableSearch implementation but I didn't get to that yet.

提交回复
热议问题