Posts

Showing posts with the label hibernate

Automatic Dirty Checking in Hibernate

Hibernate provides as feature called Automatic Dirty checking whereby changes to a persistent object are automatically saved to the database when the session is flushed or the transaction is committed. So the code does not need to invoke an explicit save or update. In this article, I will be covering this feature in detail. Introduction Hibernate supports 3 entity states, transient, persistent and detached. In order to understand more about entity states, you can refer to this article. So basically, an object can move into the persistent state when any one of the following happens: When the code invokes session.save, session.persist or session.saveorUpdate When the code invokes session.load or session.get Any changes to a persistent object are automatically saved to the database when the session in flushed. Flushing  is the process of synchronizing the underlying database with the objects in the session. There is a session.flush method available but you generally don’t need to invoke ...

How Hibernate SessionFactory works

In this article, I will be explaining what is Hibernate SessionFactory and how it works. Consider the following code that demonstrates a typical Hibernate application: SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();session.save(person);tx.commit();session.close();sessionFactory.close();   This code first creates a  SessionFactory object.  The sessionFactory contains all the data in the hibernate configuration file. The code uses the Configuration class to create the SessionFactory instance. The configuration.configure method reads the hibernate.cfg.xml file and sets up the Configuation object using the properties in this file. The buildSessionFactory method builds the sessionFactory object using this configuration data. The SessionFactory object is usually created only once at the start of the application and kept for later use. The SessionFactory ...

Hibernate Association Mappings with code samples

Hibernate supports associations that help you to model the relationship between database tables. In this article, I will be covering Hibernate association mappings. Introduction Most real-world applications have tables that have dependencies on each other i.e. the primary key of a table will be the foreign key in another table. Hibernate associations help us to represent the relationships between the tables. Types of association mappings Hibernate supports 4 types of associations as follows One to One You can use a One To One association mapping to represent a one-to-one relationship between database tables. A one-to-one relationship occurs between tables when one record from the main table corresponds to only one record in the second table. For example, a Person can have only one address. So one record in a Person table will correspond to only one record in the address table. One To Many You can use a One To Many association mapping to represent a one to many relationships between ta...

Hibernate Caching Mechanisms Explained

In this blog post, I will be explaining Hibernate caching. Caching is the ability to buffer the data retrieved from the database. So the cache stores recently used data items. So if the same items are requested, these items are then returned from the cache thus reducing the number of calls that are made to the database. This increases the performance of an application Hibernate supports 3 types of cache – First Level, Second Level, and Query Cache. First level cache The first-level cache is nothing but the session cache. It caches data in the session. This cache is automatically enabled, programmers do not need to do anything. Hibernate stores all objects in the session.  So once Hibernate associates an object with a session, it remains in the session till the session is closed. So even if we try to load the object again, a database call is not made if the object is in the session. So also, when the code updates an object, all updates are delayed until the session is committed or close...

Hibernate Persistence Life Cycle and Entity States

Image
In this blog post, I will be explaining the Hibernate Persistence Life Cycle and Entity States. What Are Entity States Given an object that is mapped via Hibernate, it can be in any one of 3 different states – transient, persistent and detached. Transient A transient object is an object that is not associated with a session and that does not have a database record. When you create a new object of a POJO class, that entity instance is in the transient state. Transient objects exist only in memory, Hibernate does not manage transient objects. Persistent A persistent object is an object that has a database record and that is associated with an active session. So the moment you invoke session.save on a transient object, it moves to the persistent state. Once an object is in the persistent state, hibernate tracks changes to it and automatically saves these changes to the database when the session is flushed. Detached An object that has a database record but is not associated with a session ...

Hibernate save vs saveOrUpdate

Hibernate provides several methods to save or modify the data into a database table. Two such methods are save and saveOrUpdate . In this blog post, I will be providing a detail comparison between the two. What is save? Hibernate provides the save method on the session interface to save a record into the database. So the session.save inserts a record into the database.  It returns the id , that is the primary key that will be assigned to the database record. What is saveOrUpdate? In addition to the save method, Hibernate also provides a method called saveOrUpdate on the session interface. Just as the name suggests, this method either performs a save operation or an update operation . If there is no record in the database corresponding to the object passed in, it inserts a record, but if there is a record corresponding to the object passed in, it just updates the existing record. This is generally useful in applications where a UI is involved. In such cases the back end might not ...

JPA vs Hibernate - An In-depth comparison

Often, we come across the terms JPA and Hibernate. Quite often, they are used interchangeably as well. Also, if you try to read up some tutorial to JPA, there will be a reference to Hibernate in it. So also, when you are studying Hibernate, you will come across references to JPA too. So it is often confusing for developers. In this post, I will attempt to clear this confusion. What is Hibernate? Hibernate is an ORM tool. ORM is nothing but a programming technique that allows you to map Java objects to database tables and vice versa. In addition to Hibernate, there are several other ORM tools. Before Hibernate came into existence, JDBC was widely used to access a relational database from Java code. The downside of JDBC is that it is not very object oriented.  It is very hard to map database tables to the code. Hibernate allows you to directly map your database tables to Java classes. So compared to JDBC, Hibernate provides a much cleaner approach. However, there is a disadvantage to usi...

What is Hibernate Criteria API

In this blog post, I will be explaining what is the Hibernate Criteria API. There are 3 ways in which you can query a database via Hibernate: Methods like load/get HQL (Hibernate Query Language) Criteria API Approach 1 – Methods like load/get Hibernate provides methods like load and get . You can use these to load a specific record from the database. The downside is that you can use these methods to only load a single record corresponding to an id. So if you want to retrieve all records that have a certain value, you cannot use these methods Approach 2 – Using HQL HQL stands for Hibernate Query Language . It has syntax similar to SQL.So whenever you need to query the database, you can write HQL queries in Hibernate. Instead of the database table and column names, you need to specify the class and field names in an HQL query. Based on the underlying database being used, Hibernate automatically converts HQL into equivalent SQLs statements. The downside to using HQL is that it...

Update vs Merge in Hibernate

In this blog post, I will be comparing the Update and Merge methods in Hibernate. I will be explaining how they are similar. I will also be explaining the differences between them.   Similarities Both update and merge methods on the session interface. Both methods update a record in the database. Both move an entity from the detached state to the persistent state. Differences The following table lists the differences between the update and merge methods: Edit Update Merge Hibernate proprietary method Part of the JPA specification Does not return anything, returns a void Returns the updated object Makes the original object persistent. So if the original object is changed after invoking update, changes will get saved when the session is flushed Does not make the original object persistent, so even if the original object is changed after merge, changes will not get saved in the database. Instead, the merged object is tracked for changes Always performs an SQL update Only ...

JDBC vs Hibernate

Image
In this blog post, I will be comparing JDBC and Hibernate and explaining the differences between the two.   What is JDBC? JDBC is nothing but an API to access a relational database from a java program. JDBC basically allows you to execute SQL statements from Java code, so basically any SQL statement which you can run on a database directly, you can run it from your Java code via JDBC.   Disadvantages of JDBC   In order to query a database table via JDBC, you will need code similar to the following: Class.forName("com.mysql.jdbc.Driver"); //Register JDBC Driver      Connection conn = DriverManager.getConnection(url, username, password); //Open a connection      Statement stmt = conn.createStatement(); //create a statement      ResultSet rs = stmt.executeQuery("Select * from book");// Execute a querywhile(rs.next()){ //iterate through the resultset      String bookName = rs.getString("book_name");      }         rs.close();      stmt.close();  ...

Difference between save and persist in Hibernate

In this blog post, I will be explaining the difference between the save and persist methods Hibernate. Both the save and persist methods insert a record into a database table. However, there are some differences between the two.   Edit Save Persist Hibernate Proprietary method Part of the JPA specification Returns ID of the saved object Returns a void Insert happens immediately in order to return the ID May not cause the database insert to happen immediately and the insert might happen later when the session is flushed    

Difference between Get and Load in Hibernate

In this blog post, I will be explaining the difference between the Hibernate load and get methods.  Both methods are used to load a record corresponding to an id. However, there are some differences between the two.    Edit Load Get If there is no record in the database corresponding to the id passed in, the load method throws an exception If there is no record in the database corresponding to the id passed in, the get method returns a null When the load method is used, it returns a proxy object with just the id field populated. All other fields are blank. The fields are only fetched from the database when they are accessed from the code. When the get method is used, it fetches the complete object i.e. it fetches all the fields of the object.  

Introducing my Hibernate Course!!

Happy to announce that my new Hibernate course is now live!! https://www.udemy.com/hibernate-from-scratch This course covers all Hibernate essentials from scratch! As an introductory offer I am giving away a limited number of free coupons!! Just leave a comment below and I will send a free coupon!