JPA多表查询 自写SQL

JPA操作SQL的几种方式

最近在使用Jpa写项目,随便记录一下几种操作SQL的方式,以下是我用的的几种方式。

第一种继承CrudRepository 直接用它里面的方法 如添加:

/*
  * 添加 setYlfwjgid((long) 1) 默认医疗机构1
  */
 @Transactional
 public void saveGhhl(MzGhhl mzGhhl) {
       Long id = idGeneratorUtil.generatorId(mzGhhl);
       SessionUser sessionUser = SessionUtil.getSessionUser();
       mzGhhl.setYlfwjgid(Long.valueOf(sessionUser.getYlfwjgid()));
       mzGhhl.setAid(id);
       mzGhhl.setSid(id);
       mzGhhl.setJlzt(1);
       if ("".equals(mzGhhl.getPym())) {
         mzGhhl.setPym(hzzkService.getPym(mzGhhl.getMc()));
       }
       if ("".equals(mzGhhl.getWbm())) {
         mzGhhl.setWbm(hzzkService.getWbm(mzGhhl.getMc()));
       }
        mzGhhlRepository.save(mzGhhl);
 }

mzGhhlRepository继承了CrudRepository直接调用Save方法并传入对象即可。
还有一种方式就是自己在Repository写SQL如


@Modifying
    @Query(value = "update MzGhlb set jlzt = 0  where sid in (?1)")
    void removeById(Long sid);
 

@Query(value=“SQL语句”)
不过有些时候使用源代码所提供的方法不能达到自己的需求,如多表查询

public List findAll(RequestMessageTemplete reqt) throws Exception {
  StringBuffer sql = new StringBuffer("select p.* , d.bh as hfbh, d.mc as hfmc from tMZ_GHLB as p , tMZ_GHHF as d where p.hfid = d.sid and p.jlzt = 1 \n");
        StringBuffer numsql = new StringBuffer("select count(*) n  from (\n");
        List<Condition> conditions = reqt.getConditions();
        List<Object> value = new ArrayList<>();
        for (Condition c : conditions) {
            if ("mc".equals(c.getName())) {
                sql.append("and p.mc like ?");
                value.add("%" + c.getValue() + "%");
            }
        }
        Map page = getPageAbleMap(reqt);
        sql.append(" order by p." + page.get("sortFiled"));
        sql.append(" " + page.get("sortType").toString());
        numsql.append(sql.toString() + ") as t");
        int num = Integer.valueOf(commonRepository.findSqlPageCall(numsql.toString(), value).get(0).get("n").toString());
        reqt.setQueryResponse(num);
        return commonRepository.findSqlPageCall(sql.toString(), (Integer) page.get("pageNo"), (Integer) page.get("pageSize"), value);
 }
新建一个SQL语句  然后调用commonRepository的方法(commonRepository工具类在下面有源码(包含模糊查询(可以多个),分页,排序等))但是改写法不安全(拼接参数) 应该先用?占位 在参入参数  
 /**
  * @Description:TODO
  *  @time:2018年12月27日 下午2:55:22
  * /
  @Component
  public class CommonRepository {
  /**
   * @Description: entityManager : TODO(EntityManager)
   */
   @PersistenceContext
   private EntityManager entityManager;
   /**
    * @param  list 参加
    * @return List>
    */
 public List<Map<String, Object>> findSqlCall(String sql, Object...list) {
     Query query = entityManager.createNativeQuery(sql);
     query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
     if (list != null && list.length > 0) {
     for (int i = 0; i < list.length; i++) {
        query.setParameter(i + 1, list[i]);
       }
      }
       return query.getResultList();
    }
        /**
        * @param sql sql
        * @param pageSize 每页长度
        * @return List>
        */
  public List<Map<String, Object>> findSqlPageCall(String sql, Integer page, Integer pageSize, Object... list) {
     Query query = entityManager.createNativeQuery(sql);
     query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
     query.setFirstResult((page) * pageSize);
     query.setMaxResults(pageSize);
     if (list != null && list.length > 0) {
       for (int i = 0; i < list.length; i++) {
         query.setParameter(i + 1, list[i]);
        }
      }
        return query.getResultList();
     }
       /**
       * @param sql      sql
       * @param page     当前页
       * @param pageSize 每页长度
       * @param list     参数
       * @return List>
       */
public List<Map<String, Object>> findSqlPageCall(String sql, Integer page, Integer pageSize, List<Object> list) {
   Query query = entityManager.createNativeQuery(sql);
   query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
   query.setFirstResult((page) * pageSize);
   query.setMaxResults(pageSize);
   if (list != null && list.size() > 0) {
    for (int i = 0; i < list.size(); i++) {
       query.setParameter(i + 1, list.get(i));
      }
     }
     return query.getResultList();
   }
     
     /*
     * @param sql      sql
     * @param list     参数
     *  @return List>
     * */
public List<Map<String, Object>> findSqlPageCall(String sql,  List<Object> list) {
   Query query = entityManager.createNativeQuery(sql);
   query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
   if (list != null && list.size() > 0) {
    for (int i = 0; i < list.size(); i++) {
      query.setParameter(i + 1, list.get(i));
        }
       }
      return query.getResultList();
     }
    }

你可能感兴趣的:(JPA多表查询 自写SQL)