JPQL:Java Persistence Query Language 即java持久化查询语言
jpql和sql查询之间的区别
sql :sql语句中查询的是表和表中的字段
jpql:sql语句中查询的是实体类和实体类中对应的属性
首先建立一个工程,具体的工程我的博客里面有,大家可以去找一下
然后创建test测试类
package com.w.test;
import com.w.entity.Customer;
import com.w.util.JpaUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import java.util.List;
public class TestJpql {
EntityManager entityManager;
EntityTransaction transaction;
@Before
public void before(){
entityManager = JpaUtils.getEntityManager();
transaction = entityManager.getTransaction();
transaction.begin();
}
@After
public void after(){
transaction.commit();
entityManager.close();
}
@Test
public void testFindAll(){
Query query = entityManager.createQuery("from com.w.entity.Customer ");
List<Customer> customers = query.getResultList();
for (Customer customer : customers) {
System.out.println(customer);
}
}
@Test
public void testOrder(){
Query query = entityManager.createQuery("from com.w.entity.Customer ORDER BY cId desc");
List<Customer> customers = query.getResultList();
for (Customer customer : customers) {
System.out.println(customer);
}
}
@Test
public void testCount(){
Query query = entityManager.createQuery("select count(cId) from com.w.entity.Customer ORDER BY cId desc");
Object result = query.getSingleResult();
System.out.println(result);
}
@Test
public void testLimit(){
Query query = entityManager.createQuery("from com.w.entity.Customer ORDER BY cId desc");
//显示多少条
query.setMaxResults(2);
//起始条数
query.setFirstResult(0);
List<Customer> customers = query.getResultList();
for (Customer customer : customers) {
System.out.println(customer);
}
}
@Test
public void testCondition(){
//问号后面的数字表示的是第几个占位符
Query query = entityManager.createQuery("from com.w.entity.Customer where cName like ?1");
query.setParameter(1,"%三%");
//显示多少条
query.setMaxResults(2);
//起始条数
query.setFirstResult(0);
List<Customer> customers = query.getResultList();
for (Customer customer : customers) {
System.out.println(customer);
}
}
}
jpaUtils
package com.w.util;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class JpaUtils {
static EntityManagerFactory factory;
static {
factory = Persistence.createEntityManagerFactory("jpa1");
}
public static EntityManager getEntityManager(){
return factory.createEntityManager();
}
}