Java | Hibernate best practices

| By Webner

1.  Always define hashCode() and equals() methods in your Persistent classes.
2.  Persistent class method’s equals() and hashCode() must access its fields through getter methods. It is a good practice to use accessor methods instead of direct instance variable access.
3.  Always Implement Serialization with your entity classes. It is must to transfer such objects over different streams.
4.  Use Lazy loading for dependent entity classes as far as possible.
5.  If you are using select queries then use read-only mode for them. session.setReadOnly(object, true)
6.  Use FlushMode.COMMIT instead of AUTO so that Hibernate doesn’t issue select before updates.
7.  Always use parameterized queries to avoid sql injections.
8.  Always open a new session before the beginning of the request and close it at the end of transaction. We need to manage the session by ourselves and to flush and close it “manually”:

if (!session.isOpen()) {
        session = session.getSessionFactory().openSession();

Sessions are not thread safe.
9.  For the auto incremented id field in hibernate entities, always use private setter method because the primary key value is mostly auto generated by Hibernate.
10. If you are going to implement toString() method then be careful about printing those objects which are under lazy loading. Hibernate can issue org.hibernate.LazyInitializationException in such cases.

Leave a Reply

Your email address will not be published. Required fields are marked *