开发者

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. A sample code of what I am looking for is:

 public class anEntity extends Model {
    @ManyToOne
    public User开发者_Python百科 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. Is there anyway to use @Embedded while keeping the object column hidden in the entity table?


Check out the @Transient annotation:

"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:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜