Hibernate Basics

Hibernate is a framework that takes the burden of object persistence in a relational database. With a bit of configuration, developers can concentrate on the object for data persistence while Hibernate takes care of the object-relational mismatch problem. There are three steps involved in using Hibernate:
  • Configuring the Session Factory and datasources
  • Setting the Hibernate properties
  • Creating the POJO and relevant mappings



    First, Hibernate requires a configuration file, called hibernate.properties, from where it can create a Session Factory.  In this file we define the Datasource,username,password,URL,Driver information...etc

    example :

    hibernate.dialect org.hibernate.dialect.MySQL5Dialect
    hibernate.connection.driver_class com.mysql.jdbc.Driver
    hibernate.connection.url jdbc:mysql://localhost:3306/JSDATA
    hibernate.connection.username user
    hibernate.connection.password password
    hibernate.current_session_context_class thread
    hibernate.show_sql false
     
     
    Note that you can define the same properties using a XML file,usually called 
    as hibernate.cfg.xml. 
    
    
    
    
    The next step is to create a mapping file that maps the Objects classes to the Database table 
    columns.
     
     
    
    
    
      
        
          
        
        
        
        
        
        
      
    
     
    The class attribute declares a fully qualified name of the Java object while table attribute points to the corresponding TRADES table.


    Now that our configuration and mapping is done, it is time to write a simple client:
    public class PlainHibernateTest {
      private SessionFactory factory = null;
      private Configuration configuration = null;
      public PlainHibernateTest() {
        configuration = new Configuration();
        configuration.addFile("Trade.hbm.xml");
        factory = configuration.buildSessionFactory();
      }
    
      private void testInsert(Trade t) {
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        session.save(t);
        session.getTransaction().commit();
        System.out.println("Inserted Trade"+t.getId());
      }
    
      public static void main(String[] args) {
        Trade t = DomainUtil.createDummyTrade();
        PlainHibernateTest test = new PlainHibernateTest();
        test.testInsert(t);
      }
    }


     
  • As you can see above, the Configuration object is created first. Behind the scenes, the framework reads the hibernate.properties, file which is available in the classpath and creates the Configuration object. You can provide the respective mapping files by invoking the appropriate method toward the configuration. The Configuration object is then used to create a SessionFactory. Once you have a SessionFactory, create a Session from it and start your work. The Trade is persisted into the database when you call save() on a session.
     

Spring

Injection Types

Constructor Type Injection


public class Subclass implements Super {
  private String fHost = null;
  private int fPort = 0;

  public Subclass(String fHost, int fPort) {
    this.fHost = fHost;
    this.fPort = fPort;
  }

  @Override
  public String read() {
    // your impl goes here
    return null;
  }
}
                
The fHost and fPort arguments are then wired using constructor-arg attributes defined in the XML config file:
 name="reader" class="com.test.Subclass">
   value="test.com" />
   value="1040" />
 
 
You can set references to other beans, too via the constructor arguments.
 
 name="readerService" 
    class="com.test.ReaderService">
   ref="reader" />


 name="reader" class="com.test.Subclass">
   value="src/main/resources/basics/basics-trades-data.txt" />
 

This is how the ReaderService will look with a constructor accepting
        an IReader type:
public class ReaderService  
{
 private IReader reader = null;
 public ReaderService(IReader reader)  {
this.reader = reader;  
}  
... }

 Argument type resolution

 name="reader" class="com.test.Subclass">
   type="String" value="test.com" />
   type="int" value="1040" />

                
The types are normal Java types—such as int, boolean, double, String, and so on.
You could also set index’s on the values, starting the index from zero as shown here:
 name="reader"  class="com.test.Subclass">
   index="0" type="String" value="test.com" />
   index="1" type="int" value="1040" />

Setter Type Injection

In order to use the setter injection, we have to provide setters on the respective variables. If the property exhibits read and write characteristics, provide both a setter and a getter on the variable.

public class ReaderService {
  private IReader reader = null;

  // Setter and getter
  public void setReader(IReader reader) {
    this.reader = reader;
  }
  
  public IReader getReader() {
    return reader;
  }
  ...
}            
The significant points are the the setter and getter methods on the IReader variable and the omission of the constructor altogether. The configuration of the class in our XML file looks like this:
 name="readerService" 
    class="com.test.ReaderService">
  
   name="reader" ref="reader"/>


 name="reader" class="com.test.Subclass">
  ...
 
 
 
We can mix the injection types as we like .

 name="reader" 
    class="........">
   value="src/main/resources/basics/basics-trades-data.txt" />
   name="componentName" value="TradeFileReader"/>
     

 

Composite Pattern

Composite Pattern:

Applicability:

.Objects must be composed recursively

  and no distinction between  individual  and composed elements

  and objects in structure can be treated uniformly.


Composite pattern is one of the Structural design pattern and is used when we have to represent a part-whole hierarchy. When we need to create a structure in a way that the objects in the structure has to be treated the same way, we can apply composite design pattern.
Lets understand it with a real life example – A diagram is a structure that consists of Objects such as Circle, Lines, Triangle etc and when we fill the drawing with color (say Red), the same color also gets applied to the Objects in the drawing. Here drawing is made up of different parts and they all have same operations.
Composite Pattern consists of following objects.

  1. Base Component – Base component is the interface for all objects in the composition, client program uses base component to work with the objects in the composition. It can be an interface or an abstract class with some methods common to all the objects.
  1. Leaf – Defines the behaviour for the elements in the composition. It is the building block for the composition and implements base component. It doesn’t have references to other Components.
  1. Composite – It consists of leaf elements and implements the operations in base component.
Important Points about Composite Pattern
  • Composite pattern should be applied only when the group of objects should behave as the single object.
  • Composite pattern can be used to create a tree like structure.




java.awt.Container#add(Component) is a great example of Composite pattern in java and used a lot in Swing.

Design Patterns

Patterns:

Composite Pattern:

Used under Design Problem: Non -Extensible and error prone design.

Composite Intent:Treat individual objects and multiple,recursively composed objects uniformly.

Bridge Pattern:

Used under Design Problem:Minimizing impact of variability.

Bridge Intent:Separate an abstraction from its implementation.So the two can vary independently.



Designing


Following Behaviors helps to enhance the software quality

Abstraction- emphasize what is important and De-emphasize the unimportant at a particular level of detail.

Flexibility-apply components in ways that may not be anticipated originally.

Reuse-take components developed before and applying in new contexts,where they may not be intended to be used.

Quality-ensure that bugs are eliminated,vulnerabilities fixed and code is made more "bullet proof".

Modularity-Divide and conquer a big problem space into smaller chunks that have low coupling and high cohesion,so developers and teams can work independently.