springboot hibernate jpa createNativeQuery using native sql queries and convert to model objects pojo, and easy to use

  • Query jpa first entityManager.createNativeQuery generated strong interface into the query hibernateQuery
  • Then you can call the method to hibernate, set the properties, the result is returned list Map <String, Object> There columnName the column name of the object
  • Then the jackson ObjectMapper (). ConvertValue map to convert an object pojo
  • Like the basic and jdbctemplate
        //normal use, javax.persistence.Query interface
        Query dbQuery = entityManager.createNativeQuery(sql);
        //cast to hibernate query
        org.hibernate.Query hibernateQuery =((org.hibernate.jpa.HibernateQuery)dbQuery)
                .getHibernateQuery();
        hibernateQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);

        List<Map<String,Object>> res = hibernateQuery.list();

        List<TxTestModel> txTestModels = new ArrayList<>();
        res.forEach(e->{
            TxTestModel txTestModel = new ObjectMapper().convertValue(e, TxTestModel.class);
//            txTestModels.add(new TxTestModel().setIdd((Integer) e.get("idd")).setMmm((String) e.get("mmm")).setDdd((Date) e.get("ddd")));
            txTestModels.add(txTestModel);
        });
        System.out.println(txTestModels.size());

Guess you like

Origin blog.csdn.net/c5113620/article/details/93513540