Java – save objects to entities without keeping them in JPA
I'm playing the application in the framework. I need to store the same instance of non entity objects in JPA entities instead of persisting them in the database. I want to know whether I can use annotations to implement this implementation The sample code I'm 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 it should embed object fields into entity tables Anyway, use @ embedded while keeping the object column hidden in the entity table?
Solution
View @ transient comments:
This annotation specifies that the property or field is not persistent. It is used to annotate the property or field of an entity class, mapped superclass or embeddable class
To ensure that the same object is always obtained, the singleton pattern can be implemented, so your entity can use its getInstance () method to set the transient object:
So here's 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; } }