欢迎访问我的个人网站==》 jiashubing.cn

如何使用JPQL写纯SQL语句

  使用JPQL,需要把SQL语句修改成类似HQL 语句。SQL 查询的是数据库,而JPQL 查询的是对象和属性,在语法上是有些不同的。对于有些用JPQL 无法写出来的查询,还是使用原生SQL写出来方便

  以下给出一个例子,注意语法的区别:

JPQL查询

@PersistenceContext
protected EntityManager em;

public List<Video> findVideoList1() {
  String hql = "from Video order by id desc";
  Query query = em.createQuery(hql);
  List<Video> result = query.getResultList();
  em.clear();
  return result;
}

SQL查询

查询最近7天的数据

public List<Video> findVideoList2() {
  List<Video> result = (List<Video>) em.createNativeQuery
    ("select * from db_video where date_sub(curdate(), interval 6 day) <= date(date) order by date desc", Video.class)
    .getResultList();
  return result;
}

 

原创文章,欢迎转载,转载请注明出处!

posted @ 2018-01-27 10:41  贾树丙  阅读(1400)  评论(0编辑  收藏  举报