Friday, April 7, 2017

Hibernate Interview Questions

1. What is the difference between openSession and getCurrentSession?

         openSession will open a new session and getCurrentSessiona will use an existing one which is in available in context.

2. What is the difference between get/load and createCriteria?   

         load will not hit database(because of fake object) and it will throw object not found exception if data not available.

         get will hit database and it will throw null if data is not available.

       createCriteria is a method of session interface and it will create a criteria object of persistence object of you requested class.

e.g : Criteria cr  = session.createCriteria(Employee.class)

3. Why we need to use hibernate ?

        1. HQL - You do not want to write query and it will be suitable to all database when we change in future.

        2. OOPS concept -   You will get oops concept since you are using table as entity in hibernate. So inheritance, encapsulation etc., all you will get.

         3. Caching Mechanism - First level cache and second level cache possible.

         4. Lazy loading - You can set when child has to be loaded while parent loading.

4. How many ways configure hibernate.config.xml file ?

        1. By using xml file (hibernate.config.xml)
        2.By using setProperty() method of configuration
        3.By using properties file

5. How you do hibernate pagination ?

    You can set the result per page wise. 

        Query query = session.createQuery("From Person");
        query.setFirstResult(0);
        query.setMaxResults(10);

ScrollableResults also we can use for pagination.

For more please check this stackoverflow link.

6. What is hibernate First level cache ?

1. First level cache is associated with session object.
2. Default it will enable and you can not disable it.
3. When we query for first time, it will get from DB and second time if you excecute the same query it will get from cache.

7. What is second level cache ?

Second level cache is associated with session Factory object. Actually it will reduce our database traffic. We have lot of option to enable second level cache in hibernate. But mostly all will use EHCache, since its fast and lightweight. It will support read only , read/write operation 

8. How to enable second level cache in hibernate ?

You can enable it through hibernate.cfg.xml. It look likes below.


<hibernate-configuration>
      <session-factory>
          <property  name=hibernate.cache.provider_class">
                     org.hibernate.cache.EHCacheProvider
          </property>
          <property name="net.sf.ehcache.configurationResourceName">ehcache.xml</property>
      </session-factory>
</hibernate-configuration>

9. What is evict method in hibernate ?

evict method will be useful, to remove session from first level cache.

Person t = (Person) session.load(Person.class, new Integer(1));
   
session.evict(t);

It will remove only t cached from particular session . But session.clear() remove all cached.

10. What is hibernate versioning ?

If you want to find how many times your Object was modified ,  then you should apply versioning in hibernate. Whenever you modified the object it will increment one number automatically.

11. How do you call aggregate functions in hibernate?

String hql = "select count(name) from Product";

Query query = session.createQuery(hql);
List listResult = query.list();

You can use all sum(), avg(), min(), max() etc.,

12. How to disable Hibernate first level cache ?

We can not disable hibernate first level cache and it will be enabled by default.

13. What are the interfaces available in hibernate ?

Session Interface

Session Factory Interface

Configuration Interface

Transaction Interface

Query and Criteria Interface

Wednesday, February 22, 2017

How to send Cookie in Request header

I did one file upload with Form data by using fetch. I tried to send Cookie and content type as multipart/form-data. But its not taking these two attributes in header. Finally I solved it through ajax as well as fetch.

1. If you want to send cookie you must add credentials like below.

fetch('/users', {
  credentials: 'same-origin'
})

Suppose if its a cross origin request, credentials should be like below.

fetch('https://xxxxxxxx.com:4321/users', {
  credentials: 'include'
})

and Finally you dont want to add content type as multipart/form-data. Your request will add this automatically.

2. Suppose if you are using ajax request,  your code should be like below.

$.ajax({
       url : 'xxxxxxxxxxxxxxxxxxxxx',
       type : 'POST',
       data : formData,     // form data appended values
       processData: false,  // tell jQuery not to process the data
       contentType: false,  // tell jQuery not to set contentType -  It will set multipart by request automatically
       success : function(data) {
           console.log(data);
           alert(data);
       }
});


Check Internet explorer and open Network tab (F12) request header. Now all the header attributes were added perfectly.

Chrome may not show cookies in network tab, check Application tab, there cookies will be stored.


Thursday, February 16, 2017

Chrome throwing 302 Error and Working fine in Internet Explorer

Ago some days back, I got an issue in chrome browser for one service which is returning a status code error 302. I checked the same in REST Client and this also returning error code 302.

But the same service working fine with IE browser. Initially I tried lot of tried with setting header filed cache etc., But nothing worked.

What are the possibilities for 302 status code error and How to handle it ?

The below are some of the possibilities only. But mostly it will be involved within this.

1. There is redirect issue. possibility, you might have used sendRedirect method instead of forward in java.

2. If you have load balancing then definitely there redirect will happen. The way of handling redirect may produce 302 issue.

3. Chrome throwing 302 exception since it have additional security than IE.

4. Check REST client (Chrome web store) older version, it wont produce this 302 error. But latest Rest client will produce 302 error.

5. Firewall also may produce 302 error, but in this case IE also wont work.

6. If you are using client side request through fetch, you add credential= same-origin. It will solve this issue. It will cookies for your request.

7. Finally , You have an option to play around with the below important attributes.
 Access-Control-Allow-Origin : http://www.xxxxxxx.com
Access-Control-Allow-Credentials : true

Saturday, August 6, 2016

React JS - DatePicker

Date Picker

You should install and import the below for date picker.

npm install react-datepicker --save


App.jsx


import React from 'react';
  import DatePicker from 'react-datepicker';
  import moment from 'moment';

  class App extends React.Component {

    constructor(props) {
      super(props);
      this.state = {
        startDate : moment()
      };

      this.handleChange = this.handleChange.bind(this);
      
    }

    handleChange (date) {
      this.setState({
        startDate : date
      });
    }

     render() {
        return (
           <div>
              Hello World!!!
  <br />
  <br />
  <br />
  <br />
  <br />
  <br />

  <br />
          <DatePicker
          selected={this.state.startDate}
          onChange={this.handleChange} />;
           </div>
        );
     }
  }

  export default App;

index.html
 datepicker css added here.

<!DOCTYPE html>
<html lang = "en">

   <head>
      <meta charset = "UTF-8">
      <title>React App</title>
   </head>

<link rel="stylesheet" type="text/css" href="node_modules/react-datepicker/dist/react-datepicker.css"/>

   <body>
      <div id = "app"></div>
      <script src = "index.js"></script>
   </body>

</html>

main.js

Rendered the App from here,

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';


ReactDOM.render(<App />, document.getElementById('app'));

Output:



Friday, July 22, 2016

Pass parameters from one JSP to another JSP

To do this, you need to add jsp:include and its jsp:param properties .

First.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Pass Parameters from one JSP to another JSP Page</title>
</head>

<body>
      This is your First JSP page.

    <jsp:include page="Second.jsp">
        <jsp:param name="param1" value="Firstvalue"/>
        <jsp:param name="param2" value="Secondvalue"/>
    </jsp:include>
</body>
</html>

Second.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Pass Parameters Example</title>
</head>

<body>
    This is your second JSP page.
    param1: <%= request.getParameter("param1") %>
    param2: <%= request.getParameter("param2") %>
</body>
</html>

Explanation :

1.You have to include Sceond.jsp in the First.jsp page.

2. Use jsp:include property, jsp:param to pass parameter to the Second.jsp which was already included with the help of jsp:include.

3.Retrieve the passed values from First.jsp through getParameter method.

SubQuery for Beginners

Sub query  - Embedding a SQL statement within another SQL statement. It can be used with sql comparison operators like =,<.>,<=,>= etc.,

Additionally, we can write with LIKE IN, NOT IN, ANY and IN operators. Now you may have question when we have to use LIKE IN etc., and comparison operators while writing query.

Things to remember:

1. Sub query may return one row or more than one row.
2. If it will return more than one row then you should use IN operator.
3.It must be enclosed with parenthesis.
4. You can not use ORDER BY in sub query. Instead of that, you can use GROUP BY.


Sub Query Format:

SELECT "column_name1"
FROM "table_name1"
WHERE "column_name2" [Comparison Operator] or [LIKE IN, ANY etc.,]
(SELECT "column_name3"
FROM "table_name2"
WHERE "condition");

Highlighted in blue color is inner query and highlighted in red color is called outer query. Let see the example one by one, so that we able to understand more clearly.

Example I: Sub Query with IN operator

ID     NAME  AGE PLACE     SALARY  

  1     Rajesh     35    Chennai       2000.00
  2     Velava     25    Mumbai       1500.00
  3     kajol        23    Hyderabad   2000.00
  4     Mukesh   24    Madurai       10000.00

Sub Query:

SELECT * 
FROM CUSTOMERS 
WHERE ID IN (SELECT ID 
             FROM CUSTOMERS 
             WHERE SALARY > 1800) ;

Output:

 ID   NAME      AGE  PLACE      SALARY  

  1     Rajesh        35     Chennai          2000.00 
  3     kajol           23     Hyderabad      2000.00 
  4     Mukesh      24     Madurai        10000.00 


Note: Above query uses IN operator, due to inner query will return more than one rows.

Sub Query with Comparison Operator


        student                                     marks
Student Id         Name                                 Student Id                 Marks      
     1                Kalpana                                       1                               91
     2                Peter                                             2                               89
     3                Rajini                                           3                               97
     4                Ajith                                             4                               96 
     5                Vijay                                             5                               95

Ok, Now the question is , How to identify all students who get high marks than one of the student who`s id is 5. Here, you don't know marks of student id 95.

So we can split this question as two,
 1. What s the mark of student Id 95 ? (95Marks)
 2. Who are all getting high marks than studetn Id 95 marks? (>95 Marks)

For 1st question, query is below,

Select * from marks
where student_id = '5'

Output:

Student Id     Marks
       5                  95

Now second question, query is below,

Select a1.student_id,a1.name,m1.marks 
from student s1, marks m1
where s1.student_id = m1.student_id
AND m1.marks > 95

Output:

studentId     name       marks
3                   Rajini         97
4                   Ajith           96

Now combine these two query, 

SELECT a.studentid, a.name, b.marks  
FROM student a, marks b  
WHERE a.studentid = b.studentid AND b.marks >  
(SELECT marks  
FROM marks  

WHERE studentid =  '95');  

Output:

studentId     name       marks
3                   Rajini         97
4                   Ajith           96

Thursday, July 21, 2016

JAVA Generics

Java Generics is similar to C++ Templates. You can write a code with Generics for methods, classes and interfaces. Let see one by one. 

Generics Class
To create Generics class we have to use < >. The most commonly used type parameter names are:

E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types

To know more please visit here. Ok,

Example code:

// Use < > to specify Parameter type
class JavaHit<T>
{
 // An object of type T is declared
 T obj;
 JavaHit(T obj) { this.obj = obj; } // constructor part
 public T getObject() { return this.obj; }
}

//To test above I used this class
class Main
{
 public static void main (String[] args)
 {
  // For Integer type
  JavaHit <Integer> integerObj = new JavaHit<Integer>(37);
  System.out.println(integerObj.getObject());

  // For String type
  JavaHit <String> stringObj = new JavaHit<String>("TestForString");
  System.out.println(stringObj.getObject());
 }
}

Output:
37
TestForString

From the above code , you able to understand you can pass any wrapper like Integer , Float etc.,

Multiple Type Parameters

// Use < > to specify Parameter type
class JavaHit<T, U>
{
 T obj1; // An object of type T
 U obj2; // An object of type U

 // constructor
 JavaHit(T obj1, U obj2)
 {
  this.obj1 = obj1;
  this.obj2 = obj2;
 }

 // To print objects of T and U
 public void print()
 {
  System.out.println(obj1);
  System.out.println(obj2);
 }
}

// To test above I used this class
class Main
{
 public static void main (String[] args)
 {
  JavaHit <String, Integer> obj =
   new JavaHit<String, Integer>("TestForString", 37);

  obj.print();
 }
}

Output
TestForString
37

Generics Functions:
In nutshell, you can pass here, different types of arguments. Let see code below.

// Generic functions

class Test
{
 
 static <T> void genericParameterDisplay (T typeofelement)
 {
  System.out.println(typeofelement.getClass().getName() +
      " = " + typeofelement);
 }
 
 public static void main(String[] args)
 {
  // Calling generic method for Integer
  genericParameterDisplay(37);

  // Calling generic method for String
  genericParameterDisplay("TestForString");

  // Calling generic method for double
  genericParameterDisplay(10.02);
 }
}

Output:
37
TestForString
10.02

Generics Advantages :

1. Code Reuse.
2. Type safety
3. No need Type casting