Saturday, November 7, 2015

Hibernate openSession VS openStatelessSession


We mostly use hibernate ‘s sessionFactory.openSession() method which keeps track of all events of hibernate along with managing first level cache, and also interacts with second level cache of hibernate. It also performs operations cascade on associated entities.

In openSession() method dirty checking is done automatically,  means when we fetch data from DB and do some changes it automatically check updated record and update the database accordingly.Many of things are not possible to do with org.hibernate.Session interface.

However, Hibernate gives alternative interface when you want to work with your database like executing simple JDBC Statements. This interface is org.hibernate.StatelessSession.
Hibernate sessionFactory.openStatelessSession() method works line simple JDBC. It neither listens any of hibernate events nor does any things by own.

A StatelessSession does not maintain first level cache or never interacts with second level cache, nor does it automatically do dirty checking, nor do any operation cascade on related associations. In StatelessSession you have to explicitly trigger a query or event for each update or modification on an Object.  

 For more details click here

Friday, October 30, 2015

TreeSet Case Insensitive Check




As we know that TreeSet by default store the unique value it doesn’t check case of the value that is being added.
For example if we have a set instance set1 of string type and add value like as follows.
set1.add(“a”);
set1.add(“A”);
Now if we check the size of set1 , it will give size 2 because ASCII value of  ‘a’ & ‘A’ is different, as well as equality check of both value will return false so set1 will add both the value.
It is not amazing it is the default nature of set.
Suppose we have a scenario that set should ignore case sensitive value  and when user add two value like ‘a’ & ‘A’ it should only store one value.
  See the below mentioned example which solve the case sensitive problem.
Set<String> set1=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
            set1.add("a");
            set1.add("A");
           
            System.out.println(set1.size());
            System.out.println(set1);

Output :
1
[a]

Tuesday, October 27, 2015

Reverse of a string in optimized way

Most of the time we came a cross to reverse of a string in interview and interviewer always say it should be optimized.
There are so many ways to reverse a string one of them is mentioned below.

public class StringReverse {
    
    public static void main(String arg[])
    {
        String string="I AM MIKE MORTAN";
        char[] tempCharArray=string.toCharArray();
        int start,end=0;
        end=tempCharArray.length-1;
        for(start=0;start<end;start++,end--)
        {
            char temp=tempCharArray[start];
            tempCharArray[start]=tempCharArray[end];
            tempCharArray[end]=temp;
        }
        
        System.out.println(new String(tempCharArray));
    }

}


In this way we will reverse the string in half of the iteration of a given string, rather than traversing complete string from start to end.

Tuesday, September 8, 2015

Difference between SLF4J and Log4J



SLF4J is an abstract layer designed for logging framework, which makes logging platform independent from any specific logging implementation like Java util logging or Log4j.
Log4J is implementation of logging framework that is widely used in the industry but some of the most important feature of SLF4J convinced to use SLF4J like parameterized logging rather than concatenation of string in log4j and less memory consumption and high performance. In logging there is always a memory concerns but in SLF4J reduce the memory consumption and hence increase the performance of the application.
Apart from the above feature the most important thing is that it gives us freedom to apply any logging framework whenever required without changing of code to the running application because it is an abstract layer to provide logging implementations.

See below how to use SLF4J.
Public class Test {

private final Logger slf4j = LoggerFactory.getLogger(Test.class);
    public void Test(String name) {
        slf4j.info("Hi, {}", name);//Parameterized logging rather than                                                                                                                          
        slf4j.info("Hello SLF4J.");// concatenation of log4j.
    }

}


For more details please click here.
 

Saturday, April 4, 2015

Hibernate second level cache example



Hibernate Second Level Cache

Hibernate second level cache is used to boost the application formance by minimizing database hit.
Hibernate automatically manage first level cache using session. Now here I will use second level  chache using EHCache.

To configure second level hibernate EHCache follow the following steps:-
1.   Hibernate.cfg.xml configuration for enabling cache
<hibernate-configuration>

    <session-factory>
        <!-- <property name="hbm2ddl.auto">update</property> -->
       <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="connection.url">jdbc:postgresql://localhost:5432/test</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">admin</property>
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="show_sql">true</property>
       <property name="cache.provider_class">org.hibernate.cache.EHCacheProvider</property> 
      <property name="hibernate.cache.use_second_level_cache">true</property> 
      <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
         <property name="hibernate.cache.use_second_level_cache">true</property>
         <property name="hibernate.cache.use_query_cache">true</property>
         <property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>

     
     
        <mapping class="com.pojo.User"/>
        <mapping class="com.pojo.Employee"/>
   
    </session-factory>

</hibernate-configuration>
2.   Mapping POJO of User

@javax.persistence.Entity(name="userdetails")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class User implements Serializable {
         
          private static final long serialVersionUID = 1L;
          private Integer userId;
          private String name;
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
          public Integer getUserId() {
                   return userId;
          }
          public void setUserId(Integer userId) {
                   this.userId = userId;
          }
          @Column(name="name")
          public String getName() {
                   return name;
          }
          public void setName(String name) {
                   this.name = name;
          }
          }

3.   Configure the User pojo in ehcache.xml file

<?xml version="1.0" encoding="UTF-8"?>

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
    monitoring="autodetect" dynamicConfig="true">
<defaultCache  
maxElementsInMemory="100"  
eternal="false"  
timeToIdleSeconds="120"  
timeToLiveSeconds="200" /> 
 
  <cache name="User"  maxElementsInMemory="100" eternal="false" timeToIdleSeconds="500" timeToLiveSeconds="1000"
 
  />
 
</ehcache>

4.   UserDAO to fetch all user list.
In followng ways we can apply cache in query as well as in Criteria.

public List getUsers()
            {
            List userlist=null;
            Session session=HibernateSessionFactory.getSession();
           

            /*
Set cacheable true when we are using HQL.
Query query=session.createQuery("from com.pojo.User");
            query.setCacheable(true);
            userlist=query.list();*/

//When we fetch data using Criteria set criteria.cacheable true.

            Criteria crit=session.createCriteria(User.class);
            crit.setCacheable(true);
            userlist=crit.list();
           
            session.close();
            return userlist;
      }
5.   Now write the main class to find the list of users.

public static void main(String[] args) {
     
      List userList=new UsersDAO().getUsers();
      System.out.println(userList.size()+" userlist1 records");
     
      List userList2=new UsersDAO().getUsers();
      System.out.println(userList2.size()+" userlist2 records");
      }

OUTPUT
--------------------Calling User List 1st time-----------------------------
Hibernate: select this_.userId as userId0_0_, this_.address as address0_0_, this_.city as city0_0_, this_.hobbies as hobbies0_0_, this_.interest as interest0_0_, this_.isDeleted as isDeleted0_0_, this_.name as name0_0_, this_.state as state0_0_ from userdetails this_

29 userlist1 records
------------------Calling User List 2nd time------------------------------
29 userlist2 records


We have already enabled the show_sql property of hibernate true so now when we call the user list first time it fetch records from the database and print the select query.
But when we call the same user list second time it does not hit the database and fetch the user list from the cache and hibernate does not print and select query on the console.


Note : you can configure your cache to store the data on RAM or in Hard Disk.
 If you want to remove second level cache from the entity you can use the following method to remove it.
            sessionFactory.evictEntity(“User”);

Spring Boot Config Server and Config Client.

 In Spring cloud config we can externalise our configuration files to some repository like GIT HUT, Amazon S3 etc. Benefit of externalising ...