JPA 中 sql 预编译 -- EntityManager 使用 预编译

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。

实现方式 :

1. 注入em:

  @PersistenceContext
    private EntityManager entityManager;

注入方式 2:

  @PersistenceUnit
    private EntityManagerFactory emf;

 

2. 得到em:

 private EntityManager getEm() {
        return this.entityManager;
 }

对应第2种注入方式:

  /**
     * 得EntityManager
     *
     * @return
     */
    private EntityManager getEm() {
        return emf.createEntityManager();
    }

3.预编译写法:

   EntityManager em = getEm();
   String getAllTask = "SELECT ID,DEPARTMENT,WBS,CODE,NAME,PARENT_CODE FROM GAEI_WORK_TASK" +
                    " WHERE WBS = ? AND DEPARTMENT = ? ";
            Query query = em.createNativeQuery(getAllTask);
            query.setParameter(1, wbs);
            query.setParameter(2, ((Department) userService.getSecondDepartmentByUserId(uid)).getId());
            List<Object> taskList = query.getResultList();

4. 附上原本查询写法:( 建议参数都改为走预编译 )

 String sql = " SELECT" +
                    " pro.id," +
                    " pro.CODE," +
                    " pro.PROJECT_NAME," +
                    " pro.PROJECT_DIRECTOR_NO 'PROJECT_DIRECTOR_NO.id'," +
                    " pro.source," +
                    " gaei_pro.WBS," +
                    " app_user.fullname 'PROJECT_DIRECTOR_NO.fields'," +
                    " gaei_pro.STATUS" +
                    " FROM" +
                    " GAEI_PROJECT pro" +
                    " LEFT JOIN appbricks_user app_user ON gaei_pro.PROJECT_DIRECTOR_NO = app_user.id" +
                    " WHERE app_user.id = '" + approveId + "'" +
                    " ORDER BY pro.CODE ASC";

            List<Object> resultList = getResultList(em, sql);

 

 // 执行查询
    public static <T> List<T> getResultList(EntityManager em, String sql) {
        List<T> resultList = em.createNativeQuery(sql).getResultList();
        return resultList;
    }



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值