JPA getSingleResult - EntityNotfound Exception

时间:2016-03-15 23:19:37

标签: java hibernate jpa

您好我正在尝试通过JPA getSingleResult获取一个java实体,但它抛出了我在API specs

中找不到的异常

方法:

public static Object getSingleResultOrNull(Query q){
        try{
            return q.getSingleResult();
        }catch(NoResultException| EntityNotFoundException enfex){
            System.out.println(enfex.getMessage());
            enfex.printStackTrace();
            return null;
        }catch(NonUniqueResultException ex){
            ex.printStackTrace();
            throw ex;
        }
    }

致电代码:

tagName = tagName.trim().toLowerCase();
Tags tag = (Tags) getSingleResultOrNull(namedQuery("Tags.findByName")
                                        .setParameter("name", tagName));

标记类:

@Entity @Table(name = "tags") @XmlRootElement @NamedQueries({
    @NamedQuery(name = "Tags.findByName", query = "SELECT t FROM Tags t WHERE t.name = :name")}) 
public class Tags implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Basic(optional = false)
    @Column(name = "name")
    private String name;

修改:添加ProductTags。类

public class ProductTags implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @JsonIgnore
    @Column(name = "created")
    @Temporal(TemporalType.TIMESTAMP)
    private Date created;
    @JsonIgnore
    @Column(name = "last_updated")
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastUpdated;
    @JsonIgnore
    @Column(name = "last_updated_by")
    private String lastUpdatedBy;
    @JsonIgnore
    @JoinColumn(name = "prod_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Product prod;
    @JoinColumn(name = "tag_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Tags tag;

根据getSingleResult的API规范,只应抛出以下异常:

  • NoResultException - 如果没有结果
  • NonUniqueResultException - 如果有多个结果
  • IllegalStateException - 如果调用Java Persistence查询 语言UPDATE或DELETE语句
  • QueryTimeoutException - 如果 查询执行超过了查询超时值而且只有 声明被回滚
  • TransactionRequiredException - 如果锁定 模式已设置且没有交易
  • PessimisticLockException - 如果悲观锁定失败了 交易回滚
  • LockTimeoutException - 如果悲观 锁定失败,只回滚语句
  • PersistenceException - 如果查询执行超出查询 设置超时值并回滚事务

但是,我得到一个奇怪的例外javax.persistence.EntityNotFoundException:已删除的实体传递给persist:[models.ProductTags#]

对于一个完全(不完全是因为ProductTags有一个Tags对象的外键,但在保存Tags对象的上下文中,我没有看到任何关系。)无关的实体。

  

传递给持久化的已删除实体:[models.ProductTags#]   javax.persistence.EntityNotFoundException:传递给已删除的实体   坚持:[models.ProductTags#] at   org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1369)     在   org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1315)     在org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:307)     在   controllers.PowerController.getSingleResultOrNull(PowerController.java:68)     在   controllers.ProductController.updateProductInfo(ProductController.java:282)     在   router.Routes $$ anonfun $ $航线1 $$ anonfun $ applyOrElse $ 4 $$ anonfun $ $适用4.适用(Routes.scala:1584)     在   router.Routes $$ anonfun $ $航线1 $$ anonfun $ applyOrElse $ 4 $$ anonfun $ $适用4.适用(Routes.scala:1584)     在   play.core.routing.HandlerInvokerFactory $$匿名$ 4.resultCall(HandlerInvoker.scala:136)     在   play.core.routing.HandlerInvokerFactory $ JavaActionInvokerFactory $$不久$ 14 $$不久$ 3 $$不久$ 1.invocation(HandlerInvoker.scala:127)     在play.core.j.JavaAction $$ anon $ 1.call(JavaAction.scala:70)at   play.http.DefaultHttpRequestHandler $ 1.call(DefaultHttpRequestHandler.java:20)     at interceptors.ProductAction.call(ProductAction.java:65)at   play.db.jpa.TransactionalAction.lambda $调用$ 5(TransactionalAction.java:19)     at play.db.jpa.TransactionalAction $$ Lambda $ 43 / 469822182.apply(未知   来源)at   play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:136)at at   play.db.jpa.JPA.withTransaction(JPA.java:159)at   play.db.jpa.TransactionalAction.call(TransactionalAction.java:16)at   play.core.j.JavaAction $$ anonfun $ 7.apply(JavaAction.scala:94)at at   play.core.j.JavaAction $$ anonfun $ 7.apply(JavaAction.scala:94)at at   scala.concurrent.impl.Future $ PromiseCompletingRunnable.liftedTree1 $ 1(Future.scala:24)     在   scala.concurrent.impl.Future $ PromiseCompletingRunnable.run(Future.scala:24)     在   play.core.j.HttpExecutionContext $$匿名$ 2.run(HttpExecutionContext.scala:40)     在   play.api.libs.iteratee.Execution $蹦床$ .execute(Execution.scala:70)     在   play.core.j.HttpExecutionContext.execute(HttpExecutionContext.scala:32)     在scala.concurrent.impl.Future $ .apply(Future.scala:31)at   scala.concurrent.Future $ .apply(Future.scala:485)at   play.core.j.JavaAction.apply(JavaAction.scala:94)at   play.api.mvc.Action $$ anonfun $ $申请1 $$ anonfun $ $应用4 $$ anonfun $ $申请5.apply(Action.scala:105)     在   play.api.mvc.Action $$ anonfun $ $申请1 $$ anonfun $ $应用4 $$ anonfun $ $申请5.apply(Action.scala:105)     at play.utils.Threads $ .withContextClassLoader(Threads.scala:21)at at   play.api.mvc.Action $$ anonfun $ $申请1 $$ anonfun $ $申请4.适用(Action.scala:104)     在   play.api.mvc.Action $$ anonfun $ $申请1 $$ anonfun $ $申请4.适用(Action.scala:103)     在scala.Option.map(Option.scala:145)at   play.api.mvc.Action $$ anonfun $ apply $ 1.apply(Action.scala:103)at at   play.api.mvc.Action $$ anonfun $ apply $ 1.apply(Action.scala:96)at at   play.api.libs.iteratee.Iteratee $$ anonfun $ MAPM $ 1.适用(Iteratee.scala:524)     在   play.api.libs.iteratee.Iteratee $$ anonfun $ MAPM $ 1.适用(Iteratee.scala:524)     在   play.api.libs.iteratee.Iteratee $$ anonfun $ flatMapM $ 1.适用(Iteratee.scala:560)     在   play.api.libs.iteratee.Iteratee $$ anonfun $ flatMapM $ 1.适用(Iteratee.scala:560)     在   play.api.libs.iteratee.Iteratee $$ anonfun $ flatMap $ 1 $$ anonfun $ $申请14.apply(Iteratee.scala:537)     在   play.api.libs.iteratee.Iteratee $$ anonfun $ flatMap $ 1 $$ anonfun $ $申请14.apply(Iteratee.scala:537)     在   scala.concurrent.impl.Future $ PromiseCompletingRunnable.liftedTree1 $ 1(Future.scala:24)     在   scala.concurrent.impl.Future $ PromiseCompletingRunnable.run(Future.scala:24)     at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40)at   akka.dispatch.ForkJoinExecutorConfigurator $ AkkaForkJoinTask.exec(AbstractDispatcher.scala:397)     在   scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)     在   scala.concurrent.forkjoin.ForkJoinPool $ WorkQueue.runTask(ForkJoinPool.java:1339)     在   scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)     在   scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

我知道另一种编写getSingleResultOrNull方法的方法,但在这种情况下我无法找到问题。

对此有任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

我相信你的问题是在之前的某个步骤引起的。查看堆栈跟踪,在调用您显示的方法之前就有这一行:

controllers.ProductController.updateProductInfo(ProductController.java:282)

也许您正在更新 updateProductInfo 中的某个对象的状态,并且当您调用 getSingleResultOrNull 方法时,Hibernate正在刷新会话。

此处有一些类似的情况,您也可以查看:Deleted entity passed to persist exception

答案 1 :(得分:0)

当我查询存在但不在数据库中的实体时会发生这种情况:

javax.servlet.ServletException: javax.ejb.EJBException: javax.persistence.NoResultException: No entity found for query