Quick Contact

    Hibernate

    Hibernate PrimaryKeyJoinColumn

    Hibernate will ensure that it will use a common primary key value in both the tables. This way primary key of Employee can safely be assumed the primary key of Account also.

    Employee JPA Entity

    Let’s create Employee JPA entity and account field is annotated with PrimaryKeyJoinColumn annotation:

    packagenet.ducatindia.hibernate.entity.sharedPrimaryKey;
    
    importjava.io.Serializable;
    
    importjavax.persistence.CascadeType;
    importjavax.persistence.Column;
    importjavax.persistence.Entity;
    importjavax.persistence.GeneratedValue;
    importjavax.persistence.GenerationType;
    importjavax.persistence.Id;
    importjavax.persistence.OneToOne;
    importjavax.persistence.PrimaryKeyJoinColumn;
    importjavax.persistence.Table;
    importjavax.persistence.UniqueConstraint;
    
    @Entity(name = "SharedPrimaryKeyEmployeeEntity")
    @Table(name = "Employee", uniqueConstraints = {
    @UniqueConstraint(columnNames = "ID"),
    @UniqueConstraint(columnNames = "EMAIL")
    })
    public class Employee implements Serializable {
    
    private static final long serialVersionUID = -1798070786993154676 L;
    
        @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    private Integer employeeId;
    
    @Column(name = "EMAIL", unique = true, nullable = false, length = 100)
    private String email;
    
    @Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
    private String firstName;
    
    @Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
    private String lastName;
    
    @OneToOne(cascade = CascadeType.ALL)
        @PrimaryKeyJoinColumn
    private Account account;
    
    public Integer getEmployeeId() {
    returnemployeeId;
        }
    
    public void setEmployeeId(Integer employeeId) {
    this.employeeId = employeeId;
        }
    
    public String getEmail() {
    return email;
        }
    
    public void setEmail(String email) {
    this.email = email;
        }
    
    public String getFirstName() {
    returnfirstName;
        }
    
    public void setFirstName(String firstName) {
    this.firstName = firstName;
        }
    
    public String getLastName() {
    returnlastName;
        }
    
    public void setLastName(String lastName) {
    this.lastName = lastName;
        }
    
    public Account getAccount() {
    return account;
        }
    
    public void setAccount(Account account) {
    this.account = account;
        }
    }
    

    Account JPA Entity

    In the Account JPA entity side, it will remain dependent on the owner entity (Employee) for the mapping.

    packagenet.ducatindia.hibernate.entity.sharedPrimaryKey;

    importjava.io.Serializable;
    
    importjavax.persistence.CascadeType;
    importjavax.persistence.Column;
    importjavax.persistence.Entity;
    importjavax.persistence.GeneratedValue;
    importjavax.persistence.GenerationType;
    importjavax.persistence.Id;
    importjavax.persistence.OneToOne;
    importjavax.persistence.Table;
    importjavax.persistence.UniqueConstraint;
    
    importorg.hibernate.annotations.GenericGenerator;
    importorg.hibernate.annotations.Parameter;
    
    @Entity(name="SharedPrimaryKeyAccountEntity")
    @Table(name="ACCOUNT", uniqueConstraints= {
    @UniqueConstraint(columnNames="ID")
    })
    publicclassAccountimplementsSerializable {
    
    privatestaticfinallongserialVersionUID=-6790693372846798580L;
    
    @Id
    @Column(name="ID", unique=true, nullable=false)
    @GeneratedValue(generator="gen")
    @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="employee"))
    privateIntegeraccountId;
    
    @Column(name="ACC_NUMBER", unique=true, nullable=false, length=100)
    privateStringaccountNumber;
    
    @OneToOne(mappedBy="account", cascade=CascadeType.ALL)
    privateEmployeeemployee;
    
    publicEmployeegetEmployee() {
    return employee;
        }
    
    publicvoidsetEmployee(Employeeemployee) {
    this.employee= employee;
        }
    
    publicIntegergetAccountId() {
    returnaccountId;
        }
    
    publicvoidsetAccountId(IntegeraccountId) {
    this.accountId=accountId;
        }
    
    publicStringgetAccountNumber() {
    returnaccountNumber;
        }
    
    publicvoidsetAccountNumber(StringaccountNumber) {
    this.accountNumber=accountNumber;
        }
    }
    

    Create a Hibernate configuration file – hibernate.cfg.xml

    The configuration file contains information about the database and mapping file. Conventionally, its name should be hibernate.cfg.xml. Let’s create an XML file named hibernate.cfg.xml under the resources folder and write the following code in it.

    < !DOCTYPEhibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    < hibernate-configuration>
    < session-factory>
    < !-- JDBC Database connection settings -->
    < propertyname="connection.driver_class">com.mysql.cj.jdbc.Driver< /property>
    < propertyname="connection.url">jdbc:mysql://localhost:3306/java_demo?useSSL=false< /property>
    < propertyname="connection.username">root< /property>
    < propertyname="connection.password">root< /property>
    < !-- JDBC connection pool settings ... using built-in test pool -->
    < propertyname="connection.pool_size">1< /property>
    < !-- Select our SQL dialect -->
    < propertyname="dialect">org.hibernate.dialect.MySQL5Dialect< /property>
    < !-- Echo the SQL to stdout -->
    < propertyname="show_sql">true< /property>
    < !-- Set the current session context -->
    < propertyname="current_session_context_class">thread< /property>
    < !-- Drop and re-create the database schema on startup -->
    < propertyname="hbm2ddl.auto">create-drop< /property>
    < !--dbcp connection pool configuration -->
    < propertyname="hibernate.dbcp.initialSize">5< /property>
    < propertyname="hibernate.dbcp.maxTotal">20< /property>
    < propertyname="hibernate.dbcp.maxIdle">10< /property>
    < propertyname="hibernate.dbcp.minIdle">5< /property>
    < propertyname="hibernate.dbcp.maxWaitMillis">-1< /property>
    < !--< mapping class="net.ducatindia.hibernate.entity.foreignKeyAsso.Employee"/>< mapping class="net.ducatindia.hibernate.entity.foreignKeyAsso.Account"/> -->
    < mappingclass="net.ducatindia.hibernate.entity.sharedPrimaryKey.Employee"/>
    < mappingclass="net.ducatindia.hibernate.entity.sharedPrimaryKey.Account"/>
    < !--< mapping class="net.ducatindia.hibernate.entity.joinTable.Employee"/>< mapping class="net.ducatindia.hibernate.entity.joinTable.Account"/> -->
    < /session-factory>
    < /hibernate-configuration>
    

    Hibernate Utility Class – HibernateUtil.java

    Create a helper class to bootstrap hibernate SessionFactory. In most Hibernate applications, the SessionFactory should be instantiated once during application initialization. The single instance should then be used by all code in a particular process, and any Session should be created using this single SessionFactory.

    The SessionFactory is thread-safe and can be shared; a Session is a single-threaded object. Let’s create a HibernateUtil class to configure singleton SessionFactory and use it throughout the application. The bootstrapping API is quite flexible, but in most cases, it makes the most sense to think of it as a 3 step process:

    • Build the StandardServiceRegistry
    • Build the Metadata
    • Use those 2 to build the SessionFactory
    packagenet.ducatindia.hibernate.util;
    
    importorg.hibernate.SessionFactory;
    importorg.hibernate.boot.Metadata;
    importorg.hibernate.boot.MetadataSources;
    importorg.hibernate.boot.registry.StandardServiceRegistry;
    importorg.hibernate.boot.registry.StandardServiceRegistryBuilder;
    
    publicclassHibernateUtil {
    privatestaticStandardServiceRegistry registry;
    privatestaticSessionFactorysessionFactory;
    
    publicstaticSessionFactorygetSessionFactory() {
    if (sessionFactory==null) {
    try {
    // Create registry
    registry=newStandardServiceRegistryBuilder().configure().build();
    
    // Create MetadataSources
    MetadataSources sources =newMetadataSources(registry);
    
    // Create Metadata
    Metadatametadata=sources.getMetadataBuilder().build();
    
    // Create SessionFactory
    sessionFactory=metadata.getSessionFactoryBuilder().build();
    
                } catch (Exception e) {
    e.printStackTrace();
    if (registry !=null) {
    StandardServiceRegistryBuilder.destroy(registry);
                    }
                }
            }
    returnsessionFactory;
        }
    
    publicstaticvoidshutdown() {
    if (registry !=null) {
    StandardServiceRegistryBuilder.destroy(registry);
            }
        }
    }
    

    Create the Test class and Run an Application

    packagenet.ducatindia.hibernate.test;
    
    importorg.hibernate.Session;
    
    
    importnet.ducatindia.hibernate.entity.sharedPrimaryKey.Account;
    importnet.ducatindia.hibernate.entity.sharedPrimaryKey.Employee;
    importnet.ducatindia.hibernate.util.HibernateUtil;
    
    publicclassTestSharedPrimaryKey {
    
    publicstaticvoidmain(String[] args) {
    Sessionsession=HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    
    Accountaccount=newAccount();
    account.setAccountNumber("123-345-65454");
    
    //Add new Employee object
    Employeeemp=newEmployee();
    emp.setEmail("demo-user@mail.com");
    emp.setFirstName("demo");
    emp.setLastName("user");
    
    emp.setAccount(account);
    account.setEmployee(emp);
    //Save Employee
    session.save(emp);
    
    
    session.getTransaction().commit();
    HibernateUtil.shutdown();
        }
    }
    

    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.