Spring Jdbc Template Transaction Advice AOP Project

Click here to download eclipse supported ZIP file



This is MainApplication.java file having the source code to execute business logic.


 

    
package com.cv.spring.tx.advice;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cv.spring.tx.dao.StudentDao;
import com.cv.spring.tx.model.Student;


/**
 @author Chandra Vardhan
 */
public class MainApplication {
  
  private final static Logger LOGGER = Logger.getLogger(MainApplication.class);
  public static void main(String[] args) {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        "application-config.xml");

    StudentDao studentJDBCTemplate = (StudentDaoapplicationContext
        .getBean("studentJDBCTemplate");

    LOGGER.info("------Records creation--------");
    studentJDBCTemplate.create(216"cvardhan"11992010);
    studentJDBCTemplate.create(217"kodam"20972010);
    studentJDBCTemplate.create(218"netha"251002011);

    LOGGER.info("------Listing all the records--------");
    List<Student> studentMarks = studentJDBCTemplate.listStudents();
    for (Student record : studentMarks) {
      LOGGER.info("ID : " + record.getId());
      LOGGER.info(", Name : " + record.getName());
      LOGGER.info(", Marks : " + record.getMarks());
      LOGGER.info(", Year : " + record.getYear());
      LOGGER.info(", Age : " + record.getAge());
    }
  }
}


This is StudentMarksMapper.java file having the source code to execute business logic.


 

    
package com.cv.spring.tx.advice;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.cv.spring.tx.model.Student;


/**
 @author Chandra Vardhan
 */
public class StudentMarksMapper implements RowMapper<Student> {

  public Student mapRow(ResultSet rs, int rowNumthrows SQLException {
    Student studentMarks = new Student();
    studentMarks.setId(rs.getInt("id"));
    studentMarks.setName(rs.getString("name"));
    studentMarks.setAge(rs.getInt("age"));
    return studentMarks;
  }
}


This is StudentDao.java file having the DAO logic to access the database information.


 

    
package com.cv.spring.tx.dao;

import java.util.List;

import javax.sql.DataSource;

import com.cv.spring.tx.model.Student;


/**
 @author Chandra Vardhan
 */
public interface StudentDao {
  /**
   * This is the method to be used to initialize database resources ie.
   * connection.
   */
  public void setDataSource(DataSource ds);

  /**
   * This is the method to be used to create a record in the Student and Marks
   * tables.
   */
  public void create(int id,String name, Integer age, Integer marks, Integer year);

  /**
   * This is the method to be used to list down all the records from the
   * Student and Marks tables.
   */
  public List<Student> listStudents();
  
  
  public void test();
}


This is StudentDaoImpl.java file having the DAO logic to access the database information.


 

    
package com.cv.spring.tx.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import com.cv.spring.tx.advice.StudentMarksMapper;
import com.cv.spring.tx.model.Student;


/**
 @author Chandra Vardhan
 */
public class StudentDaoImpl implements StudentDao {
  
  private final static Logger LOGGER = Logger.getLogger(StudentDaoImpl.class);

  private JdbcTemplate jdbcTemplateObject;

  public void setDataSource(DataSource dataSource) {
    this.jdbcTemplateObject = new JdbcTemplate(dataSource);
  }

  public void create(int id, String name, Integer age, Integer marks,
      Integer year) {
    Connection conn = null;
    DataSource dataSource = jdbcTemplateObject.getDataSource();
    try {
      conn = dataSource.getConnection();
      conn.setAutoCommit(true);
      Statement createStatement = conn.createStatement();
      tableCreate(createStatement);
      String SQL2 = "insert into Student (id,name,age) values (" + id
          ",'" + name + "','" + age + "')";
      createStatement.executeUpdate(SQL2);
      // jdbcTemplateObject.update(SQL2, id, name, age);

      // Get the latest student id to be used in Marks table

      String SQL3 = "select max(ID) from Student";

      /*
       * List<Student> list = jdbcTemplateObject.query(SQL3, new
       * StudentMarksMapper());
       */
      ResultSet rs = createStatement.executeQuery(SQL3);
      int sid = 0;
      while (rs.next()) {
        sid = rs.getInt(1);
      }
      /*
       * if (list != null && list.size() > 0) { Student s = list.get(0);
       * sid = s.getId(); }
       */

      /*
       * String SQL4 = "insert into Marks(sid, marks, year) " +
       * "values (?, ?, ?)"; jdbcTemplateObject.update(SQL4, sid, marks,
       * year);
       */
      String SQL4 = "insert into Marks(sid, marks, year)  values (" + sid
          "," + marks + "," + year + ")";

      createStatement.executeUpdate(SQL4);
      LOGGER.info("Created Name = " + name + ", Age = " + age);
      // to simulate the exception.
      // throw new RuntimeException("simulate Error condition");

    catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    catch (DataAccessException e) {
      LOGGER.info("Error in creating record, rolling back");
      throw e;
    }
  }

  private void tableCreate(Statement createStatement) {
    String createStudent = "CREATE TABLE STUDENT(ID INT, NAME VARCHAR(20),AGE INT,PRIMARY KEY(ID));";
    String createMarks = "CREATE TABLE MARKS(SID INT, MARKS INT, YEAR INT, ID INT references STUDENT(ID));";
    try {
      String query = "SELECT count(*) FROM MARKS";
      ResultSet rs = createStatement.executeQuery(query);
    catch (Exception e) {
      try {
        createStatement.executeUpdate(createStudent);
        createStatement.executeUpdate(createMarks);
      catch (SQLException e1) {
        e1.printStackTrace();
      }

    }

  }

  public List<Student> listStudents() {
    String SQL = "select * from Student, Marks where Student.id=Marks.sid";

    List<Student> studentMarks = jdbcTemplateObject.query(SQL,
        new StudentMarksMapper());
    return studentMarks;
  }

  public void test() {
    LOGGER.info("test method executed........");
  }
}


This is Student.java file having the source code to execute business logic.


 

    
package com.cv.spring.tx.model;


/**
 @author Chandra Vardhan
 */
public class Student {
  private Integer id;
  private String name;
  private Integer age;
  private Integer marks;
  private Integer year;

  public void setAge(Integer age) {
    this.age = age;
  }

  public Integer getAge() {
    return age;
  }

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

  public String getName() {
    return name;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public Integer getId() {
    return id;
  }

  public void setMarks(Integer marks) {
    this.marks = marks;
  }

  public Integer getMarks() {
    return marks;
  }

  public void setYear(Integer year) {
    this.year = year;
  }

  public Integer getYear() {
    return year;
  }

  
}




This is pom.xml file having the entries of dependency jars and information to build the application .


	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.spring.tx</groupId> <artifactId>SpringJdbcTemplateTransactionAdviceAOP</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>SpringJdbcTemplateTransactionAdviceAOP</name> <properties> <springframework.version>4.2.0.RELEASE</springframework.version> </properties> <dependencies> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.5.3</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <artifactId>hibernate-core</artifactId> <groupId>org.hibernate</groupId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.2.0.Final</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.2-1003-jdbc4</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </pluginManagement> </build> </project>


This is application-config.xml file having the spring configuration properties.


 
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/database.properties" />
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${database.driverClassName}"
p:url="${database.databaseurl}" p:username="${database.username}" p:password="${database.password}" />
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${database.driverClassName}"
p:url="${database.databaseurl}" p:username="${database.username}" p:password="${database.password}" />

<!--
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driverClassName}" />
<property name="url" value="${database.databaseurl}" />
<property name="username" value="postgres" />
<property name="password" value="password" />
</bean> -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="create" propagation="REQUIRED" isolation="DEFAULT" read-only="false" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="createOperation"
expression="execution(* com.cv.spring.tx.dao.StudentDaoImpl.create(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="createOperation" />
</aop:config>

<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<bean id="studentJDBCTemplate" class="com.cv.spring.tx.dao.StudentDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>



This is log4j.properties file having the entries for logging the information into the console/file.



#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


No comments:

Post a Comment