环境与上一偏的环境一样
SQL : 对数据库 表的 与表的字段 操作 JPQL : 对java 实体类的 与类的 属性操作
操作步骤: 1.通过工具类获得实体管理器 2.通过实体管理器获得事务管理器 开启事务 3.编写jpql语句
4.获得 Query 对象 执行jpql语句 5.使用getResultList()获得结果集 getSingleResult(); 获得单一结果
1.查询全部
" from Customer"
@Testpublic void testFindAll() {//1.获取entityManager对象EntityManager em = JpaUtils.getEntityManager();//2.开启事务EntityTransaction tx = em.getTransaction();tx.begin();//3.查询全部String jpql = "from Customer ";Query query = em.createQuery(jpql);//创建Query查询对象,query对象才是执行jqpl的对象//发送查询,并封装结果集List list = query.getResultList();for (Object obj : list) {System.out.print(obj);}//4.提交事务tx.commit();//5.释放资源em.close();}
2.排序查询:
倒序查询全部客户(根据id倒序) sql:SELECT * FROM cst_customer ORDER BY cust_id DESC
jpql:from Customer order by custId desc
@Testpublic void testOrders() {//1.获取entityManager对象EntityManager em = JpaUtils.getEntityManager();//2.开启事务EntityTransaction tx = em.getTransaction();tx.begin();//3.查询全部String jpql = "from Customer order by custId desc";Query query = em.createQuery(jpql);//创建Query查询对象,query对象才是执行jqpl的对象//发送查询,并封装结果集List list = query.getResultList();for (Object obj : list) {System.out.println(obj);}//4.提交事务tx.commit();//5.释放资源em.close();}
统计客户的总数
sql:SELECT COUNT(cust_id) FROM cst_customer jpql:select count(custId) from Customer 类中的属性
@Testpublic void testCount() {//1.获取entityManager对象EntityManager em = JpaUtils.getEntityManager();//2.开启事务EntityTransaction tx = em.getTransaction();tx.begin();//3.查询全部//i.根据jpql语句创建Query查询对象String jpql = "select count(custId) from Customer";Query query = em.createQuery(jpql);//ii.对参数赋值//iii.发送查询,并封装结果Object result = query.getSingleResult();System.out.println(result);//4.提交事务tx.commit();//5.释放资源em.close();}
分页查询
jqpl : from Customer sql:select * from cst_customer limit 0,2
每页查询的条数设置 : query.setFirstResult(0); query.setMaxResults(2);
@Testpublic void testPaged() {//1.获取entityManager对象EntityManager em = JpaUtils.getEntityManager();//2.开启事务EntityTransaction tx = em.getTransaction();tx.begin();//3.查询全部//i.根据jpql语句创建Query查询对象String jpql = "from Customer";Query query = em.createQuery(jpql);//ii.对参数赋值 -- 分页参数//起始索引query.setFirstResult(0);//每页查询的条数query.setMaxResults(2);//iii.发送查询,并封装结果List list = query.getResultList();for(Object obj : list) {System.out.println(obj);}//4.提交事务tx.commit();//5.释放资源em.close();}
条件查询
jpql: from Customer where custName like ? sql:SELECT * FROM cst_customer WHERE cust_name LIKE ?
设置参数:索引,值 query.setParameter(1,"传智播客%");
@Testpublic void testCondition() {//1.获取entityManager对象EntityManager em = JpaUtils.getEntityManager();//2.开启事务EntityTransaction tx = em.getTransaction();tx.begin();//3.查询全部//i.根据jpql语句创建Query查询对象String jpql = "from Customer where custName like ? ";Query query = em.createQuery(jpql);//ii.对参数赋值 -- 占位符参数//第一个参数:占位符的索引位置(从1开始),第二个参数:取值query.setParameter(1,"传智播客%");//iii.发送查询,并封装结果List list = query.getResultList();for(Object obj : list) {System.out.println(obj);}//4.提交事务tx.commit();//5.释放资源em.close(); }