Exposing Hibernate criteria via service API

前端 未结 6 1152
鱼传尺愫
鱼传尺愫 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: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.)

提交回复
热议问题