💾

Hibernate Configuration and Retrieving Data

Jul 19, 2024

Hibernate Configuration and Annotated Classes

Key Points

Configuration File

  • hibernate.cfg.xml: Standard file name used for Hibernate configuration.
    • Important parameters: driver class, URL, username, password, dialect, hibernate.hbm2ddl.auto (update), show_sql (true).
  • Custom Configuration File: If the configuration file is named differently, e.g., hb.cfg.xml, you need to pass this name as a parameter when calling the configure method. config.configure("hb.cfg.xml")

Annotated Classes

  • Entity Classes: POJO classes representing database tables, annotated with Hibernate annotations.
    • Example: For Student table, we create a Student class annotated with @Entity, @Table, @Column, @Id.
  • Adding Annotated Class: Add this entity class to Hibernate configuration using the addAnnotatedClass method. config.addAnnotatedClass(Student.class);

Session and SessionFactory

  • SessionFactory: Create a SessionFactory object from the configuration. SessionFactory sessionFactory = config.buildSessionFactory();
  • Session: Create a session from the SessionFactory. Session session = sessionFactory.openSession();
  • Transaction: Begin and commit transactions. Transaction tx = session.beginTransaction(); tx.commit();

Example Code Walkthrough

Creating Configuration and Session

Configuration config = new Configuration().configure("hb.cfg.xml") .addAnnotatedClass(Student.class); SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction();

Saving Data to Database

Student student = new Student(); student.setId(3); student.setName("Charlie"); student.setDepartment("Mech"); student.setPercentage(80); session.save(student); tx.commit();

Retrieving Data from Database

Query<Student> query = session.createQuery("from Student", Student.class); List<Student> students = query.getResultList(); for(Student s: students) { System.out.println(s); }

HQL (Hibernate Query Language)

  • HQL: Similar to SQL but uses class names instead of table names. String hql = "from Student";
  • Select with where clause: String hql = "from Student s where s.percentage > 70"; Query<Student> query = session.createQuery(hql, Student.class); List<Student> students = query.getResultList(); for(Student s: students) { System.out.println(s); }
  • Formatting SQL Output: Add hibernate.format_sql property to hibernate.cfg.xml. <property name="hibernate.format_sql">true</property> ``

Important Considerations

  • Auto Commit: By default, auto commit is false in Hibernate, unlike JDBC.
  • Standard Code for Hibernate: You can create a template or shortcut for standard Hibernate setup code to avoid repetition.