Example usage for org.springframework.data.jpa.repository.query QueryUtils createCountQueryFor

List of usage examples for org.springframework.data.jpa.repository.query QueryUtils createCountQueryFor

Introduction

In this page you can find the example usage for org.springframework.data.jpa.repository.query QueryUtils createCountQueryFor.

Prototype

@Deprecated
public static String createCountQueryFor(String originalQuery) 

Source Link

Document

Creates a count projected query from the given original query.

Usage

From source file:me.doshou.admin.monitor.web.controller.JPAQLExecutorController.java

@PageableDefaults(pageNumber = 0, value = 10)
@RequestMapping(value = "/ql", method = RequestMethod.POST)
public String executeQL(final @RequestParam("ql") String ql, final Model model, final Pageable pageable) {

    model.addAttribute("sessionFactory", HibernateUtils.getSessionFactory(em));

    try {/*from w  w w.j ava  2  s  .c  o m*/
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                //1?ql
                try {
                    Query query = em.createQuery(ql);
                    int updateCount = query.executeUpdate();
                    model.addAttribute("updateCount", updateCount);
                    return null;
                } catch (Exception e) {
                }
                //2 ?ql
                String findQL = ql;
                String alias = QueryUtils.detectAlias(findQL);
                if (StringUtils.isEmpty(alias)) {
                    Pattern pattern = Pattern.compile("^(.*\\s*from\\s+)(.*)(\\s*.*)",
                            Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
                    findQL = pattern.matcher(findQL).replaceFirst("$1$2 o $3");
                }
                String countQL = QueryUtils.createCountQueryFor(findQL);
                Query countQuery = em.createQuery(countQL);
                Query findQuery = em.createQuery(findQL);
                findQuery.setFirstResult(pageable.getOffset());
                findQuery.setMaxResults(pageable.getPageSize());

                Page page = new PageImpl(findQuery.getResultList(), pageable,
                        (Long) countQuery.getSingleResult());

                model.addAttribute("resultPage", page);
                return null;
            }
        });
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        model.addAttribute(Constants.ERROR, sw.toString());
    }

    return showQLForm();
}