【问题标题】:Saving an object into an Entity without persisting it in JPA将对象保存到实体中而不将其保存在 JPA 中
【发布时间】:2011-08-21 21:46:32
【问题描述】:

我正在做一个应用程序在播放框架中,我需要将非实体对象的相同实例存储到 JPA 实体中而不将其持久化到数据库中,我想知道是否有可能实现这一点注释。我正在寻找的示例代码是:

 public class anEntity extends Model {
    @ManyToOne
    public User user;

    @ManyToOne
    public Question question;


    //Encrypted candidate name for the answer
    @Column(columnDefinition = "text")
    public BigInteger candidateName;

    //I want that field not to be inserted into the database
    TestObject p= new TestObject();

我尝试了@Embedded 注释,但它应该将对象字段嵌入到实体表中。无论如何在实体表中隐藏对象列的同时使用@Embedded?

【问题讨论】:

  • 我编辑了问题并回答了一点,以澄清应始终使用相同的瞬态实例。希望你不介意..

标签: java hibernate jpa singleton transient


【解决方案1】:

查看@Transient注解:

“此注解指定属性或字段不是持久性的。它用于对实体类、映射超类或可嵌入类的属性或字段进行注解。”

为确保您始终获得相同的对象,您可以实现Singleton 模式,这样您的实体就可以使用其getInstance() 方法来设置瞬态对象:

所以这应该可以解决问题:

public class anEntity extends Model {
    @Transient
    private TransientSingleton t;

    public anEntity(){ // JPA calls this so you can use the constructor to set the transient instance.
        super();
        t=TransientSingleton.getInstance();
    }


public class TransientSingleton { // simple unsecure singleton from wikipedia

    private static final TransientSingleton INSTANCE = new TransientSingleton();
    private TransientSingleton() {
        [...do stuff..]
    }
    public static TransientSingleton getInstance() {
        return INSTANCE;
    }
}

【讨论】:

  • 我试过了,但是当我从数据库中获取实体后尝试使用瞬态对象时,它给了我一个空指针异常。
  • 在你的类中添加一个 Constroctur 并在那里设置 Testobject,正如答案中所指出的那样。
  • 我很确定这应该可以工作,但您也可以尝试在您的班级中的一个简单块 {} 中设置瞬态对象:xs4all.nl/~kzeil/en/project/java/initializer-block.html
  • 您还必须使用默认构造函数。没有任何参数。
  • 并且不要将@Transient 注释与transient 关键字混淆。它们都在字段上有效;)javabeat.net/tips/168-what-is-transient-keyword-in-java.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-18
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多