public void save() { Person person = new Person("aaa",121); entityManager.persist(person);//持久化一个对象,将数据保存到数据库中 } |
public void update(){ Person person = entityManager.find(Person.class, 1);//相当于hibernate的get方法,不会延迟加载,没有找到会返回null person.setName("bbb"); } |
public void delete(){ Person person = entityManager.find(Person.class, 3); entityManager.remove(person); } |
public void findPersonById(){ //相当于hibernate的get方法,不会延迟加载,没有找到会返回null Person person = entityManager.find(Person.class, 1); entityManager.clear(); System.out.println(person.getName()); }
public void findPersonById2(){ //相当于hibernate的load方法,不会延迟加载,没有找到在真正使用的时候会报异常 Person person = entityManager.getReference(Person.class, 1); entityManager.clear();//将所有的持久态的对象变为游离态 //System.out.println(person.getName());//报异常 entityManager.merge(person);//将游离态的对象变为持久态 } |
PersonDao.java |
package com.morris.dao.impl;
import javax.persistence.EntityManager; import javax.persistence.Persistence;
import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test;
import com.morris.entity.Person;
public class PersonDao {
private static EntityManager entityManager;
@BeforeClass public static void before() { entityManager = Persistence.createEntityManagerFactory("jpaDemo").createEntityManager();
entityManager.getTransaction().begin();
}
@Test public void findPersonById(){ //相当于hibernate的get方法,不会延迟加载,没有找到会返回null Person person = entityManager.find(Person.class, 1);
//System.out.println(person.getName());
entityManager.clear();
System.out.println(person.getName());
}
@Test public void findPersonById2(){ //相当于hibernate的load方法,不会延迟加载,没有找到在真正使用的时候会报异常 Person person = entityManager.getReference(Person.class, 1);
entityManager.clear();//将所有的持久态的对象变为游离态
//System.out.println(person.getName());//报异常
entityManager.merge(person);//将游离态的对象变为持久态
//System.out.println(person.getName());//报异常
}
@Test public void save() {
Person person = new Person("aaa",121);
entityManager.persist(person);//持久化一个对象,将数据保存到数据库中 }
@Test public void delete(){ Person person = entityManager.find(Person.class, 3);
entityManager.remove(person); }
@Test public void update(){
Person person = entityManager.find(Person.class, 1);//相当于hibernate的get方法,不会延迟加载,没有找到会返回null
person.setName("bbb");
}
@AfterClass public static void after(){ entityManager.getTransaction().commit(); entityManager.close(); }
}
|
原文地址:http://blog.csdn.net/u022812849/article/details/42534009