Monday, October 29, 2018

Hibernate CRUD using Oracle


CRUD Operations Using Hibernate 5 & Oracle

Image result for Hibernate image

 Hibernate is Java based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa. It provides reference implementation of Java Persistence API, that makes it a great choice as an ORM tool with benefits of loose coupling

Framework provides option to map plain old Java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.

A CRUD operation deals with creating, retrieving, updating, and deleting records from the table. In this tutorial we will see how it is done using Hibernate annotations. We are going to discuss 4 main functionalities:
  1. Create a record
  2. Read a record
  3. Update a Record
  4. Delete a Record 
Following script will create table,Sequence & Trigger in Oracle 11g


CREATE TABLE student
( id number(11) NOT NULL,
  first_name varchar2(50) default null,
  last_name varchar2(50) default null,
  email varchar2(50) default null,
 CONSTRAINT student_pk PRIMARY KEY (id)
);

//To create Id as auto increment,we need to sequence & trigger

CREATE SEQUENCE student_seq START WITH 1;

CREATE OR REPLACE TRIGGER student_bir
BEFORE INSERT ON student
FOR EACH ROW

BEGIN
  SELECT student_seq.NEXTVAL
  INTO   :new.id
  FROM   dual;
END;
/

select * from  student;


AnnotationModifierDescription
@Entity
Marks a class as a Hibernate Entity (Mapped class)
@TableNameMaps this class with a database table specified by name modifier. If the name is not supplied it maps the class with a table having the same name as the class.
@Id
Marks this class field as a primary key column.
@GeneratedValue
Instructs database to generate a value for this field automatically.
@ColumnNameMaps this field with table column specified by name and uses the field name if name modifier is absent.

Project Creation

create a Java based Maven project with Eclipse 

 

SessionFactory

  • Reads the hibernate config file
  • Creates Session objects
  • Heavy-weight object
  • Only create once in your app


Session

  • Wraps a JDBC connection
  • Main object used to save/retrieve object
  • short-lived object
  • Retrived from SessionFactory

Maven Dependencies


<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>Hibernate</groupId>
       <artifactId>HibernateDemo</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <packaging>jar</packaging>

       <name>HibernateDemo</name>
       <url>http://maven.apache.org</url>

       <properties>
             <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       </properties>

       <dependencies>
             <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
             <dependency>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-core</artifactId>
                    <version>5.3.7.Final</version>
             </dependency>

       </dependencies>
       <repositories>
             <repository>
                    <id>codelds</id>
                    <url>https://code.lds.org/nexus/content/groups/main-repo</url>
             </repository>
       </repositories>
</project>



Create a record 


Hibernate Configuration File

<?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>
       <!--  <property name="hbm2ddl.auto">update</property>  -->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">SYSTEM</property>
        <property name="connection.password">oracle</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
       
        <property name="connection.pool_size">1</property>
        <property name="show_sql">true</property>
        <property name="current_session_context_class">thread </property>
    <!-- <mapping resource="EMP.hbm.xml"/> -->
    </session-factory>

</hibernate-configuration> 
  

ID Generation Strategies

GenerationType.AUTO           = Pick an appropriate strategy for the particular database
GenerationType.IDENTITY   = Assign primary keys using a database identity column
GenerationType.SEQUENCE = Assign primary keys using a database sequence
GenerationType.TABLE         = Assign primary keys using an underlying
                                                  database table to ensure uniqueness

 



Implementation of Model Class

package com.hibernate.entity;

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

@Entity
@Table(name = "student")
public class Student {

       @Id
       @Column(name = "id")
       private int id;

       @Column(name = "first_name")
       private String firstname;

       @Column(name = "last_name")
       private String lastname;

       @Column(name = "email")
       private String email;

       public Student(String firstname, String lastname, String email) {
             super();
             this.firstname = firstname;
             this.lastname = lastname;
             this.email = email;
       }

       public int getId() {
             return id;
       }

       public void setId(int 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;
       }

       @Override
       public String toString() {
             return "Student [id=" + id + ", firstname=" + firstname + ", lastname=" + lastname + ", email=" + email + "]";
       }

}

 


Implementation of DAO Class

package Hibernate.HibernateDemo;

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

import com.hibernate.entity.Student;

public class CreateStudentDemo {

       public static void main(String[] args) {

             // create session factory
             SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();

             // create session
             Session session = factory.getCurrentSession();

             // create a student object
             Student tempstu = new Student("Devyan", "Thakur", "devyan@newton.com");

             /*
              * // save student object session.save(tempstu);
              *
              *
              * //commit transaction session.getTransaction().commit();
              *
              * System.out.println("Done!");
              */

             // creating transaction object
             Transaction t = session.beginTransaction();

             // persisting the object
             session.persist(tempstu);

             // commit transaction
             t.commit();

             session.close();
             factory.close();

             System.out.println("successfully saved");

       }

}

 

 Output:

INFO: HHH000182: No default (no-argument) constructor for class: com.hibernate.entity.Student (class must be instantiated by Interceptor)
Hibernate: insert into student (email, first_name, last_name, id) values (?, ?, ?, ?)
successfully saved


  Read a record

 

package Hibernate.HibernateDemo;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.hibernate.entity.Student;

public class ReadStudentdemo {

     static Session session;
     static SessionFactory sessionFactoryObj;

     public static List<Student> displayRecords() {
           List studentsList = new ArrayList();
           // create session factory
           SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();

           // create session
           session = factory.getCurrentSession();

           // Getting Transaction Object From Session Object
           session.beginTransaction();

           studentsList = session.createQuery("FROM Student").list();
           session.close();
           factory.close();

           System.out.println("successfully Retrived");

           return studentsList;

     }

     public static void main(String[] args) {

           List<Student> viewstudent = ReadStudentdemo.displayRecords();

           for (Student s : viewstudent) {
                System.out.println("Student id:" + s.getId() + "Student Name:" + s.getFirstname());
           }

     }

}


Output:
INFO: HHH10001008: Cleaning up connection pool [jdbc:oracle:thin:@localhost:1521:xe]
successfully Retrived
Student id:1Student Name:Paul
Student id:2Student Name:Devyan
Student id:7Student Name:Rahul



Update a Record

package Hibernate.HibernateDemo;

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


import com.hibernate.entity.Student;

public class UpdateStudentRecord {
     static Session session;
     static SessionFactory sessionFactoryObj;

     public static void updateStudent(int student_id) {
           // create session factory
           SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();

           // create session
           session = factory.getCurrentSession();

           // Getting Transaction Object From Session Object
           session.beginTransaction();

           //Creating Transaction Entity
           Student stu=session.get(Student.class, student_id);
           stu.setFirstname("Harendera");
          
           //committing the transaction to the database
           session.getTransaction().commit();

           session.close();
           factory.close();
     }

     public static void main(String[] args) {
           int updateId=1;
           UpdateStudentRecord.updateStudent(updateId);

     }

}

 

 Output:


INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_name3_0_0_, student0_.last_name as last_name4_0_0_ from student student0_ where student0_.id=?
Hibernate: update student set email=?, first_name=?, last_name=? where id=?
Oct 30, 2018 9:24:49 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:oracle:thin:@localhost:1521:xe]

Delete a Record 

package Hibernate.HibernateDemo;

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

import com.hibernate.entity.Student;


public class DeleteStudentRecord {
     static Session session;
     static SessionFactory sessionFactoryObj;
    
     public static void deleteStudent(int student_id) {
           // create session factory
           SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();

           // create session
           session = factory.getCurrentSession();

           // Getting Transaction Object From Session Object
           session.beginTransaction();

           // Creating Transaction Entity
           Student stu = session.get(Student.class, student_id);
           session.delete(stu);

           // committing the transaction to the database
           session.getTransaction().commit();

           session.close();
           factory.close();

     }
    
     public static void main(String[] args) {
           int id=1;
           DeleteStudentRecord.deleteStudent(id);
     }

}

Output:


INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_name3_0_0_, student0_.last_name as last_name4_0_0_ from student student0_ where student0_.id=?
Hibernate: delete from student where id=?
Oct 30, 2018 10:41:52 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:oracle:thin:@localhost:1521:xe]



If I can be of assistance, please do not hesitate to contact me:)

Tuesday, October 9, 2018

Core Java Interview Question

Core Java Interview Question


Q1. Explain public static void main(String args[]).

  • public : Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
  • static : It is a keyword in java which identifies it is class based i.e it can be accessed without creating the instance of a Class.
  • void : It is the return type of the method. Void defines the method which will not return any value.
  • main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.
  • String args[] : It is the parameter passed to the main method
Q2. Differentiate between JDK, JRE and JVM.
  • JVM stands for Java Virtual Machine which provides runtime environment for Java Byte Codes to be executed.
  • JRE (Java Runtime Environment) that includes sets of files required by JVM during runtime.
  • JDK (Java Development Kit) consists of JRE along with the development tools required to write and execute a program.
Q3  What is JVM and is it platform independent?

 JVM is responsible for converting byte code into machine readable code. JVM is not platform independent, thats why you have different JVM for different operating systems. We can customize JVM with Java Options, such as allocating minimum and maximum memory to JVM. It’s called virtual because it provides an interface that doesn’t depend on the underlying OS. 

Q4  Name some OOPS Concepts in Java? 

Java is based on Object Oriented Programming Concepts, following are some of the OOPS concepts implemented in java programming.
  • Abstraction
  • Encapsulation
  • Polymorphism
  • Inheritance
  • Association
  • Aggregation
  • Composition
Q5 What is String in Java? String is a data type? 
 String is a Class in java and defined in java.lang package. It’s not a primitive data type like int and long. String class represents character Strings. String is used in almost all the Java applications and there are some interesting facts we should know about String. String in immutable and final in Java and JVM uses String Pool to store all the String objects.
Some other interesting things about String is the way we can instantiate a String object using double quotes and overloading of “+” operator for concatenation.

Q6 What are different ways to create String Object?
We can create String object using new operator like any normal java class or we can use double quotes to create a String object. There are several constructors available in String class to get String from char array, byte array, StringBuffer and StringBuilder.

String str = new String("abc");
String str1 = "abc";



When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.




 Q7 Why Char array is preferred over String for storing password?


String is immutable in java and stored in String pool. Once it’s created it stays in the pool until unless garbage collected, so even though we are done with password it’s available in memory for longer duration and there is no way to avoid it. It’s a security risk because anyone having access to memory dump can find the password as clear text.
If we use char array to store password, we can set it to blank once we are done with it. So we can control for how long it’s available in memory that avoids the security threat with String.

Q8 Is String thread-safe in Java? Why?

Yes, String is thread-safe because it's Immutable. All Immutable objects are thread-safe because once they are created, they can't be modified, hence no issue with respect to multiple threads accessing them.

Q9 Can we use String in switch case in Java?

Yes, after JDK 7 release, you can use the String in the switch case in Java. Earlier it wasn't possible but now it's possible.

Q10 When you execute String str = new String("abcd")? how many String objects are created? 
 
This is another tricky Java interview question as many Java developer will answer just one but that's not true. There are two String objects are created here, the first String object is created by String literal "abcd" and the second one is created by new String(). 
 
Q11 Difference between str1 == str2 and str1.equals(str2)?
 
The key difference is that first one is using == operator which does reference based comparison while the second one is using equals() method which does a content-based comparison. Since String class overrides equals() to perform character-based comparison first will return true only if both str1 and str2 points to the same object but the second one will return true if str1 and str2 have same content even if they are a different object