Friday, December 2, 2016

Hibernate: query.list() or criteria.list() is very slow or taking too long

Stumbled upon a perforamance problem in my application where the execution was taking ages. It was fetching around 1000-2000 records from the oracle database. After investigating for couple of days and tried various randon things i wasn't able to figure out much what was going wrong, I debugged to the point where i came to know that it was looping of the result set which was taking time, and then my friend who is also programmer asked why you look frustrated and i told her the issue, she said she will think about it and then after sometime she said, have you tried fetch size. I was like, comon how the fetch size can affect the looping but Bingo! that was a bull's eye. Advantage of having brainy friends.

There is also a great analysis done by Andreas on https://stackoverflow.com/questions/17744090/iterating-a-resultset-using-the-jdbc-for-oracle-takes-a-lot-of-time-about-16s/17744738#17744738


So, lets narrow down the options if you stumbled upon such issues.

1. setFetchSize(1000).

2. Check the fetch type for your joins in the entity model. See in the hibernate logs that if it is executing too many queries for single execution then you must be facing n+1 problem in which your fetching making round trips to the database to get the data. Try fetch="join" instead of "select". be careful in using it as you may worsen the situation because you are enabling the eager fetch.

3. There was a very siple query which was taking way more than the expected time and it was random timings as well. The query was something like "Select * from XYZ where columnId=123". How long do you think it should take in fetching from 350000 records. Yes, within a second. but, it was talking from 2-8 seconds. So what i find that the column was missing the indexing. Indexing is mandatory to improve your performance in fetching the result on the basis of certain column data. So i did create the index on that column, It wan't a unique data column so can't create the unique index but only the index. And it works like magic.


There are other random things which i tried but didn't help much in my case:

1. Creating your Entity class constructor with all the member variables of the class.

2. Correcting the doctype in hbm and config files.

Monday, April 20, 2015

Spring Boot demo with Maven:


Using:


Java 1.7
Maven 3.2

Steps:


Install spring CLI :
--------------------------


Unzip it and set the path of the folder to environment variables.

Set Environment Variables
---------------------------
set SPRING_HOME to point to a specific installation. 
You should also add SPRING_HOME/bin to your PATH environment variable.

Checking Your Installation
----------------------------
To test if you have successfully install the CLI you can run the following command:

               spring --version

Create a demo using the following link:
-----------------------------


Check Actuator under section “Ops” and Web.

Click generate project and then import that project in eclipse or your IDE.

In DemoApplication class:
--------------------------------

@RestController
@EnableAutoConfiguration
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
   
    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }
}

Run the demo:
----------------------------

Using the command: mvn spring-boot:run

Run your demo and hit localhost:8080




Saturday, April 11, 2015

Broadleaf commerce with Rest Api

Common errors that occured while working with broadleaf & Rest Api

1. 

Error:

SEVERE: A message body writer for Java class com.wrapper.CustomNameWrapper, and Java type class com.wrapper.CustomNameWrapper, and MIME media type application/xml was not found
Apr 11, 2015 9:58:06 PM com.sun.jersey.spi.container.ContainerResponse write
SEVERE: The registered message body writers compatible with the MIME media type are:
application/xml ->
  com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$App
  com.sun.jersey.core.impl.provider.entity.DocumentProvider
  com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter
  com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$App
  com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$App
*/* ->
  com.sun.jersey.core.impl.provider.entity.FormProvider
  com.sun.jersey.core.impl.provider.entity.MimeMultipartProvider
  com.sun.jersey.core.impl.provider.entity.StringProvider
  com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
  com.sun.jersey.core.impl.provider.entity.FileProvider
  com.sun.jersey.core.impl.provider.entity.InputStreamProvider
  com.sun.jersey.core.impl.provider.entity.DataSourceProvider
  com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
  com.sun.jersey.core.impl.provider.entity.ReaderProvider
  com.sun.jersey.core.impl.provider.entity.DocumentProvider
  com.sun.jersey.core.impl.provider.entity.StreamingOutputProvider
  com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter
  com.sun.jersey.server.impl.template.ViewableMessageBodyWriter
  com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider
  com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
  com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General


Cause:

The controller/endpoint class annotated with proper @Produces element but in the wrapper the following root element was missing :

Solution:


@XmlRootElement(name = "name")
@XmlAccessorType(value = XmlAccessType.FIELD)




2. 

Error:


SEVERE: Exception sending context destroyed event to listener instance of class org.broadleafcommerce.common.web.extensibility.MergeContextLoaderListener
java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
         at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:171)
         at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1090)
         at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1064)
         at org.broadleafcommerce.common.web.extensibility.MergeXmlWebApplicationContext.doClose(MergeXmlWebApplicationContext.java:149)
         at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:1010)
         at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:586)
         at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:143)
         at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4980)
         at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5626)
         at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
         at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
         at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
         at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
         at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
         at java.util.concurrent.FutureTask.run(FutureTask.java:166)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:722)



Cause/Solution:

The most common error that I faced till now was due the silly mistakes in the application-context.xml files. Be careful about your change in the config files rather try to do step by step instead of all in once. That is why I personally do not prefer the xml-based configurations and rely generally on on java-based configurations.

Tuesday, May 27, 2014

Generating PDF from HTML using itext & flying-saucer


public static void main(String[] args)
       {
              try
              {
                     String inputFile = "firstdoc.xhtml";
                     String outputFile = "firstdoc.pdf";
                     OutputStream os = new FileOutputStream(outputFile);

                     InputSource source = new InputSource(inputFile);
                     DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                     Document xhtmlContent = documentBuilder.parse(source);
                     ITextRenderer renderer = new ITextRenderer();
                     renderer.setDocument(xhtmlContent, null);
                     renderer.layout();
                     renderer.createPDF(os);

                     os.close();
              }
              catch (Exception e)
              {
                     e.printStackTrace();
              }

Tuesday, January 28, 2014

Hierarchical/Grouping enum :

We have different statuses and under each status there were sub statuses. We don’t want to check in switch or/if-else each sub statuses so we will check the main status.

public enum Status
{
       ACTIVE1(Group.ACTIVE, "active value 1"),
ACTIVE2(Group.ACTIVE, "active value 2"),
ACTIVE3(Group.ACTIVE, "active value 3"),
       BLOCKED1(Group. BLOCKED, "blocked value 1"),
BLOCKED2(Group. BLOCKED, "blocked value 2"),
BLOCKED3(Group. BLOCKED, "blocked value 3");

public enum Group
{
       ACTIVE, BLOCKED;
}

private String value;
private Group group;

private Status(Group group, final String value)
{
    this.value = value;
    this.group = group;
}

public String getValue()
{
       return this.value;
}
      
public Group getGroup()
{
       return this.group;
}
      
public boolean isInGroup(Group group)
{
    return this.group == group;
}
}

Using this enum in our conditional statements :

switch(statusObject.getGroup())
{
       case ACTIVE:
       case BLOCKED:
}

If(ACTIVE1.isInGroup(Group.ACTIVE)) // true


References:


Monday, October 21, 2013

Common git commands:


1. To cut a new branch from an existing one
       • git checkout -b "branch name"

2. To push the above created branch
       • git push –u origin “branch name”

3. To rename a branch 
       • git branch –m “old name” “new name”

4. To remove all the commits 
       • git reset –hard origin/branchName

5. To delete a branch (First remove remote)
       • git push origin :branchName

6. To delete a branch (Then Locally)
       • git branch –d branchName
       • git branch –D branchName (Forcefully)

7. To remove a file from staging area
       • git reset HEAD fileName

8. To remove commit 
  • git reset --hard HEAD
then
  • git push origin HEAD --force 

Monday, October 14, 2013

Replacing with new line in eclipse using regular expression:


Regular expression for the new line in eclipse:

For eg:

Convert from :

public String getAddress() {
              return address;
       }

To:

public String getAddress ()
{
return address;
}

Check the regular expression checkbox.

In Find:           \) \{

Replace with:           )\n\t\{
                                 OR
                              )\R\t\{