<!--[endif]-->查找对象
1) <!--[endif]-->用find()方法查找对象
1) <!--[endif]-->用find()方法查找对象
- public void getPerson(){
- EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa");
- EntityManager em = factory.createEntityManager();
- //相当于Hibernate中的get方法
- Person person = em.find(Person.class, 1);
- System.out.println(person.getUserName());
- em.close();
- factory.close();
- }
2) <!--[endif]-->用getReference()方法查找对象
- public void getPerson2(){
- EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa");
- EntityManager em = factory.createEntityManager();
- //相当于Hibername中的load方法,延迟加载
- Person person = em.getReference(Person.class, 1);
- System.out.println(person.getUserName());
- em.close();
- factory.close();
- }
find方法相当于Hibernate中的get方法,getReference方法相当于Hibernate中的load方法,具有延迟加载的作用;当查找的对象不存在时,find的方法返回null值,而getReference方法则抛出异常javax.persistence.EntityNotFoundException
2. <!--[endif]-->更新对象
- public void update(){
- EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa");
- EntityManager em = factory.createEntityManager();
- em.getTransaction().begin();
- Person person = em.find(Person.class, 1);
- person.setUserName("kate");
- em.getTransaction().commit();
- em.close();
- factory.close();
- }
- 将游离状态下的数据更新到数据库中
- public void updatePerson(){
- EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa");
- EntityManager em = factory.createEntityManager();
- em.getTransaction().begin();
- Person person = em.find(Person.class, 1);
- //把实体管理器中的实体变成游离状态
- em.clear();
- person.setUserName("jerry");
- //把游离状态下的更新同步到数据库中
- em.merge(person);
- em.getTransaction().commit();
- em.close();
- factory.close();
- }
3. <!--[endif]-->删除
- public void delete(){
- EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa");
- EntityManager em = factory.createEntityManager();
- em.getTransaction().begin();
- Person person = em.find(Person.class, 1);
- em.remove(person);
- em.getTransaction().commit();
- em.close();
- factory.close();
- }