Java – hibernate and Flyweight
Is there a way to use flyweight objects with sleep persistence mapping? My data model contains many of the same objects Instead of setting up separate instances for each same object, I use the flyweight design pattern and always reference the same physical object How do I do this in Hibernate?
By the way Do all JVMs optimize the use of strings in such a way that when the same string is used multiple times, it will always be the same physical instance?
Solution
It depends on
For read-only values, you can easily implement flyweight mode by creating a custom UserType, which will return objects from the pool each time instead of new instances
For entities, hibernate is rational by default and wants consistency between transactions, so entities will not be shared between sessions to avoid data race conditions - I don't think this is what you want
But if so (and it's not recommended at all and you don't know what you're doing), you can implement interceptor Getentity(), which is used for L2 cache In this method, you can return an entity (or even an entity shared by other sessions), and you will effectively set a flyweight mode for your entity
But I strongly recommend not to let entities refer to the actual immutable flyweight value for the sake of data consistency, rather than trying to connect with lightweight actual entities