I am pretty new to Hibernate. I am having problem understanding these simple logics. I have understood that @Repository is used by Spring for accessing objects. Also, Hibernate uses @Entity to denote entities which are mapped into database tables. I was just wondering if a single class can be annotated with both @Repository and @Entity as they more or less imply the same.
I am pretty new to Hibernate. I am having problem understanding these simple logics.
Share
NO.
Hibernate entities are managed by Hibernate ORM framework, they(and their proxies) are created by hibernate when you access them via get() or load(). They have a completely different (and complex) lifecycle than the Spring beans(they can be attached/detached/proxied/pending for removal)
Spring repositories are singletons, managed by Spring framework. Typically they exist as long as the container instance exists. New Hibernate sessions may be opened and closed, new user sessions engaged and then expired, but there still will be the same singleton instances of repositories.
Please see http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-overview for the possible hibernate object states.
As for the repository instances – typically they are stateless, as they are services.
RE:
they more or less imply the same.No they are not the same. There was an old jokeBut good OOP programmers do not think that way, according to single responsibility principle objects should should have a single reason to change. Repository works with the infrastructure and has nothing to do with the business rules. Infrastructure may change(you may need for example to store you object in XML instead of RDBMS), but this should not affect the classes encapsulating the state of business objects.
You can possibly mitigate this problem by making a reference from the entity class to an abstract repository interface(implement an infamous Active Record pattern – it will be like referencing some abstract bulb socket from the bulb, this does not seem to be a good solution because bulb sockets and bulbs have different lifecycles).
That is where High Cohesion principle starts to play, according to which it’s just illogical for an object, whose role is to reflect the abstractions from the model, to perform some completely unrelated things like persistence or transmitting over the network. It’s weird when
Studentclass will haveprint(),saveToXml()ortransmitByHttp()methods.