go4it

just do it

实体bean(九)EntityManager的CURD

1.查找:

   知道Entity的唯一标识符,用find()/getReference()方法获取Entity

   find():没有找到记录时,返回null

   getReference():没有找到记录时,抛出javax.persistence.EntityNotFoundException例外,

                          而且不能保证实体bean已经被初始化。

   em.find(Person.class,1)

   em.getReference(Person.class,1)

 

2.增加

   em.persist(person)参数是实体bean

 

3.更新

   Person p=em.find(Person.class,1);

   p.setName(“persia”);

  (1)当实体正在被容器管理时,可以调用实体的setter方法来对数据进行修改,当容器决定flush时,更新的数据才同步到数据库。

  如果希望修改后的数据实时同步到数据库,则执行EntityManager.flush()方法。

(2) 当实体bean已经脱离了EntityManager的管理时使用em.merge(person)方法。当容器决定flush时,数据将同步到数据库中。

     Person person=persondao.getPersonByID(1);
        person.setName("linda");
        persondao.updatePerson(person);
   此时的实体bean已经脱离了容器管理,所以更新的时候仅仅用setter是不够的,还要merge一下。
public boolean updatePerson(Person person) {
		// TODO Auto-generated method stub
		try{
			em.merge(person);
				
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
 

4.删除

          Person p=em.find(Person.class,2);

em.remove(p);//必须传递实体bean为参数

   如果级联关系为ALL的时候,当删除person,会把级联对象删除。REMOVE也一样的效果。

posted on 2009-01-18 19:00  cxccbv  阅读(337)  评论(0)    收藏  举报

导航