JPA Query Native SQL Transform VO Object Mode

  • 2021-12-13 08:09:23
  • OfStack

Directory JPA Query Native SQL Conversion VO Object JPA Non-annotated Native sql Query

JPA Query Native SQL Transform VO Object


 List<String> sqlList = RiverCourseSql.getRiverCourseSQLString(new RiverCourseDataQO());
        List<RiverCourseDataVO> riverCourseDataVO = rsvrfsrBDao.executeNativeQuery2Obj(sqlList.get(0), new PageQO(), RiverCourseDataVO.class);

Query sql, and then execute the functional method.


 <E> List<E> executeNativeQuery2Obj(String sql, SortQO sortQO, Class<E> clz);
public <E> List<E> executeNativeQuery2Obj(String sql, SortQO sortQO, Class<E> clz) {
        Query query = this.entityManager.createNativeQuery(sql);
        this.setAliasParameter(query, sortQO);
        ((NativeQueryImpl)query.unwrap(NativeQueryImpl.class)).setResultTransformer(Transformers.aliasToBean(clz));
        List<E> resultList = query.getResultList();
        return resultList;
    }

Some considerations for JPA non-annotated native sql query

BACKGROUND: DDD system has complex aggregation statistics, and it is inconvenient to assemble data by code


import javax.persistence.EntityManager;
import javax.persistence.Query;
@Autowired
private EntityManager entityManager;

Here, it is directly received by user-defined VO, and the result set returned by sql must be a subset of VO, otherwise the assembled data will report errors. To put it bluntly, the fields of sql query results must all correspond to vo, and vo can have redundant fields, but sql results cannot have redundant fields


String sql = "sql";
Query nativeQuery = entityManager.createNativeQuery(sql);

Give sql dynamic transfer parameter setting parameters: = param, note that in after the transfer of arrays, according to the version is not 1, some to add brackets, some do not add, directly transfer data into the line


nativeQuery.setParameter(String var1, Object var2);

This is an out-of-date way to convert sql query results to custom VO

Transformers can be converted into list and vo, and nativeQueryImplementor can also be converted into list and vo


NativeQueryImplementor nativeQueryImplementor = nativeQuery.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(VO.class));
VO vo = new VO();
try {
//  There is a pit here. If the return result is empty, it will report an error. To catch this exception, enter again 1 Step operation 
    vo = (VO)nativeQueryImplementor.getSingleResult();
} catch (EntityNotFoundException e) {
    e.printStackTrace();
    return vo ;
}

That's all for now.


Related articles: