SimpleDateFormat

            String dateFormat = "dd/MM/yyyy";
	    Scanner scanner = new Scanner(System.in);
	    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
	    Date date =sdf.parse(scanner.nextLine());
	    System.out.println(sdf.format(date));

Spring – Java Based Configuration

BasicConfig.java


package com.learningtask.init;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Configuration
@ComponentScan(basePackages ="com.learningtask")
@EnableWebMvc
public class BasicConfig extends WebMvcConfigurerAdapter{

	@Bean
	public UrlBasedViewResolver setupResolver()
	{
		UrlBasedViewResolver resolver = new UrlBasedViewResolver();
		resolver.setViewClass(JstlView.class);
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		return resolver;
	}
}

MyWebApplicationInitializer.java


package com.learningtask.init;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;

import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class MyWebApplicationInitializer implements WebApplicationInitializer{

	public void onStartup(ServletContext servletContext) throws ServletException {
		AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
		appContext.register(BasicConfig.class);
		servletContext.addListener(new ContextLoaderListener(appContext));
		ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet",new DispatcherServlet(appContext));
		dispatcher.addMapping("/");
		dispatcher.setLoadOnStartup(1);

	}

}

HomeController.java


package com.learningtask.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {
	@RequestMapping("/")
	public String home()
	{
		System.out.println("Home Controller");
		return "home";
	}
	
	
}

Spring -XML configuration in Maven

Spring Dependencies


<!-- Spring Dependency -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.2.4.RELEASE</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.2.4.RELEASE</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.2.4.RELEASE</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
			<scope>runtime</scope>
		</dependency>

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>LearningTask-webapp</display-name>
  
  <welcome-file-list>
  <welcome-file>home.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/springDispatcher-servlet.xml</param-value>
  </context-param>	
  
  
  <servlet>
      <servlet-name>springDispatcher</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>springDispatcher</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
   
  
</web-app>

springDispatcher-servlet.xml


<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans     
               http://www.springframework.org/schema/beans/spring-beans.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context.xsd
               http://www.springframework.org/schema/tx 
               http://www.springframework.org/schema/tx/spring-tx.xsd
               http://www.springframework.org/schema/mvc
			   http://www.springframework.org/schema/mvc/spring-mvc.xsd
			   http://www.springframework.org/schema/data/jpa
     		   http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
     		   http://www.springframework.org/schema/aop 
    		   http://www.springframework.org/schema/aop/spring-aop.xsd" >
	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- Scans within the base package of the application for @Components to configure as beans -->
<!-- @Controller, @Service, @Configuration, etc. -->
<context:component-scan base-package="com.sridhar.controller" />

<!-- Enables the Spring MVC @Controller programming model -->
<!-- <mvc:annotation-driven /> -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	      <property name="prefix" value="/WEB-INF/views/" />
	      <property name="suffix" value=".jsp" />
	   </bean>

</beans>

HomeController.java


package com.sridhar.controller;

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

@Controller
public class HomeController {

	@RequestMapping("/")
	public String home()
	{
		System.out.println("Home Controller");
		return "home";
	}
}

Spring Dependencies

<!-- Shared version number properties -->
<properties>
    <org.springframework.version>4.0.0.RELEASE</org.springframework.version>
</properties>

<!--
    Core utilities used by other modules.
    Define this if you use Spring Utility APIs (org.springframework.core.*/org.springframework.util.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    Expression Language (depends on spring-core)
    Define this if you use Spring Expression APIs (org.springframework.expression.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-expression</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!-- 
    Bean Factory and JavaBeans utilities (depends on spring-core)
    Define this if you use Spring Bean APIs (org.springframework.beans.*) 
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    Aspect Oriented Programming (AOP) Framework (depends on spring-core, spring-beans)
    Define this if you use Spring AOP APIs (org.springframework.aop.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    Application Context (depends on spring-core, spring-expression, spring-aop, spring-beans) 
    This is the central artifact for Spring's Dependency Injection Container and is generally always defined
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    Various Application Context utilities, including EhCache, JavaMail, Quartz, and Freemarker integration
    Define this if you need any of these integrations
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    Transaction Management Abstraction (depends on spring-core, spring-beans, spring-aop, spring-context)
    Define this if you use Spring Transactions or DAO Exception Hierarchy
    (org.springframework.transaction.*/org.springframework.dao.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    JDBC Data Access Library (depends on spring-core, spring-beans, spring-context, spring-tx)
    Define this if you use Spring's JdbcTemplate API (org.springframework.jdbc.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA, and iBatis.
    (depends on spring-core, spring-beans, spring-context, spring-tx)
    Define this if you need ORM (org.springframework.orm.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-orm</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    Object-to-XML Mapping (OXM) abstraction and integration with JAXB, JiBX, Castor, XStream, and XML Beans.
    (depends on spring-core, spring-beans, spring-context)
    Define this if you need OXM (org.springframework.oxm.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-oxm</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    Web application development utilities applicable to both Servlet and Portlet Environments
    (depends on spring-core, spring-beans, spring-context)
    Define this if you use Spring MVC, or wish to use Struts, JSF, or another web framework with Spring (org.springframework.web.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    Spring MVC for Servlet Environments (depends on spring-core, spring-beans, spring-context, spring-web)
    Define this if you use Spring MVC with a Servlet Container such as Apache Tomcat (org.springframework.web.servlet.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    Spring MVC for Portlet Environments (depends on spring-core, spring-beans, spring-context, spring-web)
    Define this if you use Spring MVC with a Portlet Container (org.springframework.web.portlet.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc-portlet</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

<!--
    Support for testing Spring applications with tools such as JUnit and TestNG
    This artifact is generally always defined with a 'test' scope for the integration testing framework and unit testing stubs
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>${org.springframework.version}</version>
  <scope>test</scope>
</dependency>

BeanFactory vs ApplicationContext

  • Spring provides two kinds of IOC container, one is BeanFactory and the other is ApplicationContext.

  • Syntactically BeanFactory and ApplicationContext both are Java interfaces and ApplicationContext extends BeanFactory.
  • Both of them are configured using XML configuration file.
  • Both BeanFactory and ApplicationContext provides a way to get a bean from Spring IOC container by calling getBean(“bean name”), but there is some difference in their working and features provided by them.

BeanFactory

ApplicationContext

BeanFactory instantiate bean when you call getBean() method. ApplicationContext instantiate Singleton bean when the container is started
BeanFactory doesn’t provide support for internationalization i.e.(i18n). ApplicationContext provides support for it.
 Implementation of BeanFactory interface is XMLBeanFactory Implementation of ApplicationContext interface is ClassPathXmlApplicationContext.
If you are using auto wiring and using BeanFactory then you need to register AutoWiredBeanPostProcessor using API. Which is configured in XML.
BeanFactory is OK for testing and non production use. ApplicationContext is more feature rich container implementation and should be favored over BeanFactory.

Example:

BeanFactory factory = new XmlBeanFactory(new FileSystemResource("spring.xml"));

ExamMark mark = (ExamMark)factory.getBean("exammark");

Example:

ApplicationContext ctx = new ClassPathXmlApplicationContext(“spring.xml”);

ExamMark mark = (ExamMark)ctx.getBean(“exammark”);

@ManyToOne

1. Create Tables


CREATE TABLE IF NOT EXISTS user_type (
  USER_TYPE_SID int(11) NOT NULL,
  USER_TYPE varchar(50) NOT NULL,
  OPRTNL_FLAG char(1) DEFAULT 'A',
  PRIMARY KEY (USER_TYPE_SID),
  UNIQUE KEY USER_TYPE (USER_TYPE)
) 

CREATE TABLE IF NOT EXISTS user_account (
  USER_SID int(11) NOT NULL AUTO_INCREMENT,
  USER_TYPE_SID int(11) NOT NULL DEFAULT '3',
  NAME varchar(50) NOT NULL,
  USERNAME varchar(50) NOT NULL,
  PASSWORD varchar(50) NOT NULL,
  EMAIL_ID varchar(100) DEFAULT NULL,
  OPRTNL_FLAG char(1) DEFAULT 'A',
  CREATED_BY int(10) DEFAULT '1',
  ACTIVE_CODE varchar(20) NOT NULL,
  PRIMARY KEY (USER_SID),
  UNIQUE KEY USERNAME (USERNAME),
  KEY USER_TYPE_CID_FK (USER_TYPE_SID)
) 

2. Entity Classes (UserType, UserDetail)

UserType.java


package com.spin.view;

import javax.persistence.Column;
import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;

@Entity
@Table (name="user_type")
public class UserType {
	
	//in this table, id is primary key.
	@Id
	@Column(name="USER_TYPE_SID")
	private Long userTypeId;
	
	@Column(name="USER_TYPE", length=50, nullable=false)
	private String userType;
	
	@Column(name="OPRTNL_FLAG", length=1, nullable=false)
	private String oprtnlFlag="A";


	@Override
	public String toString() {
		return "UserType [userTypeId=" + userTypeId + ", userType=" + userType + ", oprtnlFlag=" + oprtnlFlag + "]";
	}
	public String getOprtnlFlag() {
		return oprtnlFlag;
	}
	public void setOprtnlFlag(String oprtnlFlag) {
		this.oprtnlFlag = oprtnlFlag;
	}

	public Long getUserTypeId() {
		return userTypeId;
	}
	public void setUserTypeId(Long userTypeId) {
		this.userTypeId = userTypeId;
	}

	public String getUserType(){
		return userType;
	}
	public void setUserType(String userType){
		this.userType=userType;
	}

}

UserDetail.java


package com.spin.view;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table (name="USER_ACCOUNT")
public class UserDetail {

	@Id
	@Column(name="USER_SID", nullable=false)
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long userId;
	
	@JoinColumn(name="USER_SID",referencedColumnName="USER_TYPE_SID",insertable=false,updatable=false)
	@ManyToOne(fetch = FetchType.LAZY) // this column is foreign key , so addition Relationship
	private UserType userType;
	
	@Column(name="NAME", nullable=false)
	private String name;
	
	@Column(name="USERNAME", nullable=false)
	private String userName;
	
	@Column(name="PASSWORD", nullable=false)
	private String passWord;
	
	@Column(name="EMAIL_ID", nullable=true)
	private String emailId;
	
	@Column(name="OPRTNL_FLAG", nullable=true)
	private String oprnlFlag = "A";
	
	@Column(name="CREATED_BY", nullable=true)
	private Long createdBy;
	
	@Column(name="ACTIVE_CODE", nullable=false)
	private String activationCode = "SPINSOFT";

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public UserType getUserType() {
		return userType;
	}

	public void setUserType(UserType userType) {
		this.userType = userType;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassWord() {
		return passWord;
	}

	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

	public String getOprnlFlag() {
		return oprnlFlag;
	}

	public void setOprnlFlag(String oprnlFlag) {
		this.oprnlFlag = oprnlFlag;
	}

	public Long getCreatedBy() {
		return createdBy;
	}

	public void setCreatedBy(Long createdBy) {
		this.createdBy = createdBy;
	}

	public String getActivationCode() {
		return activationCode;
	}

	public void setActivationCode(String activationCode) {
		this.activationCode = activationCode;
	}

	@Override
	public String toString() {
		return "UserDetail [userId=" + userId + ", userType=" + userType + ", name=" + name + ", userName=" + userName
				+ ", passWord=" + passWord + ", emailId=" + emailId + ", oprnlFlag=" + oprnlFlag + ", createdBy="
				+ createdBy + ", activationCode=" + activationCode + "]";
	}

	

	
}

Hibernate JPA – CRUD

1. Create Table


CREATE TABLE USER_DETAIL ( USER_ID INTEGER PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(100) NOT NULL );

2. Create Entity Class


package com.sridhar.taskapp.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name="user_detail")
public class UserDetail {
 
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY ) //strategy=GenerationType.AUTO )
    @Column(name="USER_ID")
    private Long id;
     
    @Column(name="NAME", length=50 , nullable=false)
    private String name;
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
     
}

3. Create persistence.xml [ Save it in src/META-INF/persistence.xml ]


<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
    <persistence-unit name="TaskAppJPA"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.spinsoft.taskapp.view.UserDetail</class>
        <properties>
            <property name="javax.persistence.jdbc.driver"
                value="com.mysql.jdbc.Driver"></property>
            <property name="javax.persistence.jdbc.url"
                value="jdbc:mysql://localhost/spindb"></property>
            <property name="javax.persistence.jdbc.user" value="root"></property>
            <property name="javax.persistence.jdbc.password" value=""></property>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

4. Test Class:


package com.sridhar.taskapp.util;
 
import java.util.List;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
 
import com.spinsoft.taskapp.domain.UserDetail;
 
public class TestUserDetailDAO {
 
    public static void insert() {
 
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TaskAppJPA");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        UserDetail userDetail = new UserDetail();
        userDetail.setName("Siva");
        em.persist(userDetail);
        em.getTransaction().commit();
        em.close();
        emf.close();
 
    }
 
    public static void update(UserDetail userDetail) {
 
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TaskAppJPA");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.merge(userDetail);
        em.getTransaction().commit();
        em.close();
        emf.close();
 
    }
 
    public static void main(String[] args) {
 
        list();
        insert();
        list();
        UserDetail userDetail = findByName("Siva");
        userDetail.setName("Siva Kumar");
        update(userDetail);
        delete(userDetail.getId());
        list();
 
    }
 
    private static void list() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TaskAppJPA");
        EntityManager em = emf.createEntityManager();
        List<UserDetail> emps = em.createQuery("SELECT e FROM UserDetail e", UserDetail.class).getResultList();
        for (UserDetail e : emps) {
            System.out.println(e.getId() + ", " + e.getName());
        }
        em.close();
        emf.close();
    }
 
    public static UserDetail findById(Long id) {
 
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TaskAppJPA");
        EntityManager em = emf.createEntityManager();
        TypedQuery<UserDetail> query = em.createQuery("SELECT e FROM UserDetail e where id=?", UserDetail.class);
        query.setParameter(1, id);
        UserDetail userDetail = query.getSingleResult();
        em.close();
        emf.close();
 
        return userDetail;
 
    }
 
    public static UserDetail findByName(String name) {
 
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TaskAppJPA");
        EntityManager em = emf.createEntityManager();
        TypedQuery<UserDetail> query = em.createQuery("SELECT e FROM UserDetail e where name=?", UserDetail.class);
        query.setParameter(1, name);
        UserDetail userDetail = query.getSingleResult();
        em.close();
        emf.close();
 
        return userDetail;
 
    }
 
    public static UserDetail findOne(Long id) {
 
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TaskAppJPA");
        EntityManager em = emf.createEntityManager();
        UserDetail userDetail = em.find(UserDetail.class, id);
        return userDetail;
 
    }
 
    public static void delete(Long id) {
 
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TaskAppJPA");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        UserDetail userDetail = findOne(id);
        em.remove(em.merge(userDetail));
        em.getTransaction().commit();
        em.close();
        emf.close();
 
    }
 
}

Hibernate Validator

1. Create a domain class – User


package com.sridhar.taskapp;
 
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
 
public class User {
 
    private Long id;
 
    @Size(min = 3, max = 20)
    @NotNull(message = "Name cannot be null")
    private String name;
 
    @Pattern(regexp = ".+@.+\\.[a-z]+", message = "Invalid EmailId")
    private String email;
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", email=" + email + "]";
    }
 
}

2. Create a Test Class


package com.sridhar.taskapp;
 
import java.util.Set;
 
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
 
public class TestUser {
 
    public static void main(String[] args) {
 
        User user = new User();
 
        user.setId(1L);
        user.setName("abc");
        user.setEmail("Sridhar");
 
        System.out.println(user);
 
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
 
        Set<ConstraintViolation<User>> violations = validator.validate(user);
 
        for (ConstraintViolation<User> violation : violations) {
            String fieldName = violation.getPropertyPath().toString();
            String message = violation.getMessage();
 
            System.out.println( fieldName + " : " + message );
        }
 
    }
}

Insert using JDBCTemplate ( inject Datasource ) – @Repository Annotation

DAO.java


package com.sridhardao;
 
import javax.sql.DataSource;
 
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
@Repository("dao")
public class DAO {      
     
    private DataSource dataSource;
     
    private JdbcTemplate jdbcTemplate ;
     
    @Autowired
        public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
 
    public void save(){
         
               jdbcTemplate.update("INSERT INTO EMPLOYEE VALUES (?,?)" , 105, "Subash");    
         
    }
}

applicationContext.xml


<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans     
               http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
     
         <context:component-scan base-package="com.sridhar.dao" /> 
         <context:annotation-config/>
  
     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/testdb" />
        <property name="username" value="root" />
        <property name="password" value="pwd" />
    </bean>
     
   <!-- <bean id="dao" class="com.sridhar.dao.DAO">
         <property name="dataSource" ref="dataSource" /> 
    </bean> -->
    
</beans> 

Testing:


import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class TestEmployeeService {
 
    public static void main(String[] args) {
      
        AbstractApplicationContext  context = new ClassPathXmlApplicationContext("applicationContext.xml");
         
        DAO dao = (DAO)context.getBean("dao");
        dao.save();
        context.registerShutdownHook();
}
}

HTML – Text Formatting Elements

Tag

Description

<b> Defines bold text
<em> Defines emphasized text
<i> Defines italic text
<small> Defines smaller text
<strong> Defines important text
<sub> Defines subscripted text
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted text
<mark> Defines marked / highlighted text