Saturday, January 2, 2016

Java: Hibernate without configuration files

This Hibernate project does not require any configuration files related to hibernate. Maven is required to get the dependencies. So I will provide the pom.xml bellow. This also starts h2database console mode. When you run this notice the h2 icon which appears in the system tray. The crucial part is hibernate configuration setup.

TestHibernate.java

 package jpatest;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;

import org.h2.tools.Server;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;



public class TestHibernate{

 public static boolean ping(String url, int timeout) {
     url = url.replaceFirst("^https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

     try {
         HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
         connection.setConnectTimeout(timeout);
         connection.setReadTimeout(timeout);
         connection.setRequestMethod("GET");
         int responseCode = connection.getResponseCode();
         System.out.println(responseCode);
         return (200 <= responseCode && responseCode <= 399);
     } catch (IOException exception) {
         return false;
     }
 }
 
 public static void main(String[] args) {
  
  try {
   if(!ping("http://localhost:8082/login.jsp",10000)){
    System.out.println("starting");
    org.h2.tools.Console.main(new String[]{});
//    Server.createTcpServer(new String[]{}).start();
//    Server.createWebServer(new String[]{"-ifExists"});
     
   }
   
  } catch (Exception e) {
   e.printStackTrace();
   
  }
  
  SessionFactory sessionFactory = new Configuration()
      //  .addPackage("com.lara.entity") //the fully qualified package name
  .addAnnotatedClass(Person.class)
  .addAnnotatedClass(Degree.class)
       // .addResource("test/animals/orm.xml")
        //.configure()             //This method .configure() looks for hibernate.cfg.xml uncommenting this will cause error like hibernate.cfg.xml not found 
        .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
        .setProperty("hibernate.connection.driver_class", "org.h2.Driver")
        .setProperty("hibernate.connection.url", "jdbc:h2:tcp://localhost/~/myhibernatetest")
        .setProperty("hibernate.connection.user", "sa")
        .setProperty("hibernate.connection.password", "")
        .setProperty("hibernate.hbm2ddl.auto", "create")
        .setProperty("hibernate.show_sql", "true")
        .buildSessionFactory();
  
  Session session = sessionFactory.openSession();
  Transaction txn = session.beginTransaction();
  txn.begin();
  
  Person p= new Person();
  p.setFirstName("Samajit");
  p.setLastName("Samanta");
   
  List<Degree> degree = new ArrayList<Degree>();
  
  Degree  d= new Degree();
  d.degree = "12th";
  d.percentage = 80.1;
  d.addPerson(p);
  
  Degree d1 = new Degree();
  d1.degree = "Btech";
  d1.percentage = 75d;
  d1.addPerson( p);
  
  degree.add(d);
  degree.add(d1);
  
  
  p.setDegree(degree);
  session.save(p);
//  session.save(d);
//  session.save(d1);
  
  List list = session.createCriteria(Person.class).list();
  System.out.println(list);
  txn.commit();
  session.close();
  
 }

}

@Entity 
class Degree {

 @Id @GeneratedValue
 Long id;
 
 public String degree;
 
 public Double percentage;

 @ManyToMany
 @JoinTable(name="PERSON_DEGREE")
 public List <Person> person;
 
 public void addPerson(Person p){
  if(person == null)person = new ArrayList <Person>();
  person.add(p);
 }
}

@Entity
class Person {

 @Id
 @GeneratedValue
 public Long id;
 
 @Column(name="FIRST_NAME")
 public String firstName;
 
 @Column(name="LAST_NAME")
 public String lastName;
 
 public String email;
 
 @ManyToMany(mappedBy="person",cascade=CascadeType.ALL)
 public List<Degree> degree;
 
  
 public Long getId() {
  return id;
 }
 public void setId(Long id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public List<Degree> getDegree() {
  return degree;
 }
 public void setDegree(List<Degree> degree) {
  this.degree = degree;
 }
 
 
}

This pom.xml is required to get all the Maven dependencies.

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>
  <groupId>MyHib</groupId>
  <artifactId>MyHib</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
   <dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.1.3</version>
   </dependency>
   <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.187</version>
   </dependency>
   <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.1</version>
   </dependency>
   <dependency>
    <groupId>org.hibernate.common</groupId>
    <artifactId>hibernate-commons-annotations</artifactId>
    <version>5.0.0.Final</version>
   </dependency>
   <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>5.0.0.CR1</version>
   </dependency>
  </dependencies>
</project>


Here are a list to conventional hibernate files which are not requires in the above example. But anyway I am keeping a reference copy here. Hibernate config files just for my reference

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection properties - Driver, URL, user, password -->
        <property name="hibernate.connection.driver_class">org.h2.Driver</property>
        <property name="hibernate.connection.url">jdbc:h2:tcp://localhost/~/myhibernatetest</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password"></property>
         
        <!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="show_sql">true
        <!-- Mapping with model class containing annotations -->
        <!-- <mapping class="com.journaldev.hibernate.model.Employee1"/> -->
        <!-- List of XML mapping files -->
               <mapping resource="Person.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

hibernate.properties

hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.username=sa
hibernate.connection.password=
hibernate.connection.url=jdbc:h2:tcp://localhost/~/myhibernatetest
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=update

Person.hbm.xml files

<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping package ="com.view">
   <class name="Person" table="PERSON12">
      <id name="id" type="int" column="id">
      <generator class="native">
      </id>
      <property name="firstName" column="first_name" type="string"/>
   </class>
</hibernate-mapping>