Wednesday, June 4, 2014

How to add Foreign Key to existing table column in mysql?

It is simple to add a foreign key to a column in Existing table.The Following command adds foreign key to the table


alter table table_name add CONSTRAINT foreign_key_constraint_name FOREIGN KEY (column_name)  REFERENCES reference_table_name (reference_table_column_name) ON UPDATE CASCADE ON DELETE CASCADE;  
                       
Eg:    
alter table MerchantOfferImage add CONSTRAINT banner_image_id_fk FOREIGN KEY (banner_image_id)  REFERENCES MerchantOffer (offer_id) ON UPDATE CASCADE ON DELETE CASCADE;
                                                                   or
alter table MerchantOfferImage add foreign key(offer_id) references MerchantOffer (offer_id)  ON UPDATE CASCADE ON DELETE CASCADE;

How to remove primary key Constraint in mysql?

.





We should remove the autoincrement property before dropping the key

ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
Eg: 
ALTER TABLE User MODIFY id int NOT NULL;

Then delete the primary key Constraint            

ALTER TABLE table_name DROP PRIMARY KEY;                      
Eg: 
ALTER TABLE User DROP PRIMARY KEY;


Thursday, May 29, 2014

Spring MVC

Introduction:
              Spring MVC has the most flexible architecture to develop web applications in java/spring environment.It provides clear separation of different layers components, with this MVC Architecture we can use different types front-end technologies like Jsp,freemaker etc.

Basic architecture and flow of Spring MVC Architecture


Dispatcher Servlet: 'Dispatcher Servlet'  which receives  requests and forward them to controllers and also allows to use Other all Features.It traps and takes the requests  and dispatches them to the appropriate controllers with the help of Handler Mappings.

Handler Mapping: Handles the execution of a list of pre-processors and post-processors and controllers if they match certain(Ex: matching URL specified with a controller).It maps requests with Intended Controllers.

Controller: Controller interpret user input and transforms it into a model that represented to the user by View. It serves the user requests and returns Model and View Object.

ViewResolver:  resolves view names to views.

View:  A view is a generated HTML output to the User.

Lets take an Example to explain flow of Spring MVC.

1. Take a new DynamicWebApplication in your IDE with name 'Spring3MVC'.
                       

    
2. go to WEB-INF  Folder and Add the following code to web.xml file.

 <!-- Dispatcher Servlet -->    <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

By adding the above code we are configuring the 'DispatcherServlet'  or Front Controller which controls the entire application execution flow of control.

3. Next add some list of jar file as shown below in lib Folder.
          
     

I am using spring 3.2.2 in my application.you can get 'commons-logging.jar' from spring 2.5 and download 'jstl.jar' .

4.Add a Controller class to service/process client request.
In my application i want to display some 'hello world ' kind of message so i use my     Controller to do this.add this controller in some package like 'com.controller'

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

   @RequestMapping("/hello")
   public ModelAndView helloWorld() {

       String message = "Hello World, Spring 3.2.2..!!";
       return new ModelAndView("hello", "message", message);
   }
}


In the above code there are 2 Annotations
  •       @Controller
  •       @RequestMapping("/hello")
 @Controller-tells to spring that this bean is a Controller bean to process client  
                         requests.
@RequestMapping("/hello")-tells to spring that this bean should process all the requests beginning  with '/hello'. 

This controller returns Model and View Object with a message ''Hello World, Spring 3.2.2..!!".

5. To display this result to the client we need View.we are using jsp in view layer. So we have to create a jsp with name hello.jsp. place this jsp file in WEB-INF/jsp folder.

    

the code in hello.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>hello</title>
    <title>Spring 3.2.2 MVC: Hello World</title>
</head>
<body>
    ${message}
</body>
</html>

This 'message' displays Hello World, Spring 3.2.2..!! ,Because message is the name in Model and View Object which return by the Controller.

And also we need one more jsp to send request, for this take a jsp with name 'index.jsp' and place in in /WEB-INF/jsp/ Folder.


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring 3.2.2 SpringMVC</title>
</head>
<body>
    <a href="hello.htm">demo request</a>
</body>
</html>

make this 'index.jsp' as the welcome file for Application,to do this add following code to web.xml file.

<display-name>Spring3MVC</display-name>
  <welcome-file-list>
    <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
  </welcome-file-list>

Finally we need spring bean configuration file with name 'springmvc-servlet.xml'. Because when DispatcherServlet initialized it looks for file with name [value of <servlet-name> tag in DispatcherServlet configuration]-servlet.xml in WEB-INF Folder.So in our example the spring bean configuration file name should be ''springmvc-servlet.xml".

This file contains Handler Mappings, ViewResolvers, Controllers and Other Spring Bean configuration.
our file contains

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
.......>

     <context:component-scan  base-package="com.controller" />
       
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
   </beans>

The '<context:component-scan  base-package="com.controller" />' tag tells Spring to load components from 'com.controller' package and it's sub packages.
The ViewResolver  bean resolves the view and add prefix  '/WEB-INF/jsp/' and suffix '.jsp' . In this app Controller HelloWorldController have return Model and View Object with view hello ,this resolver resolves that to '/WEB-INF/jsp/hello.jsp'.

Final structure of Application
                  


Flow:
1. request sent from index.jsp.

2. DispatcherServlet traps and Takes the request and dispatches it to Controller HelloWorldController by looking at HadlerMapping(this was done by annotations).

3. Controller HelloWorldController process use request and returns a Model and View Object with View name hello and other details.

4. DispatcherServlet resolves the view name to '/WEB-INF/jsp/hello.jsp' by looking at into ViewResolver Configuration in Spring bean configuration file springmvc-servlet.xml. The hello.jsp rendered by the spring and send to the client.

That is the end of Spring MVC First App.


Monday, April 14, 2014

Auto wiring in Spring

Assigning  dependent values to spring bean resources is technically known as "WIRING". There are 2 types in wiring. They are

  • Explicit wiring                                             
  • Auto wiring
Explicit wiring
The setter injection,constructor injections are considered as explicit wiring. In this approach programmer has to pass/provide dependent value the spring container to inject to the reference bean.

Auto wiring: 
In this approach spring container itself choose the dependent value to assian to resource. To let Spring container do this we use '<autowire>' attribute in bean tag.

There are 4 types of auto wiring,
byName:  
In this type of auto wiring the spring container assigns value to the dependent bean by  name of the bean property, i.e the id of the dependent bean object and the name of the spring bean property must be same.
In this approach spring container use setter injection to assign value.

Look at the following example ...how a java.util.Date value is assigning to the bean
in this example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;

 /**
* @return the uname
*/
public String getUname() {
return uname;
}
/**
* @param uname the uname to set
*/
public void setUname(String uname) {
this.uname = uname;
}
/**
* @return the date
*/
public Date getDate() {
return date;
}
/**
* @param date the date to set
*/
public void setDate(Date date) {
this.date = date;
  System.out.println("date: "+date);
}
}

MainApp.java 
//MainApp.java
public class MainApp{
public static void main(String a[]){
FileSystemResource res=new FileSystemResource("beans.xml");
XmlBeanFactory factory=new XmlBeanFactory(res);
Demo beanobj=(Demo)factory.getBean("demobean");
}
}

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="byName">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

with the  autowire="byName"  the spring container look for  bean object which has 'date' as id (here date is property name)  if found assigns to the resource other wise no value will be assigned.

byType:
In this type of auto wiring the spring container assigns value to the dependent bean by  type(data type) of the bean property, i.e the type(data type) of the dependent bean object and the type(data type) of the spring bean property must be same.
In this approach spring container use setter injection to assign value.

Look at the following example ...how a java.util.Date value is assigning to the bean
in this example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

DemoBean.java & MainApp.java are same,but change in beans.xml

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="byType">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

with the  autowire="byType"  the spring container look for  bean object 'java.util.Date'  type if found assigns to the resource other wise no value will be assigned.
If more than one 'java.util.Date'  type object found in spring configuration file Exception will be thrown by container.

constructor:
In this type of auto wiring the spring container assigns value to the dependent bean through parameterized constructor  of bean , i.e the the spring container calls
parameterized constructor to assign dependent values to the resource.This is similar to byTtype  mode.

Look at the following example ...how a java.util.Date value is assigning to the bean
in this example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

in this example MainApp.java is same and changes are needed in beans.xml,
DemoBean.xml.

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="constructor">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;

 /**
 * @return the uname
 */
public String getUname() {
return uname;
}
/**
 * @param uname the uname to set
 */
public void setUname(String uname) {
this.uname = uname;
 System.out.println("uname:  "+uname);
}
/**
*constructor
**/
public DemoBean(Date d){
date=d;
  System.out.println("date: "+date);
}
}

with the  autowire="constructor"  the spring container look for  bean object 'java.util.Date'  type if found assigns to the resource otherwise Exception will be thrown by container.
If more than one 'java.util.Date'  type object found in spring configuration file Exception will be thrown by container.

autodetect:
In this mode of auto wiring spring container first try to assigns a value to dependent bean using constructor mode if this mode is not possible then container go to byType mode, i.e if we place a constructor in bean class container choose constructor mode else you place setter methods container use byType mode.

Lets take the same example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

in this example MainApp.java is same and changes are needed in beans.xml,
DemoBean.xml.

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="autodetect">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;

 /**
 * @return the uname                                                                  1
 */
public String getUname() {
return uname;
}
/**
 * @param uname the uname to set
 */
public void setUname(String uname) {
this.uname = uname;
 System.out.println("uname:  "+uname);
}

/**
*constructor
**/
public DemoBean(Date d){
date=d;
  System.out.println("constructor autowiring: "+date);
}
}

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;
                                                                                                             2
 /**
 * @return the date
 */
public Date getDate() {
return date;
}
/**
 * @param date the date to set
 */
public void setDate(Date date) {
System.out.println("setter method autodetect: "+date);
this.date = date;
}

 /**
 * @return the uname
 */
public String getUname() {
return uname;
}
/**
 * @param uname the uname to set
 */
public void setUname(String uname) {
this.uname = uname;
 System.out.println("uname:  "+uname);
}
}

with 1 'DemoBean.java' spring container performs constructor based auto wiring and
with 2 'DemoBean.java' spring container performs byType(setter injection) based auto wiring.
if neither constructor nor setter method found container don't assign a value.

Limitations of Autowiring:
  1. Autowiring is possible only on reference type Bean Propertied(we can inject only object,simple values can not be injected).
  2. There is chance of getting ambiguity.
  3. Kills readability of spring configuration file.


Wednesday, April 9, 2014

Bean Scopes in Spring

Spring Provides Multiple types of Scopes.Here we can consider scope is availability of bean Object.The different types of scopes are
  1. singleton                                                             
  2. prototype
  3. request
  4. session
  5. globalsession

singleton: The singleton means creating only one object/ instance per JVM.
The class which allow to create only one object per JVM is known as singleton class.
  • This is the default scope of spring bean.
  • spring container returns the same object every time you access  from BeanFactory or ApplicationContext objects.

Ex for specifying scope in spring configuration file of a bean is

<bean id="beanid" class="beanclass" scope="singleton"/>
                                              or
<bean id="beanid" class="beanclass" scope="singleton">
....
...
</bean>

for singleton scope no need to specify it in spring configuration file ,because it is the default scope.

prototype: In this prototype scope the spring container creates and returns a new object for each time when you access  from BeanFactory or ApplicationContext objects.

Ex for specifying scope in spring configuration file of a bean is

<bean id="beanid" class="beanclass" scope="prototype"/>
                                              or
<bean id="beanid" class="beanclass" scope="prototype">
....
...
</bean>

request:
  • The request scoped bean object will be created one per HTTP request .
  • This bean object will become request object attribute value.
Ex for specifying scope in spring configuration file of a bean is

<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>
                                                            or
<bean id="loginAction" class="com.foo.LoginAction" scope="request">
....
...
</bean>

  • With the above bean definition  the Spring container will create a brand new instance of the LoginAction bean using the 'loginAction' bean definition for each and every HTTP request.
  • When the request is finished the bean that is scoped to the request will be discarded.
  • It is useful only in web Environment.

session:
The session scoped beans will be created one per HTTP session.
This bean object will become HTTP session scope object.

Ex for specifying scope in spring configuration file of a bean is

<bean id="loginAction" class="com.foo.LoginAction" scope="session"/>
                                                            or
<bean id="loginAction" class="com.foo.LoginAction" scope="session">
....
...
</bean>

  • With the above bean definition  the Spring container will create a brand new instance of the LoginAction bean using the 'loginAction' bean definition for each and every HTTP session.
  • When the HTTP session is finished the bean that is scoped to the session will be discarded.
  • It is useful only in web Environment.

globalsession: 
  • This is similar to the session scope.
  • But this is useful in Spring based portlet development environment.
Ex for specifying scope in spring configuration file of a bean is

<bean id="loginAction" class="com.foo.LoginAction" scope="globalsession"/>
                                                            or
<bean id="loginAction" class="com.foo.LoginAction" scope="globalsession">
....
...
</bean>

These are the scopes in Spring Framework.