Thursday, November 1, 2018

Java Application accessing Oracle Database by using Hibernate


1. Download Hibernate from http://www.hibernate.org/downloads or mvnrepository.com

2. Configure Hibernate by hibernate.cfg.xml or hibernate.properties
   hibernate.cfg.xml sample for Oracle
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" 
"http://www.jboss.org/dtd/hibernate/hibernate-configuration-3.0.dtd">
 <!-- // NOTE: if accessing .dtd has a problem, download .dtd to local and refer it from CLASSPATH like below -->
 <!-- <!DOCTYPE hibernate-configuration SYSTEM "classpath://org/hibernate/hibernate-configuration-3.0.dtd"> -->
<hibernate-configuration>
<session-factory> <!-- Oracle -->
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 
<property name="hibernate.connection.url">jdbc:oracle:thin:@server:port:SID</property> 
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> 
<property name="hibernate.default_schema">schema_name</property> 
<property name="hibernate.connection.username">user_name</property> 
<property name="hibernate.connection.password">user_password</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property> 
<property name="hibernate.current_session_context_class">thread</property> 
<property name="hibernate.jdbc.batch_size">30</property>
</session-factory>
</hibernate-configuration>

   hibernate.properties sample for PostgreSQL
    hibernate.connection.driver_class = org.postgresql.Driver
    hibernate.connection.url = jdbc:postgresql://localhost:5432/mydatabase
    hibernate.connection.username = myuser
    hibernate.connection.password = secret
    hibernate.c3p0.min_size=5
    hibernate.c3p0.max_size=20
    hibernate.c3p0.timeout=1800
    hibernate.c3p0.max_statements=50
    hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

3. Create a Hibernate Java project in Maven with required dependencies, including:
    database client library files. e.g. ojdbc*.jar for Oracle, postgresql*.jar for PostgreSQL
hibernate-core
hibernate-entitymanager for Hibernate JPA implementation
hibernate-ehcache for using Hibernate cache mechenism
    e.g. in pom.xml
    <properties>
        <hibernate.version>4.3.5.Final</hibernate.version> <!-- bundled with Wildfly 8.1.0 -->
    </properties>
    <dependencies>
      <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc</artifactId>
        <version>5.0</version>
      </dependency>
      <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
      </dependency>
      <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate.version}</version>
      </dependency>
      <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>${hibernate.version}</version>
      </dependency>
  </dependencies>

4. Create an Entity object mapped with the data structure (e.g. a table or a view) in DB
    For an example of Student Table in DB, the entity class defined as Student in below:
@Entity
 @Table(name="Student_Table")
public class Student {
 @Id
@Column(name="Student_Id")
private String studentId;

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

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

public String getStudentId(){ return studentId; }
public void setStudentId(String id) { this.studentId = id; }

public String getFirstName(){ return firstName; }
public void setFirstName(String name) { this.firstName = name; }

public String getLastName(){ return lastName; }
public void setLastName(String name) { this.lastName = name; }
}

5. Map the entity class in hibernate.cfg.xml by adding the following in <session-factory />
    <mapping class="org.freecode.demo.entity.Student" /> <!-- // full class name with package -->

6. Access DB through Hibernate
    public static void main(String[] args) {
String configFile = "hibernate.cfg.xml"; // load Hibernate configuration
Configuration cfg = new Configuration();
cfg.configure(configFile);
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
ssrb.applySettings(cfg.getProperties());
ServiceRegistry sr = ssrb.build();
SessionFactory sf = cfg.buildSessionFactory(sr); // initialize a session factory
Session s = sf.openSession();
// Session s = sf.getCurrentSession(); // initialize a DB session
// Transaction tx = null;
try {
// tx = s.beginTransaction();
List<ProjectCause> causes = s.createQuery("FROM Student").list(); // create a Hibernate Query to get all student objects from the DB session
// tx.commit();
if (causes != null) {
for (ProjectCause c : causes) {
System.out.println("Student: " + c.getStudentId() + " - " c.getFirstName() + " " + c.getLastName());
}
}
}
catch (HibernateException he) {
he.printStackTrace();
// tx.rollback();
}
finally {
if (s.isOpen()) {
            s.close();
}
}
}

7. Use Hibernate JPA Implementation by creating JPA descriptor - persistence.xml
    <?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
  <persistence-unit name="Hibernate_JPA_Unit" transaction-type="RESOURCE_LOCAL"> <!-- non EJB type -->
<description>Persistence Unit for JPA Implementation</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
  <class>org.freecode.demo.entity.Student</class> <!-- need to map the class for WAR, EAR -->
<properties>
  <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
  <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@server:port:SID" />
  <property name="javax.persistence.jdbc.user" value="db user" />
  <property name="javax.persistence.jdbc.password" value="db password" />
  <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
  
  <!-- for caching, require hibernate-ehcache.jar -->
  <property name="hibernate.cache.use_second_level_cache" value="true"/>
  <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"></property>
  <property name="hibernate.cache.use_query_cache" value="true"></property>

  <property name="hibernate.jdbc.batch_size" value="30"/>
  <property name="hibernate.show_sql" value="true" />
  <!-- logger: org.hibernate.SQL, org.hibernate.engine.query, org.hibernate.type, org.hibernate.jdbc -->
  <property name="hibernate.format_sql" value="true"/>
  <property name="hibernate.transaction.flush_before_completion" value="true" />
</properties>
  </persistence-unit>
</persistence>

8. Access DB through Hibernate JPA
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("Hibernate_JPA_Unit"); // unit name is defined in persistence.xml
EntityManager em = emf.createEntityManager();

try {
Query qry = em.createQuery("SELECT c FROM Student c");
List<ProjectCause> students = qry.getResultList();
if (causes != null) {
for (Student std : students) {
System.out.println(std.getStudentId() + " - " + std.getFirstName() + " " + c.getLastName());
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
if (em.isOpen()) {
em.close();
}
em = null;
if (emf.isOpen()) {
emf.close();
}
emf = null;
}