Slip 10 Q A

Write a java Program in Hibernate to display “Hello world” message.

1. Project Structure (Basic)
HibernateHelloWorld
 ├── src
 │   └── com/example/HelloWorld.java
 ├── hibernate.cfg.xml
 └── lib
     └── (hibernate JAR files)

Hibernate Configuration File (hibernate.cfg.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>

        <!-- Database settings (not used here but required) -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>

        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

        <!-- Show SQL -->
        <property name="hibernate.show_sql">true</property>

    </session-factory>
</hibernate-configuration>

Java Program (HelloWorld.java)

package com.example;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HelloWorld {

    public static void main(String[] args) {

        // Create SessionFactory
        SessionFactory factory = new Configuration()
                .configure("hibernate.cfg.xml")
                .buildSessionFactory();

        // Open Session
        Session session = factory.openSession();

        // Display message
        System.out.println("Hello World");

        // Close resources
        session.close();
        factory.close();
    }
}
Spread the love

Leave a Comment

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

Scroll to Top