具有回调方法的JPA瞬态字段 [英] JPA Transient fields with callback methods

查看:43
本文介绍了具有回调方法的JPA瞬态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体,其中包含几个基本字段A,B和C,以及一个复杂字段X,该字段未(不应)映射到数据库列.这个想法是在加载实例时从A,B和C创建X,并在持久存储时将X分解为A,B和C.

I have an entity which contains several basic fields A, B and C and one complex field X which is not (should not be) mapped to a database column. The idea is to create X from A, B and C when loading an instance, and to deconstruct X into A, B and C when persisting.

首先要尝试的逻辑事情是:

The first logical thing to try was something like:

      @Entity
      class Xxx
      {

      private String a;

      @Transient
      private X x;

      @PrePersist
      public void prePersist()
      {
      XParts xp = x.deconstruct();
      a = xp.getA();
      //...
      }
      //...
      }

问题是,在调用entityManager.merge(xxx)时; x丢失了.与JPA中如何处理@Transients有关. @Transient和@PrePersist不要混合使用.好的.我猜不出规格.

The problem is, when calling entityManager.merge(xxx); x is lost. Something to do with how the @Transients are handled in JPA. @Transient and @PrePersist don't mix. Ok. Can't argue with the specification I guess.

但是,还有哪些选择?我真的不需要数据库中的X.

But, what are the alternatives? I really don't need X in database.

我能想到的最好的方法是:

The best I could come up with is:

    @Column(insertable=false,updatable=false)
    private X x;

将创建X列,该列始终为空.如果真的是唯一的方法,我可以忍受,但这似乎充其量是骇人听闻的.

Which creates column X, which is always null. If it's really the only way, I can live with that, but it seems hackish at best.

我不是唯一一个遇到此问题的人.有什么更好的方法吗?

I can't be the only one who run into this problem. Is there any better way to do this?

推荐答案

JPA不提供任何PostMerge事件,但是如果您使用的是EclipseLink,则可以定义一个有权访问postMerge的DescriptorEventListener,以允许您合并临时对象属性.

JPA does not provide any PostMerge events, but if you are using EclipseLink you can define a DescriptorEventListener that does have access to postMerge that would allow you to merge your transient attributes.

这篇关于具有回调方法的JPA瞬态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆