com.belajar.ORMHibernate.Main.MainHibernate.java Source code

Java tutorial

Introduction

Here is the source code for com.belajar.ORMHibernate.Main.MainHibernate.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.belajar.ORMHibernate.Main;

import com.belajar.ORMHibernate.entity.Person;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

/**
 *
 * @author raditya
 */
public class MainHibernate {

    public static void main(String[] args) {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

        Person p = new Person();
        p.setName("Shinta");
        p.setPassword("diditshinta");
        System.out.print("saved!");

        Session session = sessionFactory.openSession();
        try {
            session.beginTransaction();
            session.save(p);
            session.getTransaction().commit();
        } catch (HibernateException hibernateException) {
            session.getTransaction().rollback();
        }
        session.close();

        session = sessionFactory.openSession();
        Query query = session.createQuery("from Person");
        List<Person> persons = query.list();
        for (Person person : persons) {
            System.out.println("Id: " + person.getId());
            System.out.println("Name: " + person.getName());
            System.out.println("Password: " + person.getPassword() + "\n");
        }

        session.close();
        sessionFactory.close();
    }
}