(Annotation and Configuration) : Chapter 23
In this section, you will learn how to develop a CRUD application using hibernate annotation.Follows the following steps for developing the CRUD application in hibernate annotation. Step 1: Create Domain Entity Class
Student.java view plainprint? 1. package com.sdnext.hibernate.tutorial.dto; 2. 3. import java.io.Serializable; 4. 5. import javax.persistence.Column; 6. import javax.persistence.GeneratedValue; 7. import javax.persistence.GenerationType; 8. import javax.persistence.Id; 9. 10. @Entity 11. @Table(name="STUDENT")
12. public class Student implements Serializable 13. {
14. 15. /**
16. * serialVersionUID 17. */
18. private static final long serialVersionUID = 8633415090390966715L; 19. @Id
20. @Column(name="ID")
21. @GeneratedValue(strategy=GenerationType.AUTO) 22. private int id;
23. @Column(name="STUDENT_NAME") 24. private String studentName; 25. @Column(name="ROLL_NUMBER") 26. private int rollNumber; 27. @Column(name="COURSE") 28. private String course; 29. public int getId() { 30. return id;
31. }
32. public void setId(int id) { 33. this.id = id;
34. }
35. public String getStudentName() { 36. return studentName;
37. }
38. public void setStudentName(String studentName) { 39. this.studentName = studentName;
40. }
41. public int getRollNumber() { 42. return rollNumber;
43. }
44. public void setRollNumber(int rollNumber) { 45. this.rollNumber = rollNumber;
46. }
47. public String getCourse() { 48. return course;
49. }
50. public void setCourse(String course) { 51. this.course = course;
52. } 53. }
Step 2: Create Hibernate Configuration file hibernate.cfg.xml
file contains
(a.) database connection setting (database driver (com.mysql.jdbc.Driver), url (jdbc:mysql://localhost:3306/hibernateDB2), username (root) and password (root)), (b.) SQL dialect (dialect - org.hibernate.dialect.MySQLDialect),
(c.) enable hibernate's automatic session context management (current_session_context_class - thread),
(d.) disable the second level cache (cache.provider_class - org.hibernate.cache.NoCacheProvider), (e.) print all executed SQL to stdout (show_sql - true) and
(f.) drop and re-create the database schema on startup (hbm2ddl.auto - none). view plainprint?
1. <hibernate-configuration> 2. <session-factory>
3. <!-- Database connection settings -->
4. <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 5. <property name="connection.url">jdbc:mysql://localhost:3306/hibernateDB2</pro perty>
6. <property name="connection.username">root</property> 7. <property name="connection.password">root</property> 8.
9. <!-- JDBC connection pool (use the built-in) --> 10. <property name="connection.pool_size">1</property> 11.
12. <!-- SQL dialect -->
13. <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 14.
15. <!-- Enable Hibernate's automatic session context management --> 16. <property name="current_session_context_class">thread</property> 17.
18. <!-- Disable the second-level cache -->
19. <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</pr operty>
20.
21. <!-- Echo all executed SQL to stdout --> 22. <property name="show_sql">true</property> 23.
24. <!-- Drop and re-create the database schema on startup --> 25. <property name="hbm2ddl.auto">update</property>
26.
27. <mapping class="com.sdnext.hibernate.tutorial.dto.Student"> 28.
29. </mapping></session-factory> 30. </hibernate-configuration> Step 3: Create Hibernate Utility Class
HibernateUtil.java view plainprint?
1. package com.sdnext.hibernate.tutorial.utility; 2.
3. import org.hibernate.SessionFactory;
4. import org.hibernate.cfg.AnnotationConfiguration; 5.
6. public class HibernateUtil 7. {
8. private static final SessionFactory sessionFactory; 9. static
10. { 11. try 12. {
13. sessionFactory = new AnnotationConfiguration().configure().buildSessionFactor y();
14. }
15. catch(Throwable th){
16. System.err.println("Enitial SessionFactory creation failed"+th); 17. throw new ExceptionInInitializerError(th);
18. } 19. }
20. public static SessionFactory getSessionFactory(){ 21. return sessionFactory;
22. } 23. }
Step 4: Create Student on the database. CreateStudent.java view plainprint? 1. package com.sdnext.hibernate.tutorial; 2. 3. import org.hibernate.Session; 4. import org.hibernate.SessionFactory; 5. 6. import com.sdnext.hibernate.tutorial.dto.Student; 7. import com.sdnext.hibernate.tutorial.utility.HibernateUtil; 8.
9. public class CreateStudent { 10.
11. /**
12. * @param args 13. */
14. public static void main(String[] args) 15. {
16. //Create student entity object 17. Student student = new Student();
18. student.setStudentName("Dinesh Rajput"); 19. student.setRollNumber(01);
20. student.setCourse("MCA"); 21.
22. //Create session factory object
23. SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 24. //getting session object from session factory
25. Session session = sessionFactory.openSession(); 26. //getting transaction object from session object 27. session.beginTransaction();
28.
29. session.save(student);
31. session.getTransaction().commit(); 32. session.close(); 33. sessionFactory.close(); 34. } 35. } OUTPUT:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version). log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into STUDENT (COURSE, ROLL_NUMBER, STUDENT_NAME) values (?, ?, ?) Inserted Successfully
Now the following code the reading the student data from database. Step 5: Reading the Student data from the database table STUDENT ReadStudent.java view plainprint? 1. package com.sdnext.hibernate.tutorial; 2. 3. import java.util.List; 4. 5. import org.hibernate.Query; 6. import org.hibernate.Session; 7. import org.hibernate.SessionFactory; 8. 9. import com.sdnext.hibernate.tutorial.dto.Student; 10. import com.sdnext.hibernate.tutorial.utility.HibernateUtil; 11.
12. public class ReadStudent { 13.
14. /**
15. * @param args 16. */
17. public static void main(String[] args) 18. {
19. //Create session factory object
20. SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 21. //getting session object from session factory
22. Session session = sessionFactory.openSession(); 23. //getting transaction object from session object 24. session.beginTransaction();
25. Query query = session.createQuery("from Student"); 26. List<student> students = query.list();
27. for(Student student : students) 28. {
29. System.out.println("Roll Number: "+student.getRollNumber()+", Student Name: "+st udent.getStudentName()+", Course: "+student.getCourse());
30. } 31. session.getTransaction().commit(); 32. sessionFactory.close(); 33. } 34. } 35. </student> Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version). log4j:WARN Please initialize the log4j system properly.
Hibernate: select student0_.ID as ID0_, student0_.COURSE as COURSE0_, student0_.ROLL_NUMBER as ROLL3_0_, student0_.STUDENT_NAME as STUDENT4_0_ from STUDENT student0_
Roll Number: 1, Student Name: Dinesh Rajput, Course: MCA Roll Number: 2, Student Name: Anamika Rajput, Course: PGDCP Roll Number: 3, Student Name: Adesh Rajput, Course: MA Roll Number: 4, Student Name: Vinesh Rajput, Course: BA
The following code is for updating the data into the database table "STUDENT". Step 6: Update the Student Record in the Database.
UpdateStudent.java view plainprint? 1. package com.sdnext.hibernate.tutorial; 2. 3. import org.hibernate.Session; 4. import org.hibernate.SessionFactory; 5. 6. import com.sdnext.hibernate.tutorial.dto.Student; 7. import com.sdnext.hibernate.tutorial.utility.HibernateUtil; 8.
9. public class UpdateStudent { 10.
11. /**
12. * @param args 13. */
14. public static void main(String[] args) 15. {
16. //Create session factory object
17. SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 18. //getting session object from session factory
19. Session session = sessionFactory.openSession(); 20. //getting transaction object from session object 21. session.beginTransaction();
22.
23. Student student = (Student)session.get(Student.class, 2); 24. student.setStudentName("Sweety Rajput");
25. System.out.println("Updated Successfully"); 26. session.getTransaction().commit(); 27. sessionFactory.close(); 28. } 29. } Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version). log4j:WARN Please initialize the log4j system properly.
Hibernate: select student0_.ID as ID0_0_, student0_.COURSE as COURSE0_0_,
student0_.ROLL_NUMBER as ROLL3_0_0_, student0_.STUDENT_NAME as STUDENT4_0_0_ from STUDENT student0_ where student0_.ID=?
Hibernate: update STUDENT set COURSE=?, ROLL_NUMBER=?, STUDENT_NAME=? where ID=? Updated Successfully
Step 7: Delete the student data from the database. DeleteStudent.java view plainprint? 1. package com.sdnext.hibernate.tutorial; 2. 3. import org.hibernate.Session; 4. import org.hibernate.SessionFactory; 5. 6. import com.sdnext.hibernate.tutorial.dto.Student; 7. import com.sdnext.hibernate.tutorial.utility.HibernateUtil; 8.
9. public class DeleteStudent { 10.
11. /**
12. * @param args 13. */
14. public static void main(String[] args) 15. {
16. //Create session factory object
17. SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 18. //getting session object from session factory
19. Session session = sessionFactory.openSession(); 20. //getting transaction object from session object 21. session.beginTransaction();
22. Student student = (Student)session.load(Student.class, 4); 23. session.delete(student);
24. System.out.println("Deleted Successfully"); 25. session.getTransaction().commit();
26. sessionFactory.close(); 27. }
28. } Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version). log4j:WARN Please initialize the log4j system properly.
Hibernate: select student0_.ID as ID0_0_, student0_.COURSE as COURSE0_0_,
student0_.ROLL_NUMBER as ROLL3_0_0_, student0_.STUDENT_NAME as STUDENT4_0_0_ from STUDENT student0_ where student0_.ID=?
Deleted Successfully