三、JPA增删改查常用方法
前言:创建EntityManager对象,需要先创建创建EntityManagerFactory对象
方式一:直接通过persistenceUnitName创建
1 String persistenceUnitName = "Jpa-1"; 2 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
方式二:通过persistenceUnitName和properties一起创建
1 String persistenceUnitName = "Jpa-1"; 2 Map<String, Object> properties = new HashMap<String, Object>(); 3 properties.put("hibernate.show_sql", false); 4 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName, properties);
2.创建一个测试增删改查的JPA项目
1 package com.jtfr.jpa.test; 2 3 import javax.persistence.EntityManager; 4 import javax.persistence.EntityManagerFactory; 5 import javax.persistence.EntityTransaction; 6 import javax.persistence.Persistence; 7 8 import org.junit.After; 9 import org.junit.Before; 10 import org.junit.Test; 11 12 public class JpaTest { 13 14 private EntityManagerFactory entityManagerFactory; 15 private EntityManager entityManager; 16 private EntityTransaction transaction; 17 18 @Before 19 public void create(){ 20 entityManagerFactory = Persistence.createEntityManagerFactory("Jpa-1"); 21 entityManager = entityManagerFactory.createEntityManager(); 22 transaction = entityManager.getTransaction(); 23 transaction.begin(); 24 } 25 26 @Test 27 public void testFind(){ 28 System.out.println("没问题"); 29 } 30 31 @After 32 public void end(){ 33 transaction.commit(); 34 entityManager.close(); 35 entityManagerFactory.close(); 36 } 37 }
3.常用增删改查方法解释
查询方法
find方法:方法调用时,已经发出了sql进行查询
1 @Test 2 public void testFind(){ 3 CustomerJpa customerJpa = entityManager.find(CustomerJpa.class, 100); 4 System.out.println("--------分割线作用:区分确实是find的时候就发出了sql语句---------"); 5 System.out.println(customerJpa.toString()); 6 }
getReference方法:方法调用时,返回的是代理对象,当代理对象使用时候才真正发送sql查询数据库,需要注意“懒加载”问题
1 @Test // 类似Hibernate的load方法 2 public void testGetReference(){ 3 CustomerJpa customerJpa = entityManager.getReference(CustomerJpa.class, 100); 4 System.out.println("返回的是代理对象"+customerJpa.getClass().getName()); 5 System.out.println("--------getReference方法调用的时候没有发sql-------------"); 6 System.out.println(customerJpa.toString()); 7 }
persist方法:方法调用为保存一条数据
1 // 类似 Hibernate 的 save 方法 2 @Test 3 public void testPersist(){ 4 CustomerJpa customerJpa = new CustomerJpa(); 5 customerJpa.setId(300100); 6 customerJpa.setLasName("夕阳游子"); 7 customerJpa.setEmail("23228858@qq.com"); 8 customerJpa.setAge(15); 9 customerJpa.setCreateTime(new Date()); 10 customerJpa.setBirth(new Date()); 11 entityManager.persist(customerJpa); // 注意不能设置 Id 12 }