Quick Contact

    Hibernate

    Hibernate- One to One Unidirectional Mapping Annotation Example

    We create Instructor and InstructorDetail entities and we make a one-to-one unidirectional mapping between them.

    We will implement CRUD (create/save, read, update, delete) operations for Instructor and InstructorDetail entities.

    For Instructor DAO CRUD operations:

    voidsaveInstructor(Instructor instructor);

    voidupdateInstructor(Instructor instructor);

    voiddeleteInstructor(int id);

    InstructorgetInstructor(int id);

    For InstructorDetailDao DAO CRUD operations:

    voidsaveInstructorDetail(InstructorDetailinstructorDetail);

    voidupdateInstructorDetail(InstructorDetailinstructorDetail);

    InstructorDetailgetInstructorDetail(int id);

    Development Steps

    1. Create a Simple Maven Project
    2. Project Directory Structure
    3. Add jar Dependencies to pom.xml
    4. Creating the JPA Entities(Persistent classes)
    5. Create Hibernate DAO Classes
    6. Create a Hibernate configuration file – HibernateUtil.java (Java Configuration)
    7. Create the Main class and Run an Application
    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.

    3. Add dependencies to pom.xml

      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-one-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)

      We are creating a unidirectional mapping, we have placed @OneToOne annotation on the Instructor entity so that the instuctor_detail_id will create in an instructor table.

      Instructor JPA Entity

      packagenet.ducatindia.hibernate.entity;
      
      importjavax.persistence.CascadeType;
      importjavax.persistence.Column;
      importjavax.persistence.Entity;
      importjavax.persistence.GeneratedValue;
      importjavax.persistence.GenerationType;
      importjavax.persistence.Id;
      importjavax.persistence.JoinColumn;
      importjavax.persistence.OneToOne;
      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;
      
      @OneToOne(cascade=CascadeType.ALL)
      @JoinColumn(name="instructor_detail_id")
      privateInstructorDetailinstructorDetail;
      
      publicInstructor() {
      
          }
      
      publicInstructor(StringfirstName, StringlastName, Stringemail) {
      this.firstName=firstName;
      this.lastName=lastName;
      this.email= email;
          }
      
      publicintgetId() {
      return id;
          }
      
      publicvoidsetId(intid) {
      this.id = id;
          }
      
      publicStringgetFirstName() {
      returnfirstName;
          }
      
      publicvoidsetFirstName(StringfirstName) {
      this.firstName=firstName;
          }
      
      publicStringgetLastName() {
      returnlastName;
          }
      
      publicvoidsetLastName(StringlastName) {
      this.lastName=lastName;
          }
      
      publicStringgetEmail() {
      return email;
          }
      
      publicvoidsetEmail(Stringemail) {
      this.email= email;
          }
      
      publicInstructorDetailgetInstructorDetail() {
      returninstructorDetail;
          }
      
      publicvoidsetInstructorDetail(InstructorDetailinstructorDetail) {
      this.instructorDetail=instructorDetail;
          }
      }
      

      InstructorDetail JPA Entity

      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="instructor_detail")
      publicclassInstructorDetail {
      
      @Id
      @GeneratedValue(strategy=GenerationType.IDENTITY)
      @Column(name="id")
      privateint id;
      
      @Column(name="youtube_channel")
      privateStringyoutubeChannel;
      
      @Column(name="hobby")
      privateString hobby;
      
      publicInstructorDetail() {
      
          }
      
      publicInstructorDetail(StringyoutubeChannel, Stringhobby) {
      this.youtubeChannel=youtubeChannel;
      this.hobby= hobby;
          }
      
      publicintgetId() {
      return id;
          }
      
      publicvoidsetId(intid) {
      this.id = id;
          }
      
      publicStringgetYoutubeChannel() {
      returnyoutubeChannel;
          }
      
      publicvoidsetYoutubeChannel(StringyoutubeChannel) {
      this.youtubeChannel=youtubeChannel;
          }
      
      publicStringgetHobby() {
      return hobby;
          }
      
      publicvoidsetHobby(Stringhobby) {
      this.hobby= hobby;
          }
      }
      
    5. Create Hibernate DAO Classes

      InstructorDao.java

      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;
          }
      }
      

      InstructorDetailDao.java

      packagenet.ducatindia.hibernate.dao;
      
      importorg.hibernate.Session;
      importorg.hibernate.Transaction;
      
      importnet.ducatindia.hibernate.entity.InstructorDetail;
      importnet.ducatindia.hibernate.util.HibernateUtil;
      
      publicclassInstructorDetailDao {
      
      publicvoidsaveInstructorDetail(InstructorDetailinstructorDetail) {
      Transactiontransaction=null;
      try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
      // start a transaction
      transaction=session.beginTransaction();
      // save the student object
      session.save(instructorDetail);
      // commit transaction
      transaction.commit();
              } catch (Exception e) {
      if (transaction !=null) {
      transaction.rollback();
                  }
      e.printStackTrace();
              }
          }
      
      publicvoidupdateInstructorDetail(InstructorDetailinstructorDetail) {
      Transactiontransaction=null;
      try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
      // start a transaction
      transaction=session.beginTransaction();
      // save the student object
      session.update(instructorDetail);
      // commit transaction
      transaction.commit();
              } catch (Exception e) {
      if (transaction !=null) {
      transaction.rollback();
                  }
      e.printStackTrace();
              }
          }
      
      publicInstructorDetailgetInstructorDetail(intid) {
      
      Transactiontransaction=null;
      InstructorDetail instructor =null;
      try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
      // start a transaction
      transaction=session.beginTransaction();
      // get an instructor object
      instructor=session.get(InstructorDetail.class, id);
      // commit transaction
      transaction.commit();
              } catch (Exception e) {
      if (transaction !=null) {
      transaction.rollback();
                  }
      e.printStackTrace();
              }
      return instructor;
          }
      }
      
    6. Create a Hibernate configuration file – HibernateUtil.java (Java Configuration)

      The HibernateUtil Java configuration file contains information about the database and mapping file. Let’s create a HibernateUtil file and write the following code in it.

      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
       * @authorrajansingh
       *
       */
      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/javafx_demo?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.Instructor;
      importnet.ducatindia.hibernate.entity.InstructorDetail;
      
      publicclassManApp {
      publicstaticvoidmain(String[] args) {
      
      Instructorinstructor=newInstructor("Rajan", "Fadatare", "rajan@ducatinida.com");
      InstructorDetailinstructorDetail=newInstructorDetail("http://www.youtube.com", "Guitar");
      instructor.setInstructorDetail(instructorDetail);
      
      InstructorDaoinstructorDao=newInstructorDao();
      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.