Showing posts with label Spring Framework. Show all posts
Showing posts with label Spring Framework. Show all posts

Sunday, June 30, 2019

Spring JdbcTemplate

PreparedStatement
RowMapper
ResultSetExtractor
NamedParameter
BeanPropertyRowMapper

ResultSetExtractor: 
  • org.springframework.jdbc.core.ResultSetExtractor is a callback interface.
  • This is used to extracting results from a ResultSet. 
  • ResultSetExtractor is used if we required.one result object for the entire ResultSet.
RowMapper: 
  • org.springframework.jdbc.core.RowMapper<T> is a interface.
  • This is used by JdbcTemplate to map each row of a ResultSet to a result object "per-row basis".
  • A RowMapper is use to process ResultSet, mapping one result object per row.

new Object[] { empId }: passing the id as a parameter to the query
new BeanPropertyRowMapper<Employee>(Employee.class): BeanPropertyRowMapper is use to map the results from ResultSet to the Employee bean.


Related Tutorial

Thursday, May 9, 2019

Spring DataSource JNDI with Tomcat Example

 Step - 1:  Create database in MySQL
create database myExampleDB
 
use myExampleDB
 
CREATE TABLE `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `firstName` varchar(45) NOT NULL,
  `lastName` varchar(45) NOT NULL,
  `username` varchar(45) NOT NULL,
  `password` varchar(45) NOT NULL,
  `email` varchar(45) NOT NULL,
  PRIMARY KEY (`user_id`)
);

 Step -2:  Go to Configuring context of tomcat -- inside $CATALINA_BASE/conf/context.xml
To create JNDI DataSource in tomcat for  MySQL database,  create a Resource XML element as given below.
<Resource
    name="jdbc/myExampleDB"
    auth="Container"
    type="javax.sql.DataSource"
    maxActive="200"
    maxIdle="30"
    maxWait="10000"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/myExampleDB"
    username="root"
    password="root"
    />

Add the above code inside the root element <Context> in a context.xml file. Apache Tomcat provide three ways to configure DataSource in JNDI context.


Application (in /META-INF directory of a web application) context.xml : the JNDI DataSource is only available for the application itself, thus this will not be shared among other applications. In addition, this configuration is dependent on the application.

Server context.xml (in $CATALINA_BASE/conf directory): In tomacte this is the preferred place because where we can create JNDI DataSource. it will be available for all web applications and it is independent of any applications. The scope of server context.xml file is application. So if we define a DataSource connection pool size of 100 connections and we have 20 applications then the datasource will be created for each of the application. This will result in 2000 connections that will obviously consume all the database server resources and hurt application performance.

server.xml and context.xml : We should define DataSource at global level by defining here in the server.xml   GlobalNamingResources  element. If we use this approach, then we need to define a   ResourceLink    from context.xml file of server or application specific. This is the preferred way while we are looking to share a common resource pool across multiple applications running on the server. Regarding resource link, whether to define it at server level context xml file or application level depends on your requirement.

<Resource name="jdbc/myExampleDB
      global="jdbc/myExampleDB
      auth="Container" 
      type="javax.sql.DataSource" 
      driverClassName="com.mysql.jdbc.Driver" 
      url="jdbc:mysql://localhost:3306/myExampleDB
      username="root" 
      password="root" 
      
      maxActive="100" 
      maxIdle="20" 
      minIdle="5" 
      maxWait="10000"/>

Tomcat DataSource JNDI Resource Link Configuration – context.xml
Add below code in the server context.xml file.

<ResourceLink name="jdbc/myExampleDB"
                global="jdbc/myExampleDB"
                auth="Container"
                type="javax.sql.DataSource" />

The following table describes the attributes specified in the above configuration:
Attribute name
Description
  name   Name of the resource example  "jdbc/myExampleDB"
  auth   Specify authentication mechanism for the application code, can be Application or Container.
  type   The fully qualified name of Java class expected by the web application when it performs a lookup for this resource.
  Example "javax.sql.DataSource"
  maxActive   Max number of active database connections required in pool.
  We can set to -1 for no limit.
  maxIdle   Max number of idle database connections to retain in pool.
  We can set to -1 for no limit.
  maxWait   Maximum waiting time for a database connection to become available in ms. example 10 seconds in my my example. If database not connected in 10 seconds.  if this timeout is exceeded an Exception is thrown.
We can set to -1 to wait indefinitely. But we must set some time in this.
  driverClassName   The fully qualified name of Java class the database driver.
  Example like MySQL Connector/J, it is "com.mysql.jdbc.Driver".
  url   Connection URL for JDBC as we provide while connect with database in any application.
  Example "jdbc:mysql://localhost:3306/myExampleDB".
  username   UserName of database for which we have to connect.
  As we are using MySQL database. 
  password   Password of databse for which we have to connect.
  As we are using MySQL database.

Wednesday, April 24, 2019

Create Custom AOP

Q- How to create custom AOP in java ?



AbstractHandler.java
package com.shubh.example.aop;
import java.lang.reflect.InvocationHandler;

public abstract class AbstractHandler implements InvocationHandler {

 /** The target object. */

 private Object targetObject;

 /**
  * Sets the target object.
  * @param targetObject
  *  the new target object
  */
 public void setTargetObject(Object targetObject) {
  this.targetObject = targetObject;
 }

 /**
  * Gets the target object.
  * @return the target object
  */
 public Object getTargetObject() {
  return targetObject;
 }

}

AfterHandler.java

package com.shubh.example.aop;
import java.lang.reflect.Method;

public abstract class AfterHandler extends AbstractHandler {

 /**
  * Handles after the execution of method.
  * @param proxy the proxy
  * @param method the method
  * @param args the args
  */
 public abstract void afterHandle(Object proxy, Method method, Object[] args);

 /*
  * (non-Javadoc)
  * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object,
  * java.lang.reflect.Method, java.lang.Object[])
  */
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  Object result = method.invoke(getTargetObject(), args);
  afterHandle(proxy, method, args);
  return result;

 }

}

BeforeHandler.java

package com.shubh.example.aop;
import java.lang.reflect.Method;

public abstract class BeforeHandler extends AbstractHandler {

 /**
  * Handles before execution of actual method.
  * @param proxy the proxy
  * @param method the method
  * @param args the args
  */
 public abstract void beforeHandle(Object proxy, Method method, Object[] args);

 /*
  * (non-Javadoc)
  * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object,
  * java.lang.reflect.Method, java.lang.Object[])
  */
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  beforeHandle(proxy, method, args);
  return method.invoke(getTargetObject(), args);
 }
}


ProxyFactory.java 

package com.shubh.example.aop;
import java.lang.reflect.Proxy;
import java.util.List;
public class ProxyFactory {

 /**
  * Gets the proxy.
  * @param targetObject the target object
  * @param handlers  the handlers
  * @return the proxy
  */
 public static Object getProxy(Object targetObject, List<AbstractHandler> handlers) {
  Object proxyObject = null;
  if (handlers.size() > 0) {
   proxyObject = targetObject;
   for (int i = 0; i < handlers.size(); i++) {
    handlers.get(i).setTargetObject(proxyObject);
    proxyObject = Proxy.newProxyInstance(targetObject.getClass()
      .getClassLoader(),
      targetObject.getClass().getInterfaces(),
      handlers.get(i));
   }
   return proxyObject;
  } else {
   return targetObject;
  }
 }
}

AfterHandlerImpl.java

package com.shubh.example.aop.impl;
import java.lang.reflect.Method;
import com.shubh.example.aop.AfterHandler;

public class AfterHandlerImpl extends AfterHandler {

 @Override
 public void afterHandle(Object proxy, Method method, Object[] args) {
  System.out.println("Handling after actual method execution ........");
  System.out.println("Inside afterHandle - Method Name : " + method.getName());
  for (Object obj : args) {
   System.out.println("Inside afterHandle - Method argument : " + obj.toString());
  }
 }
}

BeforeHandlerImpl.java

package com.shubh.example.aop.impl;
import java.lang.reflect.Method;
import com.shubh.example.aop.BeforeHandler;

public class BeforeHandlerImpl extends BeforeHandler {

 /*
  * (non-Javadoc)
  * beforeHandle(java.lang.Object, java.lang.reflect.Method,
  * java.lang.Object[])
  */
 @Override
 public void beforeHandle(Object proxy, Method method, Object[] args) {
  System.out.println("Handling before actual method call ........");
  for (Object obj : args) {
   System.out.println("Inside beforeHandle - Method argument : " + obj.toString());
  }
 }
}
 
Calculator.java

package com.shubh.example.beans;

public interface Calculator {
 /**
  * Calculate.
  * @param a int a
  * @param b  int b
  * @return the int
  */
 public int calculate(int a, int b);
}
 
CalculatorImpl.java 
package com.shubh.example.beans;

public class CalculatorImpl implements Calculator {

 public int calculate(int a, int b) {
  System.out.println("**********Actual Method Call : CalculatorImpl **********");
  int sum = a + b;
  return sum;
 }
}

DynamicAopMain.java

package com.shubh.example.aop.app;
import java.util.ArrayList;
import java.util.List;
import com.shubh.example.aop.AbstractHandler;
import com.shubh.example.aop.AfterHandler;
import com.shubh.example.aop.BeforeHandler;
import com.shubh.example.aop.ProxyFactory;
import com.shubh.example.aop.impl.AfterHandlerImpl;
import com.shubh.example.aop.impl.BeforeHandlerImpl;
import com.shubh.example.beans.Calculator;
import com.shubh.example.beans.CalculatorImpl;

public class DynamicAopMain {

 public static void main(String[] args) {
  CalculatorImpl calcImpl = new CalculatorImpl();
  BeforeHandler before = new BeforeHandlerImpl();
  AfterHandler after = new AfterHandlerImpl();

  List handlers = new ArrayList();
  handlers.add(before);
  handlers.add(after);

  Calculator proxy = (Calculator) ProxyFactory.getProxy(calcImpl, handlers);
  int result = proxy.calculate(20, 10);
  System.out.println("FInal Result :::" + result);
 }
}










Tuesday, April 9, 2019

Spring Framework Annotations

Core Spring Framework Annotations

  • @Required
  • @Autowired
  • @Qualifier
  • @Bean
  • @Lazy
  • @Value


Spring Framework Stereotype Annotations

  • @Component
  • @Controller
  • @Repository
  • @Service


Spring Boot Annotations

  • @EnableAutoConfiguration
  • @SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan

Spring MVC and REST Annotations

  • @Controller
  • @RequestMapping
  • @CookieValue
  • @CrossOrigin


Composed @RequestMapping Variants

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @PatchMapping
  • @DeleteMapping
  • @ExceptionHandler
  • @InitBinder
  • @Mappings and @Mapping
  • @MatrixVariable
  • @PathVariable
  • @RequestAttribute
  • @RequestBody
  • @RequestHeader
  • @RequestParam
  • @RequestPart
  • @ResponseBody
  • @ResponseStatus
  • @ControllerAdvice
  • @RestController = @Controller + @ResponseBody
  • @RestControllerAdvice = @ControllerAdvice + @ResponseBody
  • @SessionAttribute
  • @SessionAttributes

Spring Cloud Annotations

  • @EnableConfigServer
  • @EnableEurekaServer
  • @EnableDiscoveryClient
  • @EnableCircuitBreaker
  • @HystrixCommand



Spring Framework DataAccess Annotations

  • @Transactional

Cache-Based Annotations
  • @Cacheable : To add data into cache
  • @CachePut : To update data into cache while update into database
  • @CacheEvict : To delete data from cache while deleting from database
  • @CacheConfig : To configure cache

Task Execution and Scheduling Annotations

  • @Scheduled
  • @Async

Spring Framework Testing Annotations

  • @BootstrapWith
  • @ContextConfiguration
  • @WebAppConfiguration
  • @Timed
  • @Repeat
  • @Commit
  • @RollBack
  • @DirtiesContext
  • @BeforeTransaction
  • @AfterTransaction
  • @Sql
  • @SqlConfig
  • @SqlGroup
  • @SpringBootTest
  • @DataJpaTest
  • @DataMongoTest : To embedded MongoDB for running integration tests with Spring Data MongoDB.
  • @WebMVCTest
  • @AutoConfigureMockMVC
  • @MockBean
  • @JsonTest
  • @TestPropertySource