简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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