Search code examples
javahibernatepersistencedao

Hibernate - How do I persist an Object?


So I've made a simple hibernate application, and using HibernateUtil static method have initiated a SessionFactory which provides an appropriate session.

Question is - how can I persist using this code ? And I am further confused as to how I could build out from this design to incorporate the HibernateUtil for each of my objects needs ?

package com.hibernation.main;

import com.hibernation.model.Animal;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;


/**
 * Created by jonathan on 27/12/16.
 */
public class Earth {

    public static void main(String[] args){

        Animal a = new Animal(1,"lizard", "gekko", "test");

        HibernateUtil();
    }

    public static void HibernateUtil(){

        // create configuration instance and pass in the
        // hibernate configuration file.
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");

        // version 4.x and up, service registry is being used.
        // The ServiceRegistry scopes the Service.
        // The ServiceRegistry manages the lifecycle of the Service.
        // The ServiceRegistry handles injecting dependencies into the Service
        // (actually both a pull and a push/injection approach are supported).
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

        // create a Session factory instance: session factory creates sessions
        // at the request of clients.
        // conceptually, this is a single data store that is thread safe.
        // should be wrapped in a singleton (HibernateUtil being a common convention)
        // the internal state is immutable - once it is created the state is set.
        SessionFactory factory = configuration.buildSessionFactory(serviceRegistry);

        // get the current session.
        Session session = factory.getCurrentSession();

        // begin transaction
        session.getTransaction().begin();

        // Print out all required information
        System.out.println("Session Is Opened :: "+ session.isOpen());
        System.out.println("Session Is Connected :: "+ session.isConnected());



        // commit transaction
        session.getTransaction().commit();




    }



}

Solution

  • Question is - how can I persist using this code ?

    You can not, you must modify the code.

    You must save the entity like this:

    /**
     * Created by jonathan on 27/12/16.
     */
    public class Earth {
    
        public static void main(String[] args){
    
            Animal a = new Animal(1,"lizard", "gekko", "test");
    
            HibernateUtil(a);
        }
    
        public static void HibernateUtil(Animal a){
    
            // create configuration instance and pass in the
            // hibernate configuration file.
            Configuration configuration = new Configuration();
            configuration.configure("hibernate.cfg.xml");
    
            // version 4.x and up, service registry is being used.
            // The ServiceRegistry scopes the Service.
            // The ServiceRegistry manages the lifecycle of the Service.
            // The ServiceRegistry handles injecting dependencies into the Service
            // (actually both a pull and a push/injection approach are supported).
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    
            // create a Session factory instance: session factory creates sessions
            // at the request of clients.
            // conceptually, this is a single data store that is thread safe.
            // should be wrapped in a singleton (HibernateUtil being a common convention)
            // the internal state is immutable - once it is created the state is set.
            SessionFactory factory = configuration.buildSessionFactory(serviceRegistry);
    
            // get the current session.
            Session session = factory.getCurrentSession();
    
            // begin transaction
            session.getTransaction().begin();
    
            // Print out all required information
            System.out.println("Session Is Opened :: "+ session.isOpen());
            System.out.println("Session Is Connected :: "+ session.isConnected());
            session.save(a);
    
    
            // commit transaction
            session.getTransaction().commit();
    
    
    
    
        }
    
    
    
    }
    

    Beware

    This is a poor example because it is very procedual and not Object-Oriented and containing only whats the minimum changes to your Code. There are many other problems you will have to fix like the problem that you will loose access to the constructed sessionfactory, please read about OOD.

    IoC and Demeter's Law forces us to use a TransactionManager. Spring-TX is a usual State-of-the-art implementation.