Wednesday, October 11, 2017

Hibernate Annotations Approach



hibernate.cfg.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection properties - Driver, URL, user, password -->
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@172.20.1.47:1521:XE</property>
        <property name="hibernate.connection.username">DLAUDIT</property>
        <property name="hibernate.connection.password">DLAUDIT</property>
        <!-- Connection Pool Size -->
        <property name="hibernate.connection.pool_size">10</property>
       
        <!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
        <property name="hibernate.current_session_context_class">thread</property>
       
        <!-- Outputs the SQL queries, should be disabled in Production -->
        <property name="hibernate.show_sql">true</property>
        <property name="format_sql">true</property>
       
        <!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
            Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>

        <!-- mapping file, we can use Bean annotations too -->
        <mapping class="com.hiberante.api.annotations.Account" />
    </session-factory>

</hibernate-configuration>


Account.java


package com.hiberante.api.annotations;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="ACCOUNT")
public class Account {

@Id
@Column(name="ID")
private Integer id;

@Column(name = "GUI")
private String gui;

@Column(name="FIRST_NAME")
private String firstName;

@Column(name="LAST_NAME")
private String lastName;

@Column(name="AGE")
private Integer age;

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGui() {
return gui;
}
public void setGui(String gui) {
this.gui = gui;
}
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}

}

Hibernate Declarative Approach

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection properties - Driver, URL, user, password -->
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@172.20.1.47:1521:XE</property>
        <property name="hibernate.connection.username">DLAUDIT</property>
        <property name="hibernate.connection.password">DLAUDIT</property>
        <!-- Connection Pool Size -->
        <property name="hibernate.connection.pool_size">10</property>
       
        <!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
        <property name="hibernate.current_session_context_class">thread</property>
       
        <!-- Outputs the SQL queries, should be disabled in Production -->
        <property name="hibernate.show_sql">true</property>
        <property name="format_sql">true</property>
       
        <!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
            Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>

        <!-- mapping file, we can use Bean annotations too -->
        <mapping resource="resorces/Account.hbm.xml" />
    </session-factory>
</hibernate-configuration>


Account.hbm.xml

<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
 <hibernate-mapping>
  <class name="com.hiberante.api.declartive.Account" table = "ACCOUNT">
  <id name="id" column="ID" type="java.lang.Integer"></id>
  <property name="gui" column="GUI" type="java.lang.String"/>
  <property name="firstName" column="FIRST_NAME" type="java.lang.String"/>
  <property name="lastName" column="LAST_NAME" type="java.lang.String"/>
  <property name="age" column="AGE" type="java.lang.Integer"/>
  </class>

 </hibernate-mapping>


Hibernate Programmatic Approch

package resorces;

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.hiberante.api.programetic.Account;

public class HiberanateConfig {

//Property based configuration
    private static SessionFactory sessionJavaConfigFactory;

private static SessionFactory buildSessionJavaConfigFactory() {
       try {
       Configuration configuration = new Configuration();
       
       //Create Properties, can be read from property files too
       Properties props = new Properties();
       props.put("hibernate.connection.driver_class", "oracle.jdbc.driver.OracleDriver");
       props.put("hibernate.connection.url", "jdbc:oracle:thin:@localhost:1521:XE");
       props.put("hibernate.connection.username", "DLAUDIT");
       props.put("hibernate.connection.password", "DLAUDIT");
       props.put("hibernate.current_session_context_class", "thread");
       props.put("hibernate.show_sql", true);
       props.put("format_sql", true);
       props.put("hibernate.dialect", "org.hibernate.dialect.OracleDialect");
     
       configuration.setProperties(props);
       
       //we can set mapping file or class with annotation
       //addClass(Employee1.class) will look for resource
       // com/journaldev/hibernate/model/Employee1.hbm.xml (not good)
       configuration.addAnnotatedClass(Account.class);
     
       //configuration.addClass(Account.class);
       //configuration.addResource("resorces/Account.hbm.xml");
     
      // ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
       System.out.println("Hibernate Java Config serviceRegistry created");
       
       SessionFactory sessionFactory = configuration.buildSessionFactory();
       
       return sessionFactory;
       }
       catch (Throwable ex) {
           System.err.println("Initial SessionFactory creation failed." + ex);
           throw new ExceptionInInitializerError(ex);
       }
   }
   
   public static SessionFactory getSessionJavaConfigFactory() {
       if(sessionJavaConfigFactory == null) sessionJavaConfigFactory = buildSessionJavaConfigFactory();
       return sessionJavaConfigFactory;
   }

}

Hibernate and Spring With Domain Scan Package

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- It register the beans in context and scan the annotations inside beans and activate them -->
    <context:component-scan base-package="com.hibernate.spring" />
    <context:component-scan base-package="com.hibernate.spring.controller" />
   
    <!-- This allow for dispatching requests to Controllers -->
    <mvc:annotation-driven />
 
     <!-- This helps in mapping the logical view names to directly view files under a certain pre-configured directory -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
   
    <!-- This produces a container-managed EntityManagerFactory;
         rather than application-managed EntityManagerFactory as in case of LocalEntityManagerFactoryBean-->
    <bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <!-- This makes /META-INF/persistence.xml is no longer necessary -->
      <property name="packagesToScan" value="com.hibernate.spring.domain" />
      <!-- JpaVendorAdapter implementation for Hibernate EntityManager.
           Exposes Hibernate's persistence provider and EntityManager extension interface -->
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      </property>
      <property name="jpaProperties">
         <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
         </props>
      </property>
   </bean>

   <!-- Simple implementation of the standard JDBC DataSource interface,
        configuring the plain old JDBC DriverManager via bean properties -->
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
      <property name="url" value="jdbc:oracle:thin:@172.20.1.47:1521:XE" />
      <property name="username" value="DLAUDIT" />
      <property name="password" value="DLAUDIT" />
   </bean>
   
    <!-- This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
        JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
      <property name="entityManagerFactory" ref="entityManagerFactoryBean" />
   </bean>
 
   <!-- responsible for registering the necessary Spring components that power annotation-driven transaction management;
        such as when @Transactional methods are invoked -->
   <tx:annotation-driven />
 
</beans>