package com.atguigu.jpa.test;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.hibernate.ejb.QueryHints;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.atguigu.jpa.helloworld.Category;
import com.atguigu.jpa.helloworld.Customer;
import com.atguigu.jpa.helloworld.Department;
import com.atguigu.jpa.helloworld.Item;
import com.atguigu.jpa.helloworld.Manager;
import com.atguigu.jpa.helloworld.Order;
public class JPATest {
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
private EntityTransaction transaction;
@Before
public void init(){
entityManagerFactory = Persistence.createEntityManagerFactory("jpa-1");
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction();
transaction.begin();
}
@After
public void destroy(){
transaction.commit();
entityManager.close();
entityManagerFactory.close();
}
// JPQL UPDATE DELETE .
@Test
public void testExecuteUpdate(){
String jpql = "UPDATE Customer c SET c.lastName = ? WHERE c.id = ?";
Query query = entityManager.createQuery(jpql).setParameter(1, "YYY").setParameter(2, 12);
query.executeUpdate();
}
// jpql
@Test
public void testJpqlFunction(){
String jpql = "SELECT lower(c.email) FROM Customer c";
List emails = entityManager.createQuery(jpql).getResultList();
System.out.println(emails);
}
@Test
public void testSubQuery(){
// Customer lastName YY Order
String jpql = "SELECT o FROM Order o "
+ "WHERE o.customer = (SELECT c FROM Customer c WHERE c.lastName = ?)";
Query query = entityManager.createQuery(jpql).setParameter(1, "YY");
List orders = query.getResultList();
System.out.println(orders.size());
}
/**
* JPQL HQL .
*/
@Test
public void testLeftOuterJoinFetch(){
String jpql = "FROM Customer c LEFT OUTER JOIN FETCH c.orders WHERE c.id = ?";
Customer customer =
(Customer) entityManager.createQuery(jpql).setParameter(1, 12).getSingleResult();
System.out.println(customer.getLastName());
System.out.println(customer.getOrders().size());
// List