Here we go... This might help you if there anyone learning Hibernate in IntelliJ at 2020 :)
Create a JAVA project in IntelliJ
2)Type Hibernate in the search box to locate the necessary plugin in the list.
If the checkbox next to Hibernate is not selected, select it to enable the plugin.
Click OK.
Add JDBC driver and test connection
using the common code snippet
if it working fine then add the Hibernate Config file to your root of the src directory
Terminology
Entity class : Java class that map to a database table
This Entity class should map to the actual database table
ORM - object-relational mapping
so there should be some method mapping this class to a db table
JAVA Annotations-Modern and Preferred one for mapping
step 1: Map the class to the database table
@Entity
@Table(name="db_name")
step 2: Map fields to database columns
@Id(signify primary key)
@Column(name="column_name")
like here..
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {
@Id
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
public Student(){
}
}
Develop Java code to perform database operations
Two key players in Hibernate:
SessionFactory:
this one read the hibernate config file and create session objects.
Just because of the heavy object we only create it once in-app and use
it over and over again.
Session :
It's like a wrapper in JDBC connection and used to save/retrieve
objects from the database. This is a short-lived object and retrieved
from SessionFactory.
public static void main(String [] args){
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
Session session = factory.getCurrentSession();
try{
// use the session object to save/ retrieve java objects
//create a test db object
Student temoStudent = new Student("Tim","NIke","timnike@gmail.com");
// start transaction
session.beginTransaction();
// save the student
session.save(tempStudent);
//commit the transaction
session.getTransaction().commit();
}finally {
factory.close();
}
}