Wednesday 30 July 2014

Hibernate N+1 Problems And Solution

Hibernate N+1 SELECT’s Problems And Solution
Hibernate n+1 problems only comes for one to many relationship.
Let say one example – Retailer with a one-to-many relationship with Product. One Retailer has many Products.
***** Table: Retailer *****
+—–+——————-+
| ID | NAME |
+—–+——————-+
| 1 | Retailer Name 1 |
| 2 | Retailer Name 2 |
| 3 | Retailer Name 3 |
| 4 | Retailer Name 4 |
+—–+——————-+
***** Table: Product *****
+—–+———–+——————–+——-+————+
| ID | NAME | DESCRIPTION | PRICE | RETAILERID |
+—–+———–+——————–+——-+————+
|1 | Product 1 | Name for Product 1 | 82.0 | 4 |
|2 | Product 2 | Name for Product 2 | 20.0 | 2 |
|3 | Product 3 | Name for Product 3 | 10.0 | 2 |
|4 | Product 4 | Name for Product 4 | 77.0 | 3 |
+—–+———–+——————–+——-+————+
Factors:
Lazy mode for Retailer set to “true” (default)
Fetch mode used for querying on Product is Select
Fetch mode (default): Retailer information is accessed
Caching does not play a role for the first time the Retailer is accessed
Fetch mode is Select Fetch (default)

1
2
3
4
5
6
7
8
9
10
11
// It takes Select fetch mode as a default
Query query = session.createQuery( "from Product p");
List list = query.list();
// Retailer is being accessed
displayProductsListWithRetailerName(results);
 
// It takes Select fetch mode as a default
Query query = session.createQuery( "from Product p");
List list = query.list();
// Retailer is being accessed
displayProductsListWithRetailerName(results);


select * from PRODUCT
select * from RETAILER where RETAILER.id=?
select * from RETAILER where RETAILER.id=?
select * from RETAILER where RETAILER.id=?
Result:
1 select statement for Product
N select statements for RETAILER
This is N+1 select problem!

Solution to N+1 SELECTs problem

(i) HQL fetch join
“from RETAILER retailer join fetch retailer.product Product”
Corresponding SQL would be –
SELECT * FROM RETAILER retailer LEFT OUTER JOIN PRODUCT product ON product.product_id=retailer.product_id
(ii) Criteria query
Criteria criteria = session.createCriteria(Retailer.class);
criteria.setFetchMode(“product”, FetchMode.EAGER);
In both cases, the query returns a list of Retailer objects with the Product initialized. Only one query needs to be run to return all the Product and Retailer information required.

Tuesday 29 July 2014

How I can redirect my console output to a File?

System.out is a static PrintStream that writes to the console. We can redirect the output to a different PrintStream using the System.setOut() method which takes a PrintStream as a parameter. The RedirectSystemOut class shows how we can have calls to System.out.println() output to a file rather than to the console by passing System.setOut() a PrintStream based on a FileOutputStream.

package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class RedirectSystemOut {

 public static void main(String[] args) throws FileNotFoundException {
  System.out.println("This goes to the console");
  PrintStream console = System.out;

  File file = new File("out.txt");
  FileOutputStream fos = new FileOutputStream(file);
  PrintStream ps = new PrintStream(fos);
  System.setOut(ps);
  System.out.println("This goes to out.txt");

  System.setOut(console);
  System.out.println("This also goes to the console");
 }
}


How to configure log4j using properties file

Log4j is a simple and flexible logging framework. Logging equips the developer with detailed context for application failures. With log4j it is possible to enable logging at runtime without modifying the application binary. The log4j package is designed so that these statements can remain in shipped code without incurring a heavy performance cost.
Two most common configuration options are in practice industry wide i.e. using xml configuration and using properties configuration.
In this post, I am showing the example code for configuring log4j using properties file.
Step 1) Create a maven java project and update log4j dependencies
Follow the steps given in this post related to configuring log4j with maven.
Step 2) Create log4j.properties file
This is the main properties file having all runtime configuration used by log4j. This file will have appenders information, log level information and output file names for file appenders.
log4j.rootLogger=DEBUG, consoleAppender, fileAppender

log4j.appender.consoleAppender=org.apache.log4j.ConsoleAppender
log4j.appender.consoleAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.consoleAppender.layout.ConversionPattern=[%t] %-5p %c %x - %m%n

log4j.appender.fileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.fileAppender.layout.ConversionPattern=[%t] %-5p %c %x - %m%n
log4j.appender.fileAppender.File=demoApplication.log
Step 3) Configure log4j.properties and test the application
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package default;
 
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
 
public class Log4jPropertiesConfigurationExample
{
    static Logger logger = Logger.getLogger(Log4jPropertiesConfigurationExample.class);
    public static void main(String[] args)
    {
        //PropertiesConfigurator is used to configure logger from properties file
        PropertyConfigurator.configure("log4j.properties");
 
        //Log in console in and log file
        logger.debug("Log4j appender configuration is successful !!");
    }
}
Output in console and demoApplication.log in project root folder:
[main] DEBUG com.howtodoinjava.Log4jPropertiesConfigurationExample  - Log4j appender configuration is successful !!

Thursday 24 July 2014

Understanding SOAP and REST



Simple Object Access Protocol (SOAP) and REpresentational State Transfer (REST) are two answers to the same question: how to access Web services. The choice initially may seem easy, but at times it can be surprisingly difficult.

SOAP is a standards-based Web services access protocol that has been around for a while and enjoys all of the benefits of long-term use. Originally developed by Microsoft, SOAP really isn’t as simple as the acronym would suggest.

REST is the newcomer to the block. It seeks to fix the problems with SOAP and provide a truly simple method of accessing Web services. However, sometimes SOAP is actually easier to use; sometimes REST has problems of its own. Both techniques have issues to consider when deciding which protocol to use.
Before I go any further, it’s important to clarify that both SOAP and REST are protocols: a set of rules for requesting information from a server using a specific technique. The rules are important because without rules, you can’t achieve any level of standardization. The best way to view a protocol is as if it is a diplomat who is making a request on your behalf from another entity. Some people I’ve talked with just don’t understand the entire concept; they have the idea that some sort of magic is occurring. Both SOAP and REST rely on well-established rules that everyone has agreed to abide by in the interest of exchanging information.

A Quick Overview of SOAP

SOAP relies exclusively on XML to provide messaging services. Microsoft originally developed SOAP to take the place of older technologies that don’t work well on the Internet such as the Distributed Component Object Model (DCOM) and Common Object Request Broker Architecture (CORBA). These technologies fail because they rely on binary messaging; the XML messaging that SOAP employs works better over the Internet.
After an initial release, Microsoft submitted SOAP to the Internet Engineering Task Force (IETF) where it was standardized. SOAP is designed to support expansion, so it has all sorts of other acronyms and abbreviations associated with it, such as WS-Addressing, WS-Policy, WS-Security, WS-Federation, WS-ReliableMessaging, WS-Coordination, WS-AtomicTransaction, and WS-RemotePortlets. In fact, you can find a whole laundry list of these standards on Web Services Standards.
The point is that SOAP is highly extensible, but you only use the pieces you need for a particular task. For example, when using a public Web service that’s freely available to everyone, you really don’t have much need for WS-Security.
The XML used to make requests and receive responses in SOAP can become extremely complex. In some programming languages, you need to build those requests manually, which becomes problematic because SOAP is intolerant of errors. However, other languages can use shortcuts that SOAP provides; that can help you reduce the effort required to create the request and to parse the response. In fact, when working with .NET languages, you never even see the XML.
Part of the magic is the Web Services Description Language (WSDL). This is another file that’s associated with SOAP. It provides a definition of how the Web service works, so that when you create a reference to it, the IDE can completely automate the process. So, the difficulty of using SOAP depends to a large degree on the language you use.
One of the most important SOAP features is built-in error handling. If there’s a problem with your request, the response contains error information that you can use to fix the problem. Given that you might not own the Web service, this particular feature is extremely important; otherwise you would be left guessing as to why things didn’t work. The error reporting even provides standardized codes so that it’s possible to automate some error handling tasks in your code.
An interesting SOAP feature is that you don’t necessarily have to use it with the HyperText Transfer Protocol (HTTP) transport. There’s an actual specification for using SOAP over Simple Mail Transfer Protocol (SMTP) and there isn’t any reason you can’t use it over other transports. In fact, developers in some languages, such as Python, are doing just that.

A Quick Overview of REST

Many developers found SOAP cumbersome and hard to use. For example, working with SOAP in JavaScript means writing a ton of code to perform extremely simple tasks because you must create the required XML structure absolutely every time.
REST provides a lighter weight alternative. Instead of using XML to make a request, REST relies on a simple URL in many cases. In some situations you must provide additional information in special ways, but most Web services using REST rely exclusively on obtaining the needed information using the URL approach. REST can use four different HTTP 1.1 verbs (GET, POST, PUT, and DELETE) to perform tasks.
Unlike SOAP, REST doesn’t have to use XML to provide the response. You can find REST-based Web services that output the data in Command Separated Value (CSV), JavaScript Object Notation (JSON) and Really Simple Syndication (RSS). The point is that you can obtain the output you need in a form that’s easy to parse within the language you need for your application.
As an example of working with REST, you could create a URL for Weather Underground. The API’s documentation page shows an example URL of http://api.wunderground.com/api/Your_Key/conditions/q/CA/San_Francisco.json. The information you receive in return is a JSON formatted document containing the weather for San Francisco. You can use your browser to interact with the Web service, which makes it a lot easier to create the right URL and verify the output you need to parse with your application.

Deciding Between SOAP and REST

Before you spend hours fretting over the choice between SOAP and REST, consider that some Web services support one and some the other. Unless you plan to create your own Web service, the decision of which protocol to use may already be made for you. Extremely few Web services, such as Amazon, support both. The focus of your decision often centers on which Web service best meets your needs, rather than which protocol to use.
SOAP is definitely the heavyweight choice for Web service access. It provides the following advantages when compared to REST:
  • Language, platform, and transport independent (REST requires use of HTTP)
  • Works well in distributed enterprise environments (REST assumes direct point-to-point communication)
  • Standardized
  • Provides significant pre-build extensibility in the form of the WS* standards
  • Built-in error handling
  • Automation when used with certain language products
REST is easier to use for the most part and is more flexible. It has the following advantages when compared to SOAP:
  • No expensive tools require to interact with the Web service
  • Smaller learning curve
  • Efficient (SOAP uses XML for all messages, REST can use smaller message formats)
  • Fast (no extensive processing required)
  • Closer to other Web technologies in design philosophy