Java 持久性 api 不删除/删除记录 oracle 数据库 11g XE
Java persistence api not deleting / removing record oracle database 11g XE
我使用 Java 持久性 API 成功创建、合并、获取了记录,但我无法删除记录。我使用 em.createNativeQuery("Delete ...") 并且它工作正常,问题是我想使用实体管理器来做到这一点。我认为问题可能出在 oracle 数据库上,因为我用 Derby 尝试了上面的代码并且它运行良好。
public void destroy(String id) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
Context initCtx = new InitialContext();
utx = (UserTransaction) initCtx.lookup("java:comp/env/UserTransaction");
try {
utx.begin();
em = getEntityManager();
//Query query = em.createNativeQuery("DELETE FROM SERVICIO WHERE SERVICIODESCRIPCION = '"+id+"'");
//query.executeUpdate();
Servicio servicio;
try {
servicio = em.getReference(Servicio.class, id);
servicio.getServiciodescripcion();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The servicio with id " + id + " no longer exists.", enfe);
}
em.remove(servicio);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.flush();
em.close();
}
}
}
事实上,问题是我的主键的数据类型设置为 char(10),我解决了将其更改为 VARCHAR(10),所以总而言之,在使用 Oracle 数据库时,JPA 和主键设置为文本,应该使用的数据类型是 VARCHAR 而不是 CHAR,因此实体管理器可以正常工作。谢谢
我使用 Java 持久性 API 成功创建、合并、获取了记录,但我无法删除记录。我使用 em.createNativeQuery("Delete ...") 并且它工作正常,问题是我想使用实体管理器来做到这一点。我认为问题可能出在 oracle 数据库上,因为我用 Derby 尝试了上面的代码并且它运行良好。
public void destroy(String id) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
Context initCtx = new InitialContext();
utx = (UserTransaction) initCtx.lookup("java:comp/env/UserTransaction");
try {
utx.begin();
em = getEntityManager();
//Query query = em.createNativeQuery("DELETE FROM SERVICIO WHERE SERVICIODESCRIPCION = '"+id+"'");
//query.executeUpdate();
Servicio servicio;
try {
servicio = em.getReference(Servicio.class, id);
servicio.getServiciodescripcion();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The servicio with id " + id + " no longer exists.", enfe);
}
em.remove(servicio);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.flush();
em.close();
}
}
}
事实上,问题是我的主键的数据类型设置为 char(10),我解决了将其更改为 VARCHAR(10),所以总而言之,在使用 Oracle 数据库时,JPA 和主键设置为文本,应该使用的数据类型是 VARCHAR 而不是 CHAR,因此实体管理器可以正常工作。谢谢