Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Inheritance in Hibernate

    • 0
    • 5
    • 2
    • 4
    • 0
    • 0
    • 0
    • 0
    • 404
    Comment on it

    Sometimes we need to apply inheritance in Hibernate as per our requirement. Here I'm explaining the Hibernate Inheritance using "Table per subclass: using a discriminator".

    Suppose we've a class User with subclass Student. And in this approach we'll save all the classes in a single Table. We'll use a discriminator as key to uniquely identify the base type of the class hierarchy.

    First, create the table to save the class hierarchy as below:

    CREATE TABLE `user` (
        `user_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
        `firstname` VARCHAR(50) NULL DEFAULT NULL,
        `lastname` VARCHAR(50) NULL DEFAULT NULL,
        `joining_date` DATE NULL DEFAULT NULL,
        `department_name` VARCHAR(50) NULL DEFAULT NULL,
        `discriminator` VARCHAR(20) NOT NULL,
        PRIMARY KEY (`user_d`)
    )
    

    The USER table will store both Student and User objects.

    Now create the POJO for User and Student as below:

    User.java:

    public class User {
    
        private Long userId;
        private String firstname;
        private String lastname;
    
        // Constructors and Getter/Setter methods,
    } 
    

    Student.java

    import java.util.Date;
    
    public class Student extends User {
    
        private Date joiningDate;
        private String departmentName;
    
        // Constructors and Getter/Setter methods,
    }
    

    Then create User.hbm.xml as below:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC
            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
    <hibernate-mapping package="net.viralpatel.hibernate">
    
        <class name="User" table="USER" discriminator-value="U">
            <id name="userId" column="user_id">
                <generator class="native" />
            </id>
    
            <discriminator column="DISCRIMINATOR" type="string" />
    
            <property name="firstname" />
            <property name="lastname" column="lastname" />
    
            <subclass name="Student" extends="User" discriminator-value="S">
                    <property name="departmentName" column="department_name" />
                    <property name="joiningDate" type="date" column="joining_date" />
            </subclass>
        </class>
    </hibernate-mapping>
    

    Note that we have defined only one hibernate mapping (hbm) file User.hbm.xml. Both User and Student model class are defined within one hbm file.

    tag is used to define the discriminator column.

    tag is used to map the subclass Student. Note that we have not used the usual tag to map Student as it falls below in the hierarchy tree.

    The discriminator-value for User is defined as U and that for Student is defined S, Thus, when Hibernate will persist the data for user or student it will accordingly populate this value.

    Now create the main class from where you want to insert values in the Database

    public class Main {
    
        public static void main(String[] args) {
    
            SessionFactory sf = HibernateUtil.getSessionFactory();
            Session session = sf.openSession();
            session.beginTransaction();
    
            User user = new User("Aman", "Rana");
            session.save(user);
    
            Student student = new Student("Ankit", "Kashyap", "Computer Science", new Date());
            session.save(student);
    
            session.getTransaction().commit();
            session.close();
    
        }
    }
    

    The Main class is used to persist User and Student object instance. Note that both these classes are persisted in same table USER. The discriminator column is used to distinguished between the entities.

    Output:

    Hibernate: insert into User (FIRSTNAME, LASTNAME, discriminator) values (?, ?, 'U')
    Hibernate: insert into User (FIRSTNAME, LASTNAME, department_name, joining_date, discriminator) values (?, ?, ?, ?, 'S')
    

    Hope this will help you :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: