休眠/持久性和单例模式 [英] Hibernate/persistence and singleton pattern
本文介绍了休眠/持久性和单例模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个单例要保留在数据库中.其他持久化实体应参考此单例.Hibernate如何实现?
I have a singleton that is to be persisted in database. Other persisted entities should have reference to this singleton. How can it be achieved with Hibernate?
我以这样的事情还没有结束,伪造了单身人士的单一ID:
I ended with something not-yet-working like this, faking the single ID of the singleton:
@Entity
@Subselect("select '1' as ID")
class Singleton {
@Id
@Column(name="ID")
private Long getId() { return 1l; }
private void setId(Long id) { }
}
@Entity
@Table(name="ENT")
class MyEnt {
// TODO: how to annotate so that table ENT doesn't need foreign key column
Singleton s;
}
问题是我不想在引用Singleton的实体中有一列带有外键的列-因为Singleton只是一个,我们不需要它的ID ...
The problem is that I don't want to have a column with foreign key in entities referencing the Singleton - because the singleton is only one and we don't need its ID...
也许我想的是错误的方式?也许是错误的体系结构问题?您解决了类似的问题吗?
Maybe I am thinking in a wrong way? Maybe it is wrong architecture issue? Did you solve similar issue?
推荐答案
我到此为止:
@Entity
@Subselect("select '1' as ID, * from TABLE")
class Singleton {
@Id
@Column(name="ID")
private Long getId() { return 1l; }
private void setId(Long id) { }
// ... other useful fields persisted in TABLE
}
@Entity
@Table(name="ENT")
class MyEnt implements Lifecycle {
Singleton s;
void onLoad(Session sess, Serializable id) {
this.s = sess.get(Singleton.class, 1l);
}
// etc...
}
这篇关于休眠/持久性和单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文