{"id":7949,"date":"2021-01-20T17:28:34","date_gmt":"2021-01-20T11:58:34","guid":{"rendered":"https:\/\/www.h2kinfosys.com\/blog\/?p=7949"},"modified":"2024-12-17T08:59:26","modified_gmt":"2024-12-17T13:59:26","slug":"how-to-read-and-save-data-using-hibernate","status":"publish","type":"post","link":"https:\/\/www.h2kinfosys.com\/blog\/how-to-read-and-save-data-using-hibernate\/","title":{"rendered":"How to read and save data using Hibernate?"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p>In today\u2019s fast-paced software industry, managing data efficiently is a crucial skill. Whether you are working on enterprise applications or small projects, data handling is at the core of <a href=\"https:\/\/www.h2kinfosys.com\/courses\/java-online-training-course-details\/\">Full Stack Java Development <\/a>Hibernate, one of the most powerful Object Relational Mapping (ORM) tools, simplifies database interactions by bridging the gap between Java applications and relational databases.<\/p>\n\n\n\n<p>But how do you read and save data using Hibernate effectively? This guide will walk you through the process step by step, ensuring you understand Hibernate\u2019s role in streamlining data access in Java applications. With practical examples, you\u2019ll gain confidence in handling data seamlessly, making you stand out in the job market.<\/p>\n\n\n\n<p>By the end of this blog, you\u2019ll not only grasp the theoretical aspects but also have the skills to integrate Hibernate into real-world projects.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is Hibernate?<\/strong><\/h2>\n\n\n\n<p>Hibernate is an open-source ORM framework that allows developers to interact with databases without writing repetitive SQL queries. It maps Java classes to database tables using XML configuration files or annotations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Why Use Hibernate?<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Simplifies database operations<\/li>\n\n\n\n<li>Eliminates boilerplate JDBC code<\/li>\n\n\n\n<li>Provides HQL (Hibernate Query Language) for querying data<\/li>\n\n\n\n<li>Supports automatic table creation and caching<\/li>\n<\/ul>\n\n\n\n<p>With Hibernate, you can focus on writing business logic while Hibernate takes care of the database operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Key Features of Hibernate:<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>ORM Support:<\/strong> Maps Java objects to database tables.<\/li>\n\n\n\n<li><strong>HQL (Hibernate Query Language):<\/strong> Allows querying databases using object-oriented syntax.<\/li>\n\n\n\n<li><strong>Automatic Schema Generation:<\/strong> Simplifies table creation and management.<\/li>\n\n\n\n<li><strong>Caching:<\/strong> Improves performance by minimizing database access.<\/li>\n\n\n\n<li><strong>Transaction Management:<\/strong> Provides seamless handling of <a href=\"https:\/\/en.wikipedia.org\/wiki\/Database_transaction\" rel=\"nofollow noopener\" target=\"_blank\">database transactions<\/a>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Why Use Hibernate to Read and Save Data?<\/h2>\n\n\n\n<p>When working on Java-based projects, you often need to perform CRUD (Create, Read, Update, Delete) operations. Traditional JDBC requires extensive coding to perform even simple operations, whereas it is easy to read and save data using Hibernate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits of Using Hibernate:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Simplified Code:<\/strong> No need to write repetitive SQL queries.<\/li>\n\n\n\n<li><strong>Cross-Platform Compatibility:<\/strong> Works with multiple databases like MySQL, PostgreSQL, and Oracle.<\/li>\n\n\n\n<li><strong>Performance Optimization:<\/strong> Features like caching reduce database overhead.<\/li>\n\n\n\n<li><strong>Automatic Mapping:<\/strong> Eliminates manual mapping between objects and tables.<\/li>\n\n\n\n<li><strong>Developer-Friendly API:<\/strong> Intuitive and easy to learn.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Setting Up Hibernate for Reading and Saving Data<\/strong><\/h2>\n\n\n\n<p>Before we dive into reading and saving data, let\u2019s set up Hibernate in a Java project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Step 1: Add Hibernate Dependencies<\/strong><\/h2>\n\n\n\n<p>To use Hibernate, add the required dependencies to your <strong>pom.xml<\/strong> if you are using Maven:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;dependencies>\n    &lt;dependency>\n        &lt;groupId>org.hibernate&lt;\/groupId>\n        &lt;artifactId>hibernate-core&lt;\/artifactId>\n        &lt;version>6.0.0.Final&lt;\/version>\n    &lt;\/dependency>\n    &lt;dependency>\n        &lt;groupId>com.mysql&lt;\/groupId>\n        &lt;artifactId>mysql-connector-java&lt;\/artifactId>\n        &lt;version>8.0.30&lt;\/version>\n    &lt;\/dependency>\n&lt;\/dependencies><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Step 2: Configure Hibernate<\/strong><\/h2>\n\n\n\n<p>Create a <strong>hibernate.cfg.xml<\/strong> file to configure your database connection:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!DOCTYPE hibernate-configuration PUBLIC\n  \"-\/\/Hibernate\/Hibernate Configuration DTD 3.0\/\/EN\"\n  \"http:\/\/hibernate.sourceforge.net\/hibernate-configuration-3.0.dtd\">\n\n&lt;hibernate-configuration>\n    &lt;session-factory>\n        &lt;property name=\"hibernate.connection.driver_class\">com.mysql.cj.jdbc.Driver&lt;\/property>\n        &lt;property name=\"hibernate.connection.url\">jdbc:mysql:\/\/localhost:3306\/yourdb&lt;\/property>\n        &lt;property name=\"hibernate.connection.username\">root&lt;\/property>\n        &lt;property name=\"hibernate.connection.password\">password&lt;\/property>\n        &lt;property name=\"hibernate.dialect\">org.hibernate.dialect.MySQL8Dialect&lt;\/property>\n        &lt;property name=\"hibernate.show_sql\">true&lt;\/property>\n        &lt;property name=\"hibernate.hbm2ddl.auto\">update&lt;\/property>\n    &lt;\/session-factory>\n&lt;\/hibernate-configuration><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Step 3: Create a Java Entity Class<\/strong><\/h2>\n\n\n\n<p>Define a simple <strong>POJO<\/strong> (Plain Old Java Object) class to map with the database table.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import javax.persistence.*;\n\n@Entity\n@Table(name = \"students\")\npublic class Student {\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private Long id;\n\n    private String name;\n    private String course;\n\n    public Long getId() {\n        return id;\n    }\n    public void setId(Long id) {\n        this.id = id;\n    }\n    public String getName() {\n        return name;\n    }\n    public void setName(String name) {\n        this.name = name;\n    }\n    public String getCourse() {\n        return course;\n    }\n    public void setCourse(String course) {\n        this.course = course;\n    }\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to read data?<\/strong><\/h2>\n\n\n\n<p>Hibernate provides two different methods to read data from the database:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>get(): It returns a persistence object of a given class. It returns null when there is no persistence object available.<\/li>\n\n\n\n<li>load(): It also returns a persistence object of a given class but throws an exception (objectNotFoundException) if the entity is not available in the database.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Difference between get() and load()<\/strong><\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Session.get()<\/strong><\/td><td><strong>Session.load()<\/strong><\/td><\/tr><tr><td>It never returns a proxy object.<\/td><td>It always returns a proxy object.<\/td><\/tr><tr><td>It returns null when the entity is not available in the database and continues the execution.<\/td><td>It throws an exception (objectNotFoundException) when the entity is not available in the database and terminates the execution.<\/td><\/tr><tr><td>Eager Loading; It hits the database immediately and returns the object.<\/td><td>Lazy Loading; It hits the database only when it tries to retrieve the object.<\/td><\/tr><tr><td>They are used for the SELECT operation.<\/td><td>They are used for DELETE and UPDATE operations.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to Read Data Using Hibernate<\/strong><\/h2>\n\n\n\n<p>Reading data using Hibernate involves retrieving records from the database using Hibernate Query Language (HQL).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\nimport java.util.List;\n\npublic class ReadDataExample {\n    public static void main(String&#91;] args) {\n        SessionFactory factory = new Configuration().configure(\"hibernate.cfg.xml\")\n                .addAnnotatedClass(Student.class).buildSessionFactory();\n        \n        Session session = factory.getCurrentSession();\n        try {\n            \/\/ Start a transaction\n            session.beginTransaction();\n            \n            \/\/ Query to fetch all students\n            List&lt;Student> students = session.createQuery(\"from Student\").getResultList();\n            \n            \/\/ Display the students\n            for (Student s : students) {\n                System.out.println(s.getId() + \" - \" + s.getName() + \" - \" + s.getCourse());\n            }\n            \n            \/\/ Commit the transaction\n            session.getTransaction().commit();\n        } finally {\n            factory.close();\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>HQL query (<code>from Student<\/code>) retrieves all records.<\/li>\n\n\n\n<li>Results are stored in a <strong>List<\/strong>.<\/li>\n\n\n\n<li>Data is displayed using a simple loop.<\/li>\n<\/ol>\n\n\n\n<p><strong><br><\/strong><\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"JAVA | Hibernate | SQL Query Using Hibernate | Java Online training | java course by H2Kinfosys\" width=\"800\" height=\"450\" src=\"https:\/\/www.youtube.com\/embed\/gkkb8Io2giM?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<p>Let us now understand the Session.get() using an example.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to Save Data?<\/strong><\/h2>\n\n\n\n<p>Hibernate provides different methods to save data into the database:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>save(): It returns a generated identifier and <a class=\"rank-math-link\" href=\"https:\/\/www.h2kinfosys.com\/blog\/exception-handling-in-java\/\">throws an exception<\/a> when an entity is already available in the database.<\/li>\n\n\n\n<li>persist (): It returns a void and throws an exception when an entity is already available in the database.<\/li>\n\n\n\n<li>saveOrUpdate(): It is used to either save or update the entity in the database.<\/li>\n<\/ol>\n\n\n\n<p>Let us now understand these using some examples.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to Save Data Using Hibernate<\/strong><\/h2>\n\n\n\n<p>Saving data to a database using Hibernate involves the following steps:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 1: Create a Hibernate Session Factory<\/strong><\/h3>\n\n\n\n<p>The <strong>SessionFactory<\/strong> is a heavyweight object that initializes Hibernate and manages sessions.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class SaveDataExample {\n    public static void main(String&#91;] args) {\n        SessionFactory factory = new Configuration().configure(\"hibernate.cfg.xml\")\n                .addAnnotatedClass(Student.class).buildSessionFactory();\n        \n        Session session = factory.getCurrentSession();\n        try {\n            \/\/ Create a student object\n            Student student = new Student();\n            student.setName(\"John Doe\");\n            student.setCourse(\"Java Programming\");\n\n            \/\/ Start a transaction\n            session.beginTransaction();\n            \n            \/\/ Save the student object\n            session.save(student);\n\n            \/\/ Commit the transaction\n            session.getTransaction().commit();\n\n            System.out.println(\"Data Saved Successfully!\");\n        } finally {\n            factory.close();\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Explanation:<\/strong><\/h3>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li><strong>SessionFactory<\/strong> loads the Hibernate configuration.<\/li>\n\n\n\n<li>A <strong>Session<\/strong> is created to interact with the database.<\/li>\n\n\n\n<li>Transactions are started and committed to save the entity.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Hibernate revolutionizes the way developers interact with relational databases in Java applications. By automating CRUD operations and simplifying complex SQL queries, Hibernate makes data handling efficient and developer-friendly.<\/p>\n\n\n\n<p>With a clear understanding of how to read and save data using Hibernate, you can confidently integrate it into your projects. Whether you are managing large-scale enterprise data or small datasets, Hibernate provides the flexibility and power you need.<\/p>\n\n\n\n<p>Are you ready to advance your Hibernate skills? Enroll in<a href=\"http:\/\/h2khttps:\/\/www.h2kinfosys.com\/\"> H2K Infosys<\/a> comprehensive Java and Hibernate training today to gain hands-on experience and boost your career prospects!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction In today\u2019s fast-paced software industry, managing data efficiently is a crucial skill. Whether you are working on enterprise applications or small projects, data handling is at the core of Full Stack Java Development Hibernate, one of the most powerful Object Relational Mapping (ORM) tools, simplifies database interactions by bridging the gap between Java applications [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":7951,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[42],"tags":[],"class_list":["post-7949","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-tutorials"],"_links":{"self":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/7949","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/comments?post=7949"}],"version-history":[{"count":0,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/7949\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media\/7951"}],"wp:attachment":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media?parent=7949"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/categories?post=7949"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/tags?post=7949"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}