1.抽取JPAUtil工具类
public final class JPAUtil {
private static EntityManagerFactory em;
static {
em = Persistence.createEntityManagerFactory("myJpa");
}
public static EntityManager getEntityManager() {
return em.createEntityManager();
}
}
2.使用JPA完成增删改查操作
2.1.保存
@Test
public void testAdd() {
Customer c = new Customer();
c.setCustName("JAVA学院");
c.setCustLevel("VIP客户");
c.setCustSource("网络");
c.setCustIndustry("IT教育");
c.setCustAddress("北京XXX学院");
c.setCustPhone("010-843242X0");
EntityManager em = null;
EntityTransaction tx = null;
try {
em = JPAUtil.getEntityManager();
tx = em.getTransaction();
tx.begin();
em.persist(c);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
em.close();
}
}
2.2.修改
@Test
public void testMerge(){
EntityManager em=null;
EntityTransaction tx=null;
try{
em=JPAUtil.getEntityManager();
tx=em.getTransaction();
tx.begin();
Customer c1 = em.find(Customer.class, 1L);
System.out.println(c1);
c1.setCustName("JAVA培训学院");
em.clear();
em.merge(c1);
tx.commit();
}catch(Exception e){
tx.rollback();
e.printStackTrace();
}finally{
em.close();
}
}
2.3.删除
@Test
public void testRemove() {
EntityManager em = null;
EntityTransaction tx = null;
try {
em = JPAUtil.getEntityManager();
tx = em.getTransaction();
tx.begin();
Customer c1 = em.find(Customer.class, 2L);
em.remove(c1);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
em.close();
}
}
2.4.根据id查询
@Test
public void testGetOne() {
EntityManager em = null;
EntityTransaction tx = null;
try {
em = JPAUtil.getEntityManager();
tx = em.getTransaction();
tx.begin();
Customer c1 = em.find(Customer.class, 1L);
tx.commit();
System.out.println(c1);
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
em.close();
}
}
2.5.查询实体的缓存问题
@Test
public void testGetOne1() {
EntityManager em = null;
EntityTransaction tx = null;
try {
em = JPAUtil.getEntityManager();
tx = em.getTransaction();
tx.begin();
Customer c1 = em.find(Customer.class, 1L);
Customer c2 = em.find(Customer.class, 1L);
System.out.println(c1 == c2);
tx.commit();
System.out.println(c1);
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
em.close();
}
}
2.6.延迟加载策略的方法
@Test
public void testLoadOne() {
EntityManager em = null;
EntityTransaction tx = null;
try {
em = JPAUtil.getEntityManager();
tx = em.getTransaction();
tx.begin();
Customer c1 = em.getReference(Customer.class, 1L);
tx.commit();
System.out.println(c1);
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
em.close();
}
}