@Test
public void query()
{
EntityManagerFactory entityFactory=Persistence.createEntityManagerFactory("person");
EntityManager entity=entityFactory.createEntityManager();
//select o from Person o where o.name=?1 --> 位置参数查询query.setParameter(1,"liyong");
//select o from Person o where o.name=:name and o.id=:id--->命名参数query.setParameter("name", "liyong");
//select o from Person o where o.name=? and o.id=?-->位置参数查询 query.setParameter(1, "liyong");query.setParameter(2, new Integer(3));
Query query=entity.createQuery("select o from Person o where o.name=? and o.id=?");
query.setParameter(1, "liyong");
query.setParameter(2, new Integer(2));
//只返回一条数据
Person person=(Person)query.getSingleResult();
//返回多条数据
/*List<Person> list=query.getResultList();
for(Person person2 : list)
{
System.out.println(person2.getName());
}*/
System.out.println(person.getName());
entity.close();
entityFactory.close();
}
@SuppressWarnings("unchecked")
@Test
public void queryall()
{
EntityManagerFactory entityFactory=Persistence.createEntityManagerFactory("person");
EntityManager entity=entityFactory.createEntityManager();
Query query=entity.createQuery("select o from Person o ");
//返回多条数据
List<Person> list=query.getResultList();
for(Person person : list)
{
System.out.println(person.getName());
}
entity.close();
entityFactory.close();
}
@Test
public void querydelete()
{
EntityManagerFactory entityFactory=Persistence.createEntityManagerFactory("person");
EntityManager entity=entityFactory.createEntityManager();
entity.getTransaction().begin();
Query query=entity.createQuery("delete from Person o where o.id=?1");
query.setParameter(1, new Integer(2));
query.executeUpdate();
entity.getTransaction().commit();
entity.close();
entityFactory.close();
}
@Test
public void queryupdate()
{
EntityManagerFactory entityFactory=Persistence.createEntityManagerFactory("person");
EntityManager entity=entityFactory.createEntityManager();
entity.getTransaction().begin();
Query query=entity.createQuery("update Person o set o.name=:name where o.id=:id");
query.setParameter("name","李勇");
query.setParameter("id", new Integer(3));
query.executeUpdate();
entity.getTransaction().commit();
entity.close();
entityFactory.close();
}