这里列出了和普通hibernate框架query查询不同的地方的方法,其他的查询方式和query查询一致
package test;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import org.junit.Test;
import bean.Customer;
import utils.JPAUtils;
public class demo2 {
//jpa的查询 JPA方式: 类似query的方式
@Test
//全查
public void t1() {
EntityManager en = JPAUtils.getEntityManager();
EntityTransaction tr = en.getTransaction();
tr.begin();
Query qr = en.createQuery("from Customer");
List<Customer> list = qr.getResultList();//类似于query方式的list()
for (Customer customer : list) {
System.out.println(customer);
}
tr.commit();
en.close();
}
// 条件查
@Test
public void t2() {
EntityManager en = JPAUtils.getEntityManager();
EntityTransaction tr = en.getTransaction();
tr.begin();
Query qr = en.createQuery("from Customer where cust_name like ?");
qr.setParameter(1, "a%");// hibernate对于占位符?是从0开始 JPA是从1开始
List<Customer> list = qr.getResultList();
for (Customer customer : list) {
System.out.println(customer);
}
tr.commit();
en.close();
}
// 聚合查
@Test
public void t3() {
EntityManager en = JPAUtils.getEntityManager();
EntityTransaction tr = en.getTransaction();
tr.begin();
Query qr = en.createQuery("select count(*) from Customer where cust_name like ?");
qr.setParameter(1, "a%");
Object obj = qr.getSingleResult();// hibernate query中 的 uniqueResult()
System.out.println(obj);
tr.commit();
en.close();
}
}