Build Hibernate Applications
Hibernate
What is Hibernate?• A framework for persisting / saving Java objects in a database
Benefits of Hibernate
• Hibernate handles all of the low-level SQL
• Minimizes the amount of JDBC code you have to develop
• Hibernate provides the Object-to-Relational Mapping (ORM)
Hibernate and JDBC
• Hibernate uses JDBC for all database communications
SET UP YOUR ENVIRONMENT
Required Software
To Build Hibernate Applications, you need the following:
1. Java Integrated Development Environment (IDE)
2. Database Server
3. Hibernate JAR files and JDBC Driver
Setup Hibernate in Eclipse:
1. Create Eclipse Project
2. Download Hibernate Files
3. Download MySQL JDBC Driver
4. Add JAR files to Eclipse Project … Build Path
Testing The JDBC Connection
Create class for TestJdbc
package com.luv2code.com.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
public class TestJdbc {
public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/hb_student_tracker? useSSL=false&serverTimezone-UTC";
String user = "hbstudent";
String pass = "hbstudent";
try {
System.out.println("Connecting to database : "+ jdbcUrl);
Connection myConn = DriverManager.getConnection(jdbcUrl,user,pass);
System.out.println("Connection Successfull : "+ myConn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hibernate Development Process
1. Add Hibernate Configuration file2. Annotate Java Class
3. Develop Java Code to perform database operations
Hibernate Configuration file (hibernate.cfg.xml)
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">hbstudent</property>
<property name="connection.password">hbstudent</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Develop Java Code to perform database operations
Entity Class : Java class that is mapped to a database table
Two Options for Mapping:
- Option 1: XML config file (legacy)
- Option 2: Java Annotations (modern, preferred)
- Step 1: Map class to database table
- Step 2: Map fields to database columns
Step 1: Map class to database table
Comments
Post a Comment