JPA(二)之CRUD操作

修改PerTest.java

具体代码如下:

package junit.test;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.Test;

import com.sonoi.bean.Person;

public class PerTest {

	@Test
	public void save() {
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory("unitname");
		EntityManager manager = factory.createEntityManager();
		manager.getTransaction().begin();
		//不能输入汉字!针对my操作系统
		manager.persist(new Person("nansheng"));
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
	
	@Test
	public void find1() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("unitname");
		EntityManager manager = factory.createEntityManager();
		Person person = manager.find(Person.class, 2);
		System.out.println(person.getName());
		manager.close();
		factory.close();
	}
	
	@Test
	public void find2() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("unitname");
		EntityManager manager = factory.createEntityManager();
		Person person = manager.getReference(Person.class, 1);
		System.out.println(person.getName());
		manager.close();
		factory.close();
	}
	
	@Test
	public void update1() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("unitname");
		EntityManager manager = factory.createEntityManager();
		manager.getTransaction().begin();
		Person person = manager.getReference(Person.class, 1);
		person.setName("bbbbbbb");
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
	
	//此更新方法有问题
	@Test
	public void update2() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("unitname");
		EntityManager manager = factory.createEntityManager();
		manager.getTransaction().begin();
		Person person = manager.getReference(Person.class, 1);
		//增加此句代码会出错
		manager.clear();
//		manager.merge(person);
		person.setName("hhhhhhh");
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
	
	@Test
	public void delete() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("unitname");
		EntityManager manager = factory.createEntityManager();
		manager.getTransaction().begin();
		Person person = manager.getReference(Person.class, 2);
		manager.remove(person);
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
	
}

 

你可能感兴趣的:(增删改查)