注意:查询语句,不要直接在查询语句后面加参数,因为如果别人输入";delete * from XXX"会把所有信息删除掉。
//查询1
@Test public void query(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
EntityManager em = factory.createEntityManager();
Query query = em.createQuery("select o from Person o where o.id=?1");
query.setParameter(1, 27l);
Person person = (Person)query.getSingleResult();
System.out.println(person.getName());
em.close();
factory.close();
}
//查询2
@Test public void query1(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
EntityManager em = factory.createEntityManager();
Query query = em.createQuery("select o from Person o");
List<Person> person = query.getResultList();
for(Person persons: person){
System.out.println(persons.getName());
}
em.close();
factory.close();
}
//删除
@Test public void deletequery(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("delete from Person o where o.id=?1");
query.setParameter(1, 27l);
query.executeUpdate();
em.getTransaction().commit();
em.close();
factory.close();
}
//更新
@Test public void updatequery(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("update Person o set o.name=:name where o.id=:id");
query.setParameter("name", "xxx");
query.setParameter("id", 28l);
query.executeUpdate();
em.getTransaction().commit();
em.close();
factory.close();
}