Posted on 2009-06-20 18:59
胡娟 阅读(1411)
评论(0) 编辑 收藏 所属分类:
JAVA
1.
查找对象
1)
用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)
用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.
更新对象
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.
删除
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();
}