Spring/roo custom finder

情到浓时终转凉″ 提交于 2019-12-04 16:42:35

Well, going the old fashioned way... The Servlets standard in Java defines object Request where there is Map (hash, dictionary) with the parameters, so you could access them something like

public ModelAndView searchAssets(HttpRequest request) {
    StringBuilder builder = new StringBuilder();
    for (String param : request.getParameterNames()) {
        value = request.getParameter(param);
        builder.append(param);
        builder.append("="); // or LIKE
        builder.append("\'" + value "\'");
        builder.append(" AND ");
    }
    // deleting the last " AND "
    builder.delete(builder.length-5, builder.length);
    // In the entity create a method that executes a query with the string
    // If the parameter names are column names then you'd have to use a nativeQuery
    // You'd have to look it up in JPA
   List<Asset> list = Asset.search(builder.toString());
   // put the list in the ModelAndView
}

I made a comment, but I prefer to explain my approach in an answer:

I think it's better to create a custom finder as Raloh said below (using the code generated by Roo) using a POJO as parameter instead of WebRequest, in order to not have dependencies with the MVC.

Try to create a POJO, AssetFilter, for instance, containing the attributes you want to use in the finder.

public static TypedQuery<Asset> findAssetsByFilter(AssetFilter filter) {
    If (filter.getManufacturer()!=null) where.append(" AND ...")
}

The Controller will create the POJO filter with the Request, and you can use this finder everywhere, you can even create an integration test for it.

Spring roo can generate the finders for you:

type:

finder list --class ~.domain.MyClass   
finder add --finderName findMyClassByWhatEver

finder list will list all finder with one attribute, you can set the number of attributes with an optional parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!