@Test
public void save()
{
//得到这个EntityManagerFactory时就会去创建表
//hibernate 中得到sessionFactory同等
EntityManagerFactory entityFactory=Persistence.createEntityManagerFactory("person");
//得到EntityManager
//hibernate中得到session等同
EntityManager entity=entityFactory.createEntityManager();
//开启事务和hibernate一样
entity.getTransaction().begin();
entity.persist(new Person("liyong"));
entity.getTransaction().commit();
entity.close();
entityFactory.close();
}
//获取数据不用开事务(只有数据没有改变就不需开启事务)
@Test
public void getPerson()
{
EntityManagerFactory entityFactory=Persistence.createEntityManagerFactory("person");
EntityManager entity=entityFactory.createEntityManager();
Person person=entity.find(Person.class, 1);//hibernate中的get()方法
System.out.println(person.getName());
entity.close();
entityFactory.close();
}
@Test
public void getPeron2()
{
EntityManagerFactory entityFactory=Persistence.createEntityManagerFactory("person");
EntityManager entity=entityFactory.createEntityManager();
Person person=entity.getReference(Person.class, 1);//hibernate中的load()方法返回一个代理对象
System.out.println(person.getName());//当调用代理对象方法的时候才去加载数据
entity.close();
entityFactory.close();
}
//JPA中实体的四种状态 :新建、托管、游离、删除
@Test
public void update()
{
EntityManagerFactory entityFactory=Persistence.createEntityManagerFactory("person");
EntityManager entity=entityFactory.createEntityManager();
entity.getTransaction().begin();//必须开启事务
Person person=entity.find(Person.class, 1);
person.setName("小李");//这里不行是托管状态的
entity.getTransaction().commit();
entity.close();
entityFactory.close();
}
@Test
public void update2()
{
EntityManagerFactory entityFactory=Persistence.createEntityManagerFactory("person");
EntityManager entity=entityFactory.createEntityManager();
entity.getTransaction().begin();
Person person=entity.find(Person.class, 1);
entity.clear();//把实体管理器中所有实体变成游离状态
person.setName("小王");
entity.merge(person);//这里是把游离的实体同步到数据库中
entity.getTransaction().commit();
entity.close();
entityFactory.close();
}
@Test
public void delete()
{
EntityManagerFactory entityFactory=Persistence.createEntityManagerFactory("person");
EntityManager entity=entityFactory.createEntityManager();
entity.getTransaction().begin();
Person person=entity.find(Person.class, 1);
entity.remove(person);//这里删除的实体必须是托管
entity.getTransaction().commit();
entity.close();
entityFactory.close();
}