Posted on 2009-06-20 19:04
胡娟 阅读(1562)
评论(0) 编辑 收藏 所属分类:
JAVA
1.获得对象
public void getPersonJql(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa");
EntityManager em = factory.createEntityManager();
Query query = (Query)em.createQuery("select p from Person p where p.id = ?1");
query.setParameter(1,5);
Person person = (Person)query.getSingleResult();
System.out.println(person.getUserName());
em.close();
factory.close();
}
2.
获得全部数据
public void findAll(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa");
EntityManager em = factory.createEntityManager();
Query query = (Query)em.createQuery("select p from Person p");
List<Person> list = query.getResultList();
for(Person p:list){
System.out.println(p.getUserName());
}
}
3.
更新
public void updateJql(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Query query = (Query)em.createQuery("update Person p set p.userName = ?1,p.gender = ?2 where p.id = ?3");
query.setParameter(1,"fankai");
query.setParameter(2,Gender.WoMEN);
query.setParameter(3,6);
query.executeUpdate();
em.getTransaction().commit();
em.close();
factory.close();
}
4.
删除
public void deleteJql(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("delete from Person p where p.id = ?1");
query.setParameter(1, 5);
query.executeUpdate();
em.getTransaction().commit();
em.close();
factory.close();
}