Exposing Hibernate criteria via service API

前端 未结 6 1149
鱼传尺愫
鱼传尺愫 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 14:37

    It is never a good idea to expose such implementation details. You are bounded to that library from there on. Worse, any api change of the library will couse an api i change of your service. Any security considerations left behind...

    What about bean property names used in critera (a triple of property name, enum with less, equal and more and value). With a bean wrapper on your model, you may transform this to a hibernate criteria.

    It will also be possible to transform this property names to a new version after a model change.

    0 讨论(0)
  • 2021-02-04 14:41

    Hibernate is a low-level infrastructure framework, and as such should remain hidden behind the scenes. If next month your application needs to switch to another ORM framework for some reason, your API will be useless. Encapsulation even between layers within the same application, is vitally important.

    Having said all this, I think your method should receive an abstraction of the information you need to perform the search. I advise you to create an enum of Product's fields, and implement one or two simple versions of Restriction.

    The parameters to the method can be a list of equality restrictions, another list of relative restrictions and of course an order indicator (one of the enum values plus a flag for asc/desc).

    This is just a general direction, I hope I made my point clear =8-)

    0 讨论(0)
  • 2021-02-04 14:49

    I think query by example would work really good here.

    0 讨论(0)
  • 2021-02-04 14:53

    Option One: If it's possible to expand your API, I suggest making your API "richer" -- adding more methods such as a few below to make your service sound more natural. It can be tricky to make your API larger without it seeming bloated, but if you follow a similar naming scheme it will seem natural to use.

    productService.findProductsByName("Widget")
    productService.findProductsByName(STARTS_WITH,"Widg")
    productService.findProductsByVendorName("Oracle")
    productService.findProductsByPrice(OVER,50)
    

    Combining the results (applying multiple restrictions) could be left as something for the clients to do after they received the result set by using CollectionUtils and Predicates. You could even build a few common Predicates for the consumers of your API just to be nice. CollectionUtils.select() is fun.

    Option Two: If it is not possible to expand the API, your third bullet is the one I would go with.

    • Write my own QueryCriteria interface / implementation which will form either DetachedCriteria or HQL behind the scenes...

    You could try to apply a DSL style approach to the naming using something akin to the Builder pattern to make things more readable and natural sounding. This gets a little clumsy in Java with all the dots and parens, but maybe something like:

    Product.Restriction restriction = new Product.Restriction().name("Widget").vendor("Oracle").price(OVER,50) );
    productService.findProducts(restriction);
    

    Option Three: Combine the two approaches, providing a restriction-style criteria along with a richer API. These solutions would be clean in that they hides the Hibernate implementation details from the consumer of your API. (Not that anyone would ever think of switching away from Hibernate.)

    0 讨论(0)
  • 2021-02-04 14:56

    Hmm - interesting question.

    Having thought it over, writing you own criteria interface is probably the way to go. It won't tie you to an implementation and will lower the security concerns.

    Also depending on how many objects are involved have considered returning the whole set of products (with necessary filters applied) then having the end user apply filters with lambdaj or similar. See:

    http://code.google.com/p/lambdaj/

    0 讨论(0)
  • 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<Entity> 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<Product> products = findProducts("latestUpdates",
     new QueryParameters()
      .add("vendor", "Oracle")
      .add("price", "50.0")
    );
    

    or

    List<Product> 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.

    0 讨论(0)
提交回复
热议问题