简体   繁体   English

将对象保存到实体中而不将其保留在JPA中

[英]Saving an object into an Entity without persisting it in JPA

I am doing an application in play framework in which I need to store the same instance of a non-Entity object into a JPA Entity without persisting it into the database, I want to know if it's possible to achieve that or not using annotations. 我正在播放框架中的应用程序,我需要将非实体对象的相同实例存储到JPA实体中而不将其持久化到数据库中,我想知道是否可以使用注释实现该实现。 A sample code of what I am looking for is: 我正在寻找的示例代码是:

 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();

I tried @Embedded annotation but its supposed to embed the object fields into the entity table. 我尝试了@Embedded注释,但它应该将对象字段嵌入到实体表中。 Is there anyway to use @Embedded while keeping the object column hidden in the entity table? 无论如何使用@Embedded同时保持对象列隐藏在实体表中?

Check out the @Transient annotation: 查看@Transient注释:

"This annotation specifies that the property or field is not persistent. It is used to annotate a property or field of an entity class, mapped superclass, or embeddable class." “此注释指定属性或字段不是持久的。它用于注释实体类,映射的超类或可嵌入类的属性或字段。”

To make sure you always get the same object you can implement the Singleton pattern, so your entities can use its getInstance() method to set the transient object: 要确保始终获得相同的对象,可以实现Singleton模式,因此您的实体可以使用其getInstance()方法来设置瞬态对象:

so this should do the trick: 所以这应该做的伎俩:

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM