JPA加载,更新,删除

juint中:

static EntityManager em=null;
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        EntityManagerFactory emf=Persistence.createEntityManagerFactory("jpaPU");
        em=emf.createEntityManager();
    }

1.两种方法:

Person person=em.find(Person.class, 1);
已经经过泛型处理。find方法相当于Hibernate里面的get方法。如果没有找到相应数据,就返回null.

Person person=em.getReference(Person.class,2);
如果这条记录不存在,单单这句话执行不会出错(返回代理)。但当使用person.getName()时会报实体不存在的异常。   相当于Hibernate里面的load方法。而且这种方法是延迟加载的。只有当实际访问实体属性时才到数据库中去执行查询。

Person person=em.getReference(Person.class,1);
    em.close();
    System.out.println(person.getName());
   

此句话会报错,因为person的属性其实没有加载出来。

Person person=em.find(Person.class, 1);

em.close();
System.out.println(person.getName());

而这段可以正确执行,因为person在find的时候就已经获取了相应的属性。

2.更新:

先看JPA里面的实体的状态:

新建、托管、游离、删除

处于托管状态下的实体发生的任何改变当实体管理器关闭的时候都会自动更新到数据库。

注意要更新必须要开启事务

em.getTransaction().begin();

Person person=em.find(Person.class, 1);
em.close();
person.setName("tazi00");

以上是不能成功更新的。以下可以修改。

em.getTransaction().begin();
        Person person=em.find(Person.class, 1);
        person.setName("tazi00");
       em.getTransaction().commit();
        em.close();

em.getTransaction().begin();
        Person person=em.find(Person.class, 1);
        em.clear(); //把实体管理器中的所有的实体都变成游离状态
        person.setName("tazi22");
        em.merge(person);
        em.getTransaction().commit();
        em.close();

em.getTransaction().begin();
        Person person=em.find(Person.class, 1);
        em.remove(person); //操作的也必须是持久化状态,或者托管状态的对象
        em.getTransaction().commit();
        em.close();

以下代码会报错

em.getTransaction().begin();
        Person person=new Person();
        person.setId(1);
        em.remove(person);
        em.getTransaction().commit();
        em.close();

java.lang.IllegalArgumentException: Removing a detached instance com.tazi.domin.Person#1

原文地址:https://www.cnblogs.com/tazi/p/2315610.html