Quick Contact

    Hibernate

    Hibernate One to Many Unidirectional Mapping Example

    1. Create a Simple Maven Project

      Use How to Create a Simple Maven Project in Eclipse article to create a simple Maven project in Eclipse IDE.

    2. Project Directory Structure

      Let’s create a packaging structure for the above created a simple maven project. Refer below screenshot for your reference.

    3. POM Dependencies

      We are using MySQL database so add MySQL dependency to pom.xml:

      < project
      xmlns="http://maven.apache.org/POM/4.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      < modelVersion>4.0.0< /modelVersion>
      < parent>
      < groupId>net.ducatindia.hibernate< /groupId>
      < artifactId>hibernate-tutorial< /artifactId>
      < version>0.0.1-SNAPSHOT< /version>
      < /parent>
      < artifactId>hibernate-one-to-many-example< /artifactId>
      < properties>
      < project.build.sourceEncoding>UTF-8< /project.build.sourceEncoding>
      < /properties>
      < dependencies>
      < !-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
      < dependency>
      < groupId>mysql< /groupId>
      < artifactId>mysql-connector-java< /artifactId>
      < version>8.0.13< /version>
      < /dependency>
      < !-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
      < dependency>
      < groupId>org.hibernate< /groupId>
      < artifactId>hibernate-core< /artifactId>
      < version>5.3.7.Final< /version>
      < /dependency>
      < /dependencies>
      < build>
      < sourceDirectory>src/main/java< /sourceDirectory>
      < plugins>
      < plugin>
      < artifactId>maven-compiler-plugin< /artifactId>
      < version>3.5.1< /version>
      < configuration>
      < source>1.8< /source>
      < target>1.8< /target>
      < /configuration>
      < /plugin>
      < /plugins>
      < /build>
      < /project>
      
    4. Creating the JPA Entities(Persistent classes)

      Let’s create JPA entities which we map with database tables. The @OneToMany JPA annotation is used to link one-to-many unidirectional entity mapping.

      Instructor JPA Entity – Instructor.java

      packagenet.ducatindia.hibernate.entity;
      
      importjava.util.ArrayList;
      importjava.util.List;
      
      importjavax.persistence.CascadeType;
      importjavax.persistence.Column;
      importjavax.persistence.Entity;
      importjavax.persistence.GeneratedValue;
      importjavax.persistence.GenerationType;
      importjavax.persistence.Id;
      importjavax.persistence.OneToMany;
      importjavax.persistence.Table;
      
      @Entity
      @Table(name="instructor")
      publicclassInstructor {
      
      @Id
      @GeneratedValue(strategy=GenerationType.IDENTITY)
      @Column(name="id")
      privateint id;
      
      @Column(name="first_name")
      privateStringfirstName;
      
      @Column(name="last_name")
      privateStringlastName;
      
      @Column(name="email")
      privateString email;
      
      @OneToMany(cascade=CascadeType.ALL)
      privateList< Course> courses =newArrayList< Course> ();
      
      publicInstructor() {
      
          }
      
      publicInstructor(StringfirstName, StringlastName, Stringemail) {
      this.firstName=firstName;
      this.lastName=lastName;
      this.email= email;
          }
      // getter and setter methods
      }
      

      Course JPA Entity – Course.java

      packagenet.ducatindia.hibernate.entity;
      
      importjavax.persistence.Column;
      importjavax.persistence.Entity;
      importjavax.persistence.GeneratedValue;
      importjavax.persistence.GenerationType;
      importjavax.persistence.Id;
      importjavax.persistence.Table;
      
      @Entity
      @Table(name="course")
      publicclassCourse {
      
      @Id
      @GeneratedValue(strategy=GenerationType.IDENTITY)
      @Column(name="id")
      privateint id;
      
      @Column(name="title")
      privateString title;
      
      publicCourse() {
      
          }
      // getter and setter methods
      }
      
    5. Create Hibernate DAO Classes

      InstructorDao.java

      Let’s create InstructorDao class add following hibernate DAO operations for Instructor entity:

      packagenet.ducatindia.hibernate.dao;
      
      importorg.hibernate.Session;
      importorg.hibernate.Transaction;
      
      importnet.ducatindia.hibernate.entity.Instructor;
      importnet.ducatindia.hibernate.util.HibernateUtil;
      
      publicclassInstructorDao {
      publicvoidsaveInstructor(Instructorinstructor) {
      Transactiontransaction=null;
      try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
      // start a transaction
      transaction=session.beginTransaction();
      // save the student object
      session.save(instructor);
      // commit transaction
      transaction.commit();
              } catch (Exception e) {
      if (transaction !=null) {
      transaction.rollback();
                  }
      e.printStackTrace();
              }
          }
      
      publicvoidupdateInstructor(Instructorinstructor) {
      Transactiontransaction=null;
      try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
      // start a transaction
      transaction=session.beginTransaction();
      // save the student object
      session.update(instructor);
      // commit transaction
      transaction.commit();
              } catch (Exception e) {
      if (transaction !=null) {
      transaction.rollback();
                  }
      e.printStackTrace();
              }
          }
      
      publicvoiddeleteInstructor(intid) {
      
      Transactiontransaction=null;
      try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
      // start a transaction
      transaction=session.beginTransaction();
      
      // Delete a instructor object
      Instructorinstructor=session.get(Instructor.class, id);
      if (instructor !=null) {
      session.delete(instructor);
      System.out.println("instructor is deleted");
                  }
      
      // commit transaction
      transaction.commit();
              } catch (Exception e) {
      if (transaction !=null) {
      transaction.rollback();
                  }
      e.printStackTrace();
              }
          }
      
      publicInstructorgetInstructor(intid) {
      
      Transactiontransaction=null;
      Instructorinstructor=null;
      try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
      // start a transaction
      transaction=session.beginTransaction();
      // get an instructor object
      instructor=session.get(Instructor.class, id);
      // commit transaction
      transaction.commit();
              } catch (Exception e) {
      if (transaction !=null) {
      transaction.rollback();
                  }
      e.printStackTrace();
              }
      return instructor;
          }
      }
      

      CourseDao.java

      Let’s create CourseDao class add following hibernate DAO operations for Course entity:

      packagenet.ducatindia.hibernate.dao;
      
      importorg.hibernate.Session;
      importorg.hibernate.Transaction;
      
      importnet.ducatindia.hibernate.entity.Course;
      importnet.ducatindia.hibernate.util.HibernateUtil;
      
      publicclassCourseDao {
      publicvoidsaveCourse(Coursecourse) {
      Transactiontransaction=null;
      try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
      // start a transaction
      transaction=session.beginTransaction();
      // save the student object
      session.save(course);
      // commit transaction
      transaction.commit();
              } catch (Exception e) {
      if (transaction !=null) {
      transaction.rollback();
                  }
      e.printStackTrace();
              }
          }
      
      publicvoidupdateCourse(Coursecourse) {
      Transactiontransaction=null;
      try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
      // start a transaction
      transaction=session.beginTransaction();
      // save the student object
      session.update(course);
      // commit transaction
      transaction.commit();
              } catch (Exception e) {
      if (transaction !=null) {
      transaction.rollback();
                  }
      e.printStackTrace();
              }
          }
      
      publicvoiddeleteCourse(intid) {
      
      Transactiontransaction=null;
      try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
      // start a transaction
      transaction=session.beginTransaction();
      
      // Delete a course object
      Coursecourse=session.get(Course.class, id);
      if (course !=null) {
      session.delete(course);
      System.out.println("course is deleted");
                  }
      
      // commit transaction
      transaction.commit();
              } catch (Exception e) {
      if (transaction !=null) {
      transaction.rollback();
                  }
      e.printStackTrace();
              }
          }
      
      publicCoursegetCourse(intid) {
      
      Transactiontransaction=null;
      Coursecourse=null;
      try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
      // start a transaction
      transaction=session.beginTransaction();
      // get an course object
      course=session.get(Course.class, id);
      // commit transaction
      transaction.commit();
              } catch (Exception e) {
      if (transaction !=null) {
      transaction.rollback();
                  }
      e.printStackTrace();
              }
      return course;
          }
      }
      
    6. Hibernate Utility File(Java Configuration)

      Create a helper class HibernateUtil to bootstrap hibernate.

      Map the Instructor and Course entities using the MetadataSources.addAnnotatedClass() method.

      packagenet.ducatindia.hibernate.util;
      
      importjava.util.Properties;
      
      importorg.hibernate.SessionFactory;
      importorg.hibernate.boot.registry.StandardServiceRegistryBuilder;
      importorg.hibernate.cfg.Configuration;
      importorg.hibernate.cfg.Environment;
      importorg.hibernate.service.ServiceRegistry;
      
      importnet.ducatindia.hibernate.entity.Course;
      importnet.ducatindia.hibernate.entity.Instructor;
      
      /**
       * Java based configuration
       * @authorrajansharma
       *
       */
      publicclassHibernateUtil {
      privatestaticSessionFactorysessionFactory;
      
      publicstaticSessionFactorygetSessionFactory() {
      if (sessionFactory==null) {
      try {
      Configurationconfiguration=newConfiguration();
      
      // Hibernate settings equivalent to hibernate.cfg.xml's properties
      Properties settings =newProperties();
      settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
      settings.put(Environment.URL, "jdbc:mysql://localhost:3306/hibernate_db?useSSL=false");
      settings.put(Environment.USER, "root");
      settings.put(Environment.PASS, "root");
      settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5InnoDBDialect");
      
      settings.put(Environment.SHOW_SQL, "true");
      
      settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
      
      settings.put(Environment.HBM2DDL_AUTO, "create-drop");
      
      configuration.setProperties(settings);
      configuration.addAnnotatedClass(Instructor.class);
      configuration.addAnnotatedClass(Course.class);
      
      ServiceRegistryserviceRegistry=newStandardServiceRegistryBuilder()
                          .applySettings(configuration.getProperties()).build();
      System.out.println("Hibernate Java ConfigserviceRegistry created");
      sessionFactory=configuration.buildSessionFactory(serviceRegistry);
      returnsessionFactory;
      
                  } catch (Exception e) {
      e.printStackTrace();
                  }
              }
      returnsessionFactory;
          }
      }
      
    7. Create the Main class and Run an Application

      packagenet.ducatindia.hibernate;
      
      importnet.ducatindia.hibernate.dao.InstructorDao;
      importnet.ducatindia.hibernate.entity.Course;
      importnet.ducatindia.hibernate.entity.Instructor;
      
      publicclassManApp {
      publicstaticvoidmain(String[] args) {
      
      InstructorDaoinstructorDao=newInstructorDao();
      
      Instructorinstructor=newInstructor("Rajan", "sharma", "rajan@ducatindia.com");
      instructorDao.saveInstructor(instructor);
      
      // create some courses
      Course tempCourse1 =newCourse("Learn Spring Boot");
      instructor.getCourses().add(tempCourse1);
      
      Course tempCourse2 =newCourse("Learn hibernate");
      instructor.getCourses().add(tempCourse2);
      
      instructorDao.saveInstructor(instructor);
          }
      }
      

    Apply now for Advanced Java Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.