[英]Saving an object into an Entity without persisting it in JPA
我正在播放框架中的应用程序,我需要将非实体对象的相同实例存储到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同时保持对象列隐藏在实体表中?
查看@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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.