Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate/persistence and singleton pattern

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?

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

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?

like image 762
Jakub Avatar asked Nov 12 '22 20:11

Jakub


1 Answers

I ended with this:

@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...
}
like image 192
Jakub Avatar answered Nov 15 '22 10:11

Jakub