/
ReadStudentDemo.java
69 lines (41 loc) · 1.64 KB
/
ReadStudentDemo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.luv2code.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.luv2code.hibernate.demo.entity.Student;
public class ReadStudentDemo {
public static void main(String[] args) {
//create a Session Factory
SessionFactory sessionFactory = new Configuration().
configure("hibernate.cfg.xml").
addAnnotatedClass(Student.class).
buildSessionFactory();
//create a Session
Session session = sessionFactory.getCurrentSession();
try{
System.out.println("Creating a new Student object...");
//create the Student object
Student student = new Student("John", "Smith","john.smith@gmail.com");
//start a transaction
session.beginTransaction();
//Save the Student object to the database
session.save(student);
System.out.println("Java object saved to the database");
//commit the transaction
session.getTransaction().commit();
//Get the primary key of the student
System.out.println("Saved student. Generated Id by MySQL database : " + student.getId());
//Get a new session and begin transaction
session = sessionFactory.getCurrentSession();
session.beginTransaction();
//Read the student
System.out.println("Getting the student based on id: " + student.getId());
Student readStudent = session.get(Student.class, student.getId()); //specify PRIMARY KEY of the student
System.out.println("Retrieved student : " + student);
//commit the transaction
session.getTransaction().commit();
}finally{
sessionFactory.close();
}
}
}