Yes, you can implement the Flyweight pattern with Hibernate.
The flyweight pattern is way to minimize memory usage per instance. The strategy is to share as much state between flyweight instances as possible. In your case the shareable state is everything except the hibernate object identifier and some additional state to maintain object identity.
Each flyweight instance needs its own object identity. The additional state is the way to implement identity to distinguish between objects that share common state.
public boolean equals(Object obj){
Fly other; [..]//check type
//null checks ommitted
return other.myState.equals(myState) && other.commonState.equals(commonState);
}
If the object identity is shared between instances hibernate would interpret all physical instances (references) as the same instance. Hibernate uses the equals method to check object identity and your equal implementation would have to return (! a.equals(a) == true)
which is illegal. Equal has to be reflexive. If you would break this contract all libraries that depend on the contract will be broken (collections, hibernate, etc.).
You cannot implement the equal method using the hibernate object identifier to distinguish between objects. This would make the object identity dependent on the persistence state (persisted or transient).
One way to model the common state in hibernate is a one-to-many association between shared state objects and flyweight objects. (Maybe someone has an idea how to map the data without joining two tables?)
String: Only internalized strings will be shared. This is not the best solution most of the time. It is appropriate for symbols (class name, method name, etc.).
The internalized strings will never by garbage collected and you have to have a String instance that will to be garbage collected anyway new String("..").intern()
. It will not save allocations. There is only the minor advantage that the base string will not survive a gc generation or could be allocated on the stack (with escape analysis in hot spot enabled and applicable).