JPA 删除实体

 /**
  * 删除
  */
 @Override
 public void remove(T t) throws RuntimeException {
  if (null == t) {
   throw new RuntimeException("请求删除的对象为空!");
  }
  if (entityManager.contains(t)) {
   entityManager.remove(t);
  } else {
   Object id = entityManager.getEntityManagerFactory()
     .getPersistenceUnitUtil().getIdentifier(t);
   entityManager.remove(entityManager.find(t.getClass(), id));
  }
 }

先判断实体是否存在,如果处于托管状态直接删除,反之查询一次然后删除(值得一提的是JPA提供了根据t获取t的id的方法)

 

欢迎加入JPA讨论群:234134357

你可能感兴趣的:(JPA 删除实体)