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.




Java Annotations

 Java annotations—annotations automatically generate the code necessary for classes that use them to seamlessly connect within specific frameworks.

REST Annotations

@XmlRootElement : -
When a top level class or an enum type is annotated with the @XmlRootElement annotation, then its value is represented as XML element in an XML document.

Usage: - The @XmlRootElement annotation can be used with the following program elements:

  • a top level class
  • an enum type
@Controller:-
This annotation indicates that a particular class serves as a controller. The basic purpose of the @Controller annotation is to act as a stereotype for the annotated class, indicating its role. The dispatcher will scan such annotated classes for mapped methods, detecting @RequestMapping annotations.  This is easily achieved by using the spring-context schema.

@Controller annotation in spring provides a feature of auto detection. To enable auto detection of such annotated controllers, we have to add “component-scan” in spring-context and needs to provide the base-package name or controller class package name.

 
@RequestMapping :-

This annotation is used to map a web-request to a specific class or method in controller which will handle the corresponding request.  We can apply this annotation for both at class level and method level. In class level we need to map the URL of the web-request (http request) and in method level we can map url or we can also map HTTP request methods. Example:-

@RequestMapping(method = RequestMethod.GET, value = "/getEmployees")

@RequestBody :-
This annotation indicates that a method parameter should be bound to the value of the HTTP request body.

@RequestMapping(method = RequestMethod.POST, value = "/saveEmployee")

      public ModelAndView saveEmployeeInDB(@RequestBody String body) {



            Source source = new StreamSource(new StringReader(body));

            EmpBean e = (EmpBean) jaxb2Mashaller.unmarshal(source);

            System.out.println("the val from addEmployee-" + e.toString());

            employeeDS.saveEmployee(e);

            return new ModelAndView(XML_VIEW_NAME, "emp", e);

      }



Here we are converting the request body to the method argument by using an HttpMessageConverter. HttpMessageConverter is responsible for converting from the HTTP request message to an object and converting from an object to the HTTP response body. DispatcherServlet supports annotation based processing using the DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter.
In Spring 3.0 the AnnotationMethodHandlerAdapter is extended to support the @RequestBody and has the following HttpMessageConverters registered by default:

·         ByteArrayHttpMessageConverter converts byte arrays.

·         StringHttpMessageConverter converts strings.

·         FormHttpMessageConverter converts form data to/from a MultiValueMap.

·         SourceHttpMessageConverter converts to/from a javax.xml.transform.Source.

·         MarshallingHttpMessageConverter converts to/from an object using the org.springframework.oxm package.
Note: - Reference from springsource.org

@PathVariable: -
In Spring MVC we can use the @PathVariable annotation on a method argument to bind it to the value of a URI template variable.

@RequestMapping(method = RequestMethod.DELETE, value = "/removeEmployee/{id}")

      public ModelAndView removeEmployeeFromDB(@PathVariable String id) {



            employeeDS.removeEmployee(Long.parseLong(id));

            List employees = employeeDS.getAllAfterDelete();

            EmpListBean list = new EmpListBean(employees);

            return new ModelAndView(XML_VIEW_NAME, "empBeanList", list);

      }

This will extract the part of the URL represented by {id}, and bind it to the id method parameter, e.g. taken as a string.
Java 5 enumeration of HTTP request methods. Intended for use with the RequestMapping.method () attribute of the RequestMapping  annotation.  Note that, by default, DispatcherServlet supports GET, HEAD, POST, PUT and DELETE only.

contextConfigLocation: -(Note :- This is a parameter(init/context), not annotation)
This init-param is required by DispatcherServlet. Using this parameter, we can change the name of Spring’s web context file and also we can change its(Spring’s web context file) location.


    contextConfigLocation

   

                                                /WEB-INF/restWebServiceWithCRUDOperations-context.xml

                               

 



Note: - contextConfigLocation parameter will call setContextConfigLocation method on DispatcherServlet and overrides default spring context config file. It is also possible to add multiple locations separated by any number of commas and space.


        contextConfigLocation

        /WEB-INF/spring-bean.xml, /WEB-INF/spring-bean-ds.xml, /WEB-INF/spring-bean-service.xml


@Consumes
This annotation works together with @POST and @PUT. It tells the framework to which method to delegate the incoming request.


@Produces

This annotation works with @GET, @POST, and @PUT. It lets the framework know what type of representation to send back to the client.


 


JAX-RS provides some annotations to aid in mapping a resource class (a POJO) as a web resource. The annotations include:

In addition, it provides further annotations to method parameters to pull information out of the request. All the @*Param annotations take a key of some form which is used to look up the value required.

  • @PathParam binds the method parameter to a path segment.
  • @QueryParam binds the method parameter to the value of an HTTP query parameter.
  • @MatrixParam binds the method parameter to the value of an HTTP matrix parameter.
  • @HeaderParam binds the method parameter to an HTTP header value.
  • @CookieParam binds the method parameter to a cookie value.
  • @FormParam binds the method parameter to a form value.
  • @DefaultValue specifies a default value for the above bindings when the key is not found.
  • @Context returns the entire context of the object.(for example @Context HttpServletRequest request)

Java Programming Overview

-If you do not provide an explicit call to super with arguments,the compiler provides a call to the super with no arguments,which results in calling a no-arguments constructor of the superclass.

-If you don't provide a no-argument constructor,the compiler makes call to the default no-argument constructor,which it provides itself.This will happen only if you have not defined any other constructor for the class;otherwise ,the compiler throws an error.

-An inherited class inherits all the fields and methods of its base class,except for its constructors.The constructor are strictly used by that base class only.

-The general rule is that if you want to detect an object type in an inheritance hierarchy,start with lowermost subclass and then move up the hierarchy to the base class.
example ;while using the instanceof operator .

-Whenever you create the subclass ,its parent class object is automatically created.

-With the extend keyword ,the subclass will be able to inherit all the properties of the superclass except the private properties.

-If you provide a constructor of your own-either no-argument one or one with arguments in the class definition-the compiler will not provide a default constructor.

-In string class--Clone method perform shallow copy and not deep copy.A shallow copy copies only the "surface' portion of an object.The actual object consists of this"surface",plus the all the objects are pointing to and so on.Copying entire web of objects is called a deep copy.

-A call to the this constructor must be the first statement int he implementation of the constructor.It cannot appear anywhere else.Therefore,you can have only one call to this,which must be first statement in the method body.If you call this ,you cannot call super because super cannot appear anywhere else other than the first statement.

-The overloading method differs by the number of the parameters or the  order of the parameters.

-The default implementation of the toString method returns an object reference.Many time developers override this method to print the object's state int the desired format.

-The first statement int he constructor may be call to to super or this.We use super to call the superclass constructor and use this to call some other class constructor defined within the same class.

-The final keyword can be used on class,a method or a variable.In general the use of final keyword restricts the further extensions or modifications.

-JVM creates all string literal objects in a dedicated memory pool and allocates the same reference to all strings having the same value.Therefore making the string class final makes sense so that java creators have ultimate control over the memory allocation used by the String type variables.

-If you do not want the subclass override your method implementation,you mark the method final.

-Because the private and static methods cannot be overridden in a subclass,they are always implicitly final.

-3 benefits by using final keyword
-----Explicitly preventing the overriding it in a subclass.(not to allow wait and notify methods system level methods that implement core language capabilities to modify from the Object class.)

-----final tells the compiler that a call to this method ,dynamic binding is not necessary,which potentially results in a slightly more efficient code.Static binding(compile time resolution) is more efficient than dynamic binding(runtime resolution of method call).

----marking a method final allows compile to turn any call tot hat method into an inline call.By which compiler will just replace the call with the actual method body avoiding all the overheads of storing method details on stack and popping out.

-A blank final variable must be initialized in a constructor because it is called only once during the object life cycle.If the final keyword is initialized in a constructor,it must be initialized in all overloaded constructors.

-If a final variable holds reference to an object,the reference must remain constant,not the object. We can change the object's state by invoking mutator methods on it.

-A final variable of the class type cannot refer to any object other than the object reference to which it has been set.





-

ref:Java Programming book by Poornachandra Sarang

-
Spring Bean Basics

1. If we want to access Beans in different XML Configuration files use ref tag bean attribute.
    example :

2.If we want to access Beans in same XML Configuration file use ref tag local attribute.
   example :

3..The ref tag can access bean in same or different XML file.For readability purpose we  use   local to refer to bean in same XML file.

4.In Spring there are 3 ways to inject values into  bean properties
  • Normal way :inject value using property tag.
        
               rest
         

  • Shortcut:inject value with "value" attribute.
         

  •  Using "p" schema  :  Inject values using P schemas an attributes.
         
               .....................................
              xmlns:p = http://org.springframework.com/schema/p
             
                p:name ="test" p:type = "rest"  />
        

              
5. In Large projects there are multiple configurations located at different folders for maintainability and modular.Better way to organize all spring bean configuration in single XML file and import all file resources.

 example: spring_combine.xml



.......................





Now Load all single XML file using

ApplicationContext context = new ClassPathXmlApplicationContext ("spring_combine.xml");


Then put this file under classpath

  classpath/spring_combine.xml

6. In Spring Framework,whenever a bean is used for only one particular property,it's  advise to declare it as an inner bean.And the inner bean is supported both in setter injection "property"
and constructor injection "constructor-arg".


 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
  id="CustomerBean" class="com.test.common.Customer">
   name="person" ref="PersonBean" />
 
>   id="PersonBean" class="com.test.common.Person"> name="name" value="test" /> name="address" value="address1" /> name="age" value="28" /> >   >
In general, it’s fine to reference like this, but since the ‘test’ person bean is only used for Customer bean only, it’s better to declare this ‘test’ person as an inner bean as following :
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
  id="CustomerBean" class="com.test.common.Customer">
   name="person">
    class="com.test.common.Person">
     name="name" value="test" />
     name="address" value="address1" />
     name="age" value="28" />
   
> > > >
This inner bean also supported in constructor injection as following :
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
  id="CustomerBean" class="com.test.common.Customer">
  >
    class="com.test.common.Person">
     name="name" value="test" />
     name="address" value="address1" />
     name="age" value="28" />
   
> > > >
Run it
package com.test.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class App 
{
    public static void main( String[] args )
    {
     ApplicationContext context = 
       new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
 
     Customer cust = (Customer)context.getBean("CustomerBean");
     System.out.println(cust);
 
    }
}
Output
Customer [person=Person [address=address1, age=28, name=test]]
  ref :http://www.mkyong.com/tutorials/spring-tutorials/
 7. 5 types of bean scopes supported :
  1. singleton – Return a single bean instance per Spring IoC container
  2. prototype – Return a new bean instance each time when requested
  3. request – Return a single bean instance per HTTP request. *
  4. session – Return a single bean instance per HTTP session. *
  5. globalSession – Return a single bean instance per global HTTP session. *
In most cases, you may only deal with the Spring’s core scope – singleton and prototype, and the default scope is singleton.
In Singleton scope getBean() returns only one instance.
In Proptotype scope for every call of getBean() returns new instance.
Scope can be declared 
  •    in XML configuration file by using "scope"  tag.
                 ex:
  •       Using annotaion
    @Service
    @Scope("prototype")
    public class CustomerService {.......}
      and Enabling the component scan by
      base-package="com.test.customer" />
     
8.     
Spring examples to show you how to inject values into collections type (List, Set, Map, and Properties). 4 major collection types are supported :
List,Set,Map and properties
configutraion file example :
  id="CustomerBean" class="com.test.common.Customer">
 
  
   name="lists">
   >
    >1
> bean="PersonBean" /> class="com.mkyong.common.Person"> name="name" value="testList" /> name="address" value="address" /> name="age" value="28" /> > > >   name="sets"> > >1> bean="PersonBean" /> class="com.test.common.Person"> name="name" value="testSet" /> name="address" value="address" /> name="age" value="28" /> > > >   name="maps"> > key="Key 1" value="1" /> key="Key 2" value-ref="PersonBean" /> key="Key 3"> class="com.test.common.Person"> name="name" value="testMap" /> name="address" value="address" /> name="age" value="28" /> > > > >   name="pros"> > key="admin">admin@nospam.com> key="support">support@nospam.com> > >   >   id="PersonBean" class="com.test.common.Person"> name="name" value="test2" /> name="address" value="address 1" /> name="age" value="28" /> >   > run it


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class App 
{
    public static void main( String[] args )
    {
     ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml");
 
     Customer cust = (Customer)context.getBean("CustomerBean");
     System.out.println(cust);
 
    }
}

Output
Customer [
 
lists=[
1, 
Person [address=address 1, age=28, name=test], 
Person [address=address, age=28, name=testList]
], 
 
maps={
key 1=1,
key 2=Person [address=address 1, age=28, name=test1], 
key 3=Person [address=address, age=28, name=testMap]
}, 
 
pros={admin=admin@nospam.com, support=support@nospam.com}, 
 
sets=[
1, 
Person [address=address 1, age=28, name= test1], 
Person [address=address, age=28, name=testSet]]
]