Quick Refresh : Spring : AOP, JDBC Template, Exception Handling

Aspect oriented programming (AOP): Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. There are various common good examples of aspects like logging, auditing, declarative transactions, security, caching, etc. 

Aspect: An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, you can create a logging aspect and apply it throughout your application using AOP.

Jointpoint: A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.

Advice: Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is inserted into an application at joinpoints.

Pointcut: A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. 

Target: A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to any advice that is being applied.

Proxy: A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same.

Weaving: The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven into the target object at the specified joinpoints.

What are the different points where weaving can be applied?
  • Compile Time
  • Classload Time
  • Runtime
What are the different advice types in spring?
  • Around (org.aopalliance.intercept.MethodInterceptor): Intercepts the calls to the target method 
  • Before (org.springframework.aop.BeforeAdvice) : This is called before the target method is invoked
  • After (org.springframework.aop.AfterReturningAdvice) : This is called after the target method is returned
  • Throws (org.springframework.aop.ThrowsAdvice) : This is called when the target method throws and exception
Types of AutoProxying:
  • BeanNameAutoProxyCreator
  • DefaultAdvisorAutoProxyCreator
  • Metadata autoproxying
Spring Exceptions:
The spring’s DAO class does not throw any technology related exceptions such as SQLException. They throw exceptions which are subclasses of org.springframework.dao.DataAccessException.
DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is not forced to handle these kinds of exceptions.

Configure a bean to get DataSource from JNDI:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
      <value>java:comp/env/jdbc/myDatasource</value>
    </property>
</bean>

Spring - JDBC Template:
Spring JDBC Framework takes care of all the low-level details starting from opening the connection, prepare and execute the SQL statement, process exceptions, handle transactions and finally close the connection.

JdbcTemplate Class: The JDBC Template class executes SQL queries, updates statements, stores procedure calls, performs iteration over ResultSets, and extracts returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package.

Instances of the JdbcTemplate class are threadsafe once configured. So you can configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs.

A common practice when using the JDBC Template class is to configure a DataSource in your Spring configuration file, and then dependency-inject that shared DataSource bean into your DAO classes, and the JdbcTemplate is created in the setter for the DataSource.

<bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
      <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
      <property name = "username" value = "root"/>
      <property name = "password" value = "password"/>
   </bean>

   <!-- Definition for studentJDBCTemplate bean -->
   <bean id = "studentJDBCTemplate"  class = "com.dj.StudentJDBCTemplate">
      <property name = "dataSource" ref = "dataSource" />  
   </bean>

There are other approaches to access the database where you will use NamedParameterJdbcTemplate and SimpleJdbcTemplate classes

Executing SQL statements
Let us see how we can perform CRUD (Create, Read, Update and Delete) operation on database tables using SQL and JDBC Template object.
  • Querying for an integer
String SQL = "select count(*) from Student";
int rowCount = jdbcTemplateObject.queryForInt( SQL );
  • Querying for a long
String SQL = "select count(*) from Student";
long rowCount = jdbcTemplateObject.queryForLong( SQL );
  • A simple query using a bind variable
String SQL = "select age from Student where id = ?";
int age = jdbcTemplateObject.queryForInt(SQL, new Object[]{10});
  • Querying for a String
String SQL = "select name from Student where id = ?";
String name = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, String.class);
  • Querying and returning an object
String SQL = "select * from Student where id = ?";
Student student = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, new StudentMapper());

public class StudentMapper implements RowMapper<Student> {
   public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
      Student student = new Student();
      student.setID(rs.getInt("id"));
      student.setName(rs.getString("name"));
      student.setAge(rs.getInt("age"));
      
      return student;
   }
}
  • Querying and returning multiple objects
String SQL = "select * from Student";
List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());

public class StudentMapper implements RowMapper<Student> {
   public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
      Student student = new Student();
      student.setID(rs.getInt("id"));
      student.setName(rs.getString("name"));
      student.setAge(rs.getInt("age"));
      
      return student;
   }
}
  • Inserting a row into the table
String SQL = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL, new Object[]{"Zara", 11} );
  • Updating a row into the table
String SQL = "update Student set name = ? where id = ?";
jdbcTemplateObject.update( SQL, new Object[]{"Zara", 10} );
  • Deleting a row from the table
String SQL = "delete Student where id = ?";
jdbcTemplateObject.update( SQL, new Object[]{20} );
  • Executing DDL Statements
You can use the execute(..) method from jdbcTemplate to execute any SQL statements or DDL statements. Following is an example to use CREATE statement to create a table −

String SQL = "CREATE TABLE Student( ID   INT NOT NULL AUTO_INCREMENT, " +
   "NAME VARCHAR(20) NOT NULL, AGE  INT NOT NULL, PRIMARY KEY (ID));";


jdbcTemplateObject.execute( SQL );


SQL Stored Procedure in Spring:
The SimpleJdbcCall class can be used to call a stored procedure with IN and OUT parameters. You can use this approach while working with either of the RDBMS. creating an SqlParameterSource containing the IN parameter. It's important to match the name provided for the input value with that of the parameter name declared in the stored procedure. The execute method takes the IN parameters and returns a Map containing any out parameters keyed by the name as specified in the stored procedure.

SimpleJdbcCall jdbcCall;
jdbcCall =  new SimpleJdbcCall(dataSource).withProcedureName("getRecord");

SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id);

      Map<String, Object> out = jdbcCall.execute(in);

How do you write data to backend in spring using JdbcTemplate?
The JdbcTemplate uses several of these callbacks when writing data to the database. The usefulness you will find in each of these interfaces will vary. There are two simple interfaces. One is PreparedStatementCreator and the other interface is BatchPreparedStatementSetter.
  • PreparedStatementCreator: is one of the most common used interfaces for writing data to database. The interface has one method createPreparedStatement().When this interface is implemented, we should create and return a PreparedStatement from the Connection argument, and the exception handling is automatically taken care off. When this interface is implemented, another interface SqlProvider is also implemented which has a method called getSql() which is used to provide sql strings to JdbcTemplate.
  • BatchPreparedStatementSetter: If the user what to update more than one row at a shot then he can go for BatchPreparedStatementSetter. This interface provides two methods
    • setValues(PreparedStatement ps, int i) throws SQLException;
    • int getBatchSize();
The getBatchSize() tells the JdbcTemplate class how many statements to create. And this also determines how many times setValues() will be called.

What are the differences between EJB and Spring ?
FeatureEJBSpring
Transaction management
  • Must use a JTA transaction manager.
  • Supports transactions that span remote method calls.
  • Supports multiple transaction environments through itsPlatformTransactionManager interface, including JTA, Hibernate, JDO, and JDBC.
  • Does not natively support distributed transactions—it must be used with a JTA transaction manager.
Declarative transaction support
  • Can define transactions declaratively through the deployment descriptor.
  • Can define transaction behavior per method or per class by using the wildcard character *.
  • Cannot declaratively define rollback behavior—this must be done programmatically.
  • Can define transactions declaratively through the Spring configuration file or through class metadata.
  • Can define which methods to apply transaction behavior explicitly or by using regular expressions.
  • Can declaratively define rollback behavior per method and per exception type.
PersistenceSupports programmatic bean-managed persistence and declarative container managed persistence.Provides a framework for integrating with several persistence technologies, including JDBC, Hibernate, JDO, and iBATIS.
Declarative security
  • Supports declarative security through users and roles. The management and implementation of users and roles is container specific.
  • Declarative security is configured in the deployment descriptor.
  • No security implementation out-of-the box.
  • Acegi, an open source security framework built on top of Spring, provides declarative security through the Spring configuration file or class metadata.
Distributed computingProvides container-managed remote method calls.Provides proxying for remote calls via RMI, JAX-RPC, and web services.

Comments

Popular posts from this blog

Ramoji Film City, Hyderabad, India

Ashtavinayak Temples | 8 Ganpati Temples of Maharashtra | Details Travel Reviews

Quick Refresh : Hibernate