import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.yss.capital.core.api.sql.service.ISQLExecuteService; import lombok.extern.slf4j.Slf4j; import net.oschina.j2cache.cache.support.util.SpringUtil; import org.hibernate.query.internal.NativeQueryImpl; import org.hibernate.transform.Transformers; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.Query; import java.util.List; @Service @Slf4j @Transactional(readOnly = true) public class SQLExecuteServiceImpl implements ISQLExecuteService { @Override public JSONArray executeSql(String sql) { //封装返回的json数组对象 JSONArray jsonArray = new JSONArray(); try{ //创建数据库操作实体 EntityManager entityManager = SpringUtil.getBean(EntityManager.class); //执行数据库的查询操作 Query query = entityManager.createNativeQuery(sql); //将查询结果转换成mq对象即键值对模式 query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); List resultList = query.getResultList(); jsonArray = JSONArray.parseArray(JSON.toJSONString(resultList)); log.info("自定义sql查询结果为:"+jsonArray.toJSONString()); }catch (Exception exception){ log.error("当前执行自定义sql语句失败,sql内容为【"+sql+"】"); } // 将返回结果转成JSON数组 return jsonArray; } }
JPA定义自定义sql返回JSONArray形式的结果
于 2022-05-30 16:53:58 首次发布