Pages

Monday, 9 January 2017

Hibernate Named Query and its advantages & disadvantages


Hibernate Named Query
If there are a lot of queries, then they will cause a code mess because all the queries will be scattered throughout the project(in java code). The hibernate named query is a technique to define a central location for all  queries and use them by some meaningful names/alias.

There are two ways to define the named query in hibernate:
by annotation
by mapping file.

Hibernate Named Query by annotation
@NameQueries annotation: is used to define the multiple named queries.

@NameQuery annotation: is used to define the single named query.

@NamedQueries({ 
      @NamedQuery( 
                  name = "findEmployeeByName", 
                  query = "from Employee e where e.name = :name" 
                  )
      } 
) 

Advantages
Named queries are compiled when SessionFactory is instantiated (so, essentially, when your application starts up). The obvious advantage, therefore, is that all your named queries are validated at that time rather than failing upon execution.

Easier to maintain than string literals embedded in the code certainlyfor complex queries.

HQL and native SQL queries can be used and replaced without code changes (no need to re-compile your code)

Disadvantages
static,  named queries are not customizable at runtime - you can define/supply parameters, of course, but beyond that what you've defined is what you'll get; you can't even change the sorting.

We will not be able to change the named query within a running application server without reloading the SessionFactory.




What is hibernate configuration and mapping file?


Hibernate configuration file
It contains database specific configurations and used to initialize SessionFactory. We provide database credentials or JNDI resource information in the hibernate configuration xml file. Some other important parts of hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.

Hibernate.dialect property tells Hibernate to generate the appropriate SQL statements for the chosen database. hibernate.dialect property makes Hibernate to generate the appropriate SQL statements for the chosen database.

<hibernate-configuration>
      <session-factory>
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="connection.url">
                  jdbc:mysql://localhost:3306/test_db
            </property>
            <property name="connection.username">root</property>
            <property name="connection.password">root</property>

            <property name="connection.pool_size">1</property>
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
            <property name="current_session_context_class">thread</property>
            <property name="cache.provider_class">
                  org.hibernate.cache.NoCacheProvider
            </property>
            <property name="show_sql">true</property>
            <property name="hbm2ddl.auto">validate</property>

            <mapping class="models.Category" />

      </session-factory>
</hibernate-configuration>

Hibernate mapping file
It is used to define the entity bean fields and database table column mappings. We know that JPA annotations can be used for mapping but sometimes XML mapping file comes handy when we are using third party classes and we can’t use annotations.

Wednesday, 4 January 2017

Hibernate Lazy loading


Lazy loading loads the child objects on demand;  We have a parent and that parent has a collection of children. Using "lazy-load" concept, all children will not load while loading the parent. Instead, it loads them when requested to do so.

It is used to improve performance significantly since often you won't need the children and so they will not be loaded. Since Hibernate 3.0, lazy collection is enabled by default.

When Lazy Loading is needed: Sample Problem
Consider an online portal which maintains catalog of products. This can be modeled as a catalog entity (Parent) managing a series of product entities (Children). In a large store, there may be tens of thousands of products grouped into various overlapping categories.

When a customer visits the store, the catalog must be loaded from the database. We probably don’t want the implementation to load every single one of the entities representing the tens of thousands of products to be loaded into memory. For a sufficiently large retailer, this might not even be possible, given the amount of physical memory available on the machine. Even if this were possible, it would probably cripple the performance of the site. Instead, we want only the catalog to load, possibly with the categories as well. Only when the user drills down into the categories should a subset of the products in that category be loaded from the database.

To manage this problem, Hibernate provides a facility called lazy loading. When enabled, an entity’s associated entities will be loaded only when they are directly requested.

How to Enable Lazy Loading in Hibernate
To enable lazy loading explicitly you must use "fetch = FetchType.LAZY" on an association which you want to lazy load when you are using hibernate annotations.

Lazy loading using Annotations
public class Category {

      @OneToMany(mappedBy = "category", fetch = FetchType.LAZY )
      private Set<ProductEntity> products;

      public Set<ProductEntity> getProducts() {
            return products;
      }
      public void setProducts(Set<ProductEntity> products) {
            this.products = products;
      }
}

Lazy loading using XML configuration
<set name="category" inverse="true" cascade="delete" lazy="false">
      <key column="category_id" />
            <one-to-many class="ProductEntity"/>
</set>

How Lazy Loading Works in Hibernate?
Hibernate uses proxy object to support lazy loading. Basically when you load data from tables, hibernate doesn’t load all the mapped objects. As soon as you reference a child or lookup object via getter methods, if the linked entity is not in the session cache, then the proxy code will go to the database and load the linked object. It uses javassist to effectively and dynamically generate sub-classed implementations of your entity objects.

Effect of Lazy Loading on Detached Entities
Hibernate can only access the database via a session, so if an entity is detached from the session and when we try to access an association (via a proxy or collection wrapper) that has not yet been loaded, Hibernate throws a org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate.

The cure is to ensure either that the entity is made persistent again by attaching it to a session or that all of the fields that will be required are accessed (so they are loaded into entity) before the entity is detached from the session.

Important point
We should also aware about n+1-problem.

Hibernate will not actually load all children when you access the collection. Instead, it will load each child individually. When iterating over the collection, this causes a query for every child. In order to avoid this, you can trick hibernate into loading all children simultaneously, e.g. by calling parent.getChildren().size().



Chocolate Distribution Problem

There are M chocolate packets each packet can have variable number of chocolates in each packet. There are N students (N < M). Distribute chocolate packets to student such that

a) Each student should get 1 packet
b) The difference between the number of chocolates in packet with maximum chocolates and packet with minimum chocolates given to the students should be minimum.

M = 1, 3, 4, 6, 5 (5 packets with specified number of chocolates in them)
N = 3
Output = 3, 5.

importjava.util.Arrays;

public class Chocalate {

     /**
      * @param chocalates
      * @param std
      * @return min difference
      */
     private static int getChocaltes(int[] chocalates, int std) {
           Arrays.sort(chocalates);
          
           int min = Integer.MAX_VALUE;
          
           for(int i=0;i<chocalates.length-std+1;i++) {
                min = Math.min(chocalates[i+std-1]-chocalates[i], min);
           }
           return min;
     }
    
     public static voidmain(String[] args) {

           int[] chocalates = {1, 3, 4, 6, 5};
           int students = 3;
          
           int minDiff = getChocaltes(chocalates, students);
           System.out.println("Minimum difference is # "+ minDiff);
     }
}

How to Fix SQL Injection Using Java PreparedStatement parameterized queries?


What is SQL injection?
SQL injection happens when you inject some content into a SQL query string, and the result modifies the syntax of your query in ways you didn't intend.

Injected SQL commands can alter SQL statement and compromise the security of an application.

SQL Injection Based on 1=1 is Always True
SELECT * FROM Users WHERE UserId = 105

Injection using “1=1”

SELECT * FROM Users WHERE UserId = 105 or 1=1;

SQL Injection Based on ""="" is Always True
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"

Injection using “=”

SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""

Vulnerable Usage
Example #1
String query = "SELECT * FROM users WHERE userid ='"+ userid + "'" + " AND password='" + password + "'";

Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);

This code is vulnerable to SQL Injection because it uses dynamic queries to concatenate malicious data to the query itself.

Example #2
String query = "SELECT * FROM users WHERE userid ='"+ userid + "'" + " AND password='" + password + "'";

PreparedStatement stmt = connection.prepareStatement(query);
ResultSet rs = stmt.executeQuery();

This code is also vulnerable to SQL Injection. Even though it uses the PreparedStatement class it is still creating the query dynamically via string concatenation.

Fix SQL injection using PreparedStatement
A PreparedStatement represents a precompiled SQL statement that can be executed multiple times without having to recompile for every execution.

PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE userid=? AND password=?");

stmt.setString(1, userid);
stmt.setString(2, password);

ResultSet rs = stmt.executeQuery();

This code is not vulnerable to SQL Injection because it correctly uses parameterized queries. By utilizing Java's PreparedStatement class, bind variables (i.e. the question marks) and the corresponding setString methods, SQL Injection can be easily prevented.

Advantage of PreparedStatement?
Improves performance: The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once.





Monday, 2 January 2017

Difference between AbstractFactory and Factory design patterns

Factory Method is used to create one product only but Abstract Factoryis about creating families of related or dependent products.

Factory Method pattern exposes a method to the client for creating the object whereas in case of Abstract Factory they expose a family of related objects which may consist of these Factory methods.

Factory Method pattern hides the construction of single object whereas Abstract factory method hides the construction of a family of related objects. Abstract factories are usually implemented using (a set of) factory methods.

AbstractFactory pattern uses composition to delegate responsibility of creating object to another class while Factory design pattern uses inheritance and relies on derived class or sub class to create object.

The idea behind the Factory Method pattern is that it allows for the case where a client doesn't know what concrete classes it will be required to create at runtime, but just wants to get a class that will do the job while AbstractFactory pattern is best utilized when your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details.

Real Life Examples
Factory
Imagine you are constructing a house and you approach a carpenter for a door. You give the measurement for the door and your requirements, and he will construct a door for you. In this case, the carpenter is a factory of doors. Your specifications are inputs for the factory, and the door is the output or product from the factory.

Abstract Factory
Now, consider the same example of the door. You can go to a carpenter, or you can go to a plastic door shop or a PVC shop. All of them are door factories. Based on the situation, you decide what kind of factory you need to approach. This is like an Abstract Factory.

Summary
Factory Pattern:
1. Creates object through inheritance.
2. Produce only one product.
3. Implements code in the abstract creator that makes use of the concrete type that sub-class produces.

Abstract Factory Pattern:
1. Creates object through composition.
2. Produce families of products.
3. Concrete factories implements factory method to create product.