Thursday, January 12, 2017






Enterprise Feedback Management System





Techncal Manager Roles and Responsibilites

In Agile Development, The role of Technical Manager should be equally divided across below 6 steps which will helps us in delivering better products. Recently I moved from Architecture to Technical Manager role and I am evaluating different frameworks for efficient project delivery and below framework is very promising.

Generally, I spend 30% work on Strategy, 50% work on design & develiopment and remaining on coordination and team management


Discover
1.     Understand Management’s Brand Customer Experience Strategy.
2.      “What is the end in mind?”
3.      What are the frontline Non-Negotiables or the KPI’s?
4.      Training Collateral.
5.      Reporting Needs.
Define
6.     Scenario Library or theater?
7.      Key Performance Indicators?
8.      What are the “Important Business Metrics”?
9.      What are the short term and long term Objectives?
10.   Goals to reach.
11.   Report Distribution.
12.   Targets to evaluate.
13.   What are the Cause & Effect Linkage to business metrics?
14.   Budget?
Design
15.  CBA Demographics, DB Design.
16.   Collateral Documents including Guidelines, Certification, Questionnaire.
17.   Reporting.
18.   Customized Conditional Alerts that push reports based in your defined business rules.
19.   Business Metrics to be hosted.
Develop
20.  Brand Agent Certification Exam for knowledge transfer
21.   Project Plan and Timeline.
22.   Interventions to be used.
23.   Custom Data Base Programming.
Deploy
24.  Launch Field Work.
25.   On Line Data Capture.
26.   Real time Reporting Platform.
Deliver
27.  Benchmark.
28.   Execute.

29.   Demonstrate Internal ROI Using “Cause and Effect” Linkage to Real Business Metrics

Wednesday, December 28, 2016

Configuring Hikari with spring boot framework without JPA but use jDBC template


Configuring Hikari with spring boot framework




The goal is to implement Hikari data source with spring boot default data source configuration but disable spring data  JPA and use spring JDBC templates for more control and faster queries

PostgreSQL does throw errors when we initialize spring boot Hikari with driver name. We had used pgsimpledatasoruce and configured data source properties for it.


applicaiton.propertiles file 

#spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.dataSourceClassName=org.postgresql.ds.PGSimpleDataSource
spring.datasource.dataSourceProperties.databaseName=app_dev
spring.datasource.dataSourceProperties.serverName=app-dev.xxxxxx.xx.rds.amazonaws.com
spring.datasource.dataSourceProperties.portNumber=5432
spring.datasource.minimumIdle=2
spring.datasource.maximumPoolSize=50
spring.datasource.idleTimeout=5000
spring.datasource.username=admin
spring.datasource.password=xxxxx
spring.datasource.hikari.connection-init-sql=ALTER USER admin SET search_path to default_schema_name
spring.datasource.hikari.connection-test-query=selectcount(*)from table
spring.datasource.hikari.driver-class-name=org.postgresql.Driver
spring.datasource.initialize=true
spring.datasource.continueOnError=true


connection log

2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  dataSourceProperties............{password=<masked>, portNumber=5432, databaseName=app_dev, serverName=app-dev.xxxxxx.xx.rds.amazonaws.com}
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  driverClassName.................null
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  healthCheckProperties...........{}
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  healthCheckRegistry.............null
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  idleTimeout.....................600000
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  initializationFailFast..........true
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  isolateInternalQueries..........false
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  jdbc4ConnectionTest.............false
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  jdbcUrl.........................null
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  leakDetectionThreshold..........0
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  maxLifetime.....................1800000
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  maximumPoolSize.................50
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  metricRegistry..................null
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  metricsTrackerFactory...........null
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  minimumIdle.....................2
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  password........................<masked>
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  poolName........................"HikariPool-1"
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  readOnly........................false
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  registerMbeans..................false
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  scheduledExecutorService........null
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  threadFactory...................null
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  transactionIsolation............null
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  username........................"admin"
2016-12-27 14:31:04,663 [http-nio-8080-exec-1] DEBUG c.z.h.HikariConfig -  validationTimeout...............5000


 after some time

2016-12-28 17:19:32,853 [HikariPool-1 housekeeper] DEBUG c.z.h.p.HikariPool -  HikariPool-1 - Pool stats (total=2, active=0, idle=2, waiting=0)
2016-12-28 17:20:02,854 [HikariPool-1 housekeeper] DEBUG c.z.h.p.HikariPool -  HikariPool-1 - Pool stats (total=2, active=0, idle=2, waiting=0)
2016-12-28 17:20:32,855 [HikariPool-1 housekeeper] DEBUG c.z.h.p.HikariPool -  HikariPool-1 - Pool stats (total=2, active=0, idle=2, waiting=0)



spring boot app class


package com.frazed.programming;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.frazed.programming")
@EnableAutoConfiguration
public class myApplication{

   public static void main(String[] args) {
      SpringApplication.run(myApplication.class, args);
   }


}


selvletInitializer as we are deploying springboot as war on tomcat


package com.frazed.programming;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(myApplication.class);
      }
      }


pom file


<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.frazed.programming.App</groupId>
    <artifactId>myApp2s</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>myApp2s</name>
    <description>myApp project for Spring Boo with Hikari and Spring JDBC</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <slf4j.version>1.7.22</slf4j.version>
        <logback.version>1.1.8</logback.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator-docs</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-mockmvc</artifactId>
            <scope>test</scope>
        </dependency>   

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>


        <!--everyone gets logging-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>${logback.version}</version>
        </dependency>

        <!--this is used for logback to do conditional processing-->
        <dependency>
            <groupId>org.codehaus.janino</groupId>
            <artifactId>janino</artifactId>
            <version>2.7.8</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


--
appConfig

package com.frazed.programming;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan
@EnableTransactionManagement
@PropertySource(value = { "classpath:application.properties" })

/*

SpringBoot uses spring.datasource.initialize property value, which is true by default,
to determine whether to initialize database or not. If you want to turn off the database
initialization you can set spring.datasource.initialize=false

 */

public class AppConfig 
{
    @Autowired
    private Environment env;


    @Bean
    public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer()
    {
        return new PropertySourcesPlaceholderConfigurer();
    }

 @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource)
    {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }

    


    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }


}


JUnit test case for crud operations

package com.frazed.programming.dao;

import com.frazed.programming.AppDevApplication;
import com.frazed.programming.data.dao.EntityDao;
import com.frazed.programming.data.domain.Entity;
import com.frazed.programming.data.mapper.EntityMapper;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

/**
 * Created   
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AppDevApplication.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class EntityDaoTest {

    private static final Logger logger = LoggerFactory.getLogger(EntityDaoTest.class);
    static Entity entity = new Entity();
    //static int pk = RandomNumberGenerator.getRandomNumberInRange(888, 999);
    static int pk = 999;
    static int intialCount;


    @Autowired
    EntityDao entityDao = new EntityDao();

 @Autowired
 private JdbcTemplate jdbcTemplate;





    @Test
 public void aTest() throws Exception {


     List<Entity> retval = new ArrayList<>();
     try {
         String SQL = "select * from entity_table";
         retval = jdbcTemplate.query(SQL, new EntityMapper());

         logger.debug(retval.size()+"");
         Assert.assertNotNull(retval.size());


     } catch (Exception e) {
         logger.error(e.getMessage(), e);
         throw new RuntimeException(e);
     }
 }




@Test
 public void aMigrate() throws Exception {


        List<Entity> retval = new ArrayList<>();

            try {
                String SQL = "select * from sample_table";
                 retval = jdbcTemplate.query(SQL, new EntityMapper());
                logger.debug(retval.size()+"");

            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new RuntimeException(e);
            }


        logger.debug(retval.size() +","+entityDao.findAll().size());

     Assert.assertEquals(retval.size(),entityDao.findAll().size());
 }


    @Test
    public void aCount() throws Exception {

//        entityDao = new EntityDao();
//        entityDao.init();
        // first delete test record...
        intialCount = entityDao.count();

        if (intialCount > 0) {

            logger.debug("count of records " + intialCount);
        }

        Assert.assertEquals(intialCount, intialCount);


    }

    @Test
    public void aSave() throws Exception {

//        entityDao = new EntityDao();
//        entityDao.init();
        // first delete test record...
        int retval = entityDao.delete(pk);

        entity.setentity_code(State.NEW_JERSEY.getANSIabbreviation());
        entity.setEntity(pk);
        entity.setentity_name("HYDERABAD");


        int retVal = entityDao.save(entity);
        if (retVal > 0) {

            logger.debug("inserted record " + retVal);
        }

        Assert.assertEquals(1, retVal);


    }


    @Test
    public void bfindAll() throws Exception {

        //entityDao = new EntityDao();
        // entityDao.init();
        List retList = entityDao.findAll();

        int retVal = entityDao.count();
        Assert.assertEquals(retList.size(), retVal);
        logger.debug(retList.size() + " findAll size == count " + retVal);
        if (!(null == retList || retList.size() == 0)) {
            Entity lastObj = (Entity) retList.get(retList.size() - 1);
            pk = lastObj.getEntity();
            entity = lastObj;
            logger.debug("last inserted record id " + pk);

        }
    }

    @Test
    public void cfindOne() throws Exception {
        Entity findObj = entityDao.findOne(pk);
        Assert.assertEquals(pk, (int) findObj.getEntity());
        entity = findObj;
        logger.debug("Found  Record with pk " + pk);
    }

    @Test
    public void dupdate() throws Exception {
        logger.debug("  update Record with pk " + pk);

        entity.setentity_name("Miami");
        int retval = entityDao.update(entity);
        Assert.assertEquals(1, retval);
        logger.debug("Updated  Record with CreatedId " + pk);


    }

    @Test
    public void edelete() throws Exception {
        int retval = entityDao.delete(pk);
        Assert.assertEquals(1, retval);

        logger.debug("deleted Record with CreatedId " + pk);


    }

    @Test
    public void zCount() throws Exception {

//        entityDao = new EntityDao();
//        entityDao.init();
        // first delete test record...
        int retVal = entityDao.count();

        if (retVal > 0) {

            logger.debug("count of records after crud operations " + retVal);
        }

        Assert.assertEquals(intialCount, retVal);


    }


}


---




entity rest controller

package com.frazed.programming.web;

import com.frazed.programming.data.domain.Entity;
import com.frazed.programming.service.EntityService;
import com.frazed.programming.utils.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created on
 */
@RestController
@RequestMapping("/Entity")
public class EntityController {


    private static final Logger LOGGER = LoggerFactory.getLogger(EntityController.class);

    @Autowired
    EntityService EntityService;


    @RequestMapping(value = "/add/{Entity}/state/{statecode}/city/{city}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)

    public ResponseEntity save(@PathVariable(value = "Entity") String Entity,
                               @PathVariable("statecode") String statecode,
                               @PathVariable("city") String city, HttpServletRequest request, HttpServletResponse response) {
        Integer EntityInt = null;
        try {
            EntityInt = new Integer(Entity);
            boolean retVal = EntityService.save(new Entity(EntityInt, statecode, city));
            return new ResponseEntity<Boolean>(retVal, null, HttpStatus.CREATED);

        } catch (NumberFormatException e1) {
            return ExceptionUtil.getNumberFormatExceptionResponseEntity(request, e1);

        } catch (Exception e1) {

            return ExceptionUtil.getInternalErrorResponseEntity(request, e1);


        }


    }

    @RequestMapping(value = "/update/{Entity}/state/{statecode}/city/{city}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity update(@PathVariable(value = "Entity") String Entity,
                                 @PathVariable("statecode") String statecode,
                                 @PathVariable("city") String city, HttpServletRequest request, HttpServletResponse response) {


        Integer EntityInt = null;
        try {
            EntityInt = new Integer(Entity);
            boolean retVal = EntityService.update(new Entity(EntityInt, statecode, city));
            return new ResponseEntity<Boolean>(retVal, null, HttpStatus.CREATED);


        } catch (NumberFormatException e1) {
            return ExceptionUtil.getNumberFormatExceptionResponseEntity(request, e1);

        } catch (Exception e1) {

            return ExceptionUtil.getInternalErrorResponseEntity(request, e1);


        }

    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity delete(@PathVariable(value = "id") String strId, HttpServletRequest request) {

        Integer EntityInt = null;
        try {
            EntityInt = new Integer(strId);
            boolean retVal = EntityService.delete(EntityInt);
            return new ResponseEntity(retVal, null, HttpStatus.OK);


        } catch (NumberFormatException e1) {
            return ExceptionUtil.getNumberFormatExceptionResponseEntity(request, e1);

        } catch (Exception e1) {

            return ExceptionUtil.getInternalErrorResponseEntity(request, e1);

        }


    }

    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity findAll(HttpServletRequest request) {
        try {
            List retVal = EntityService.findAll();
            return new ResponseEntity(retVal, null, HttpStatus.OK);
        } catch (NumberFormatException e1) {
            return ExceptionUtil.getNumberFormatExceptionResponseEntity(request, e1);

        } catch (Exception e1) {

            return ExceptionUtil.getInternalErrorResponseEntity(request, e1);

        }
    }


    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity findOne(@PathVariable(value = "id") String strId, HttpServletRequest request) {
        try {
            Integer EntityInt = null;
            EntityInt = new Integer(strId);
            Entity retVal = EntityService.findOne(EntityInt);
            return new ResponseEntity(retVal, null, HttpStatus.OK);

        } catch (NumberFormatException e1) {
            return ExceptionUtil.getNumberFormatExceptionResponseEntity(request, e1);

        } catch (Exception e1) {

            return ExceptionUtil.getInternalErrorResponseEntity(request, e1);

        }
    }


}


-- service


package com.frazed.programming.service;

import com.frazed.programming.data.dao.EntityDao;
import com.frazed.programming.data.domain.Entity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by 
 */
@Service
public class EntityService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EntityService.class);

    @Autowired
    EntityDao EntityDao;

    public boolean save(Entity Entity) {

        int retVal = EntityDao.save(Entity);
        if (retVal != 0) return true;
        return false;

    }

    public boolean update(Entity Entity) {

        int retVal = EntityDao.update(Entity);
        if (retVal != 0) return true;
        return false;
    }

    public boolean delete(int id) {
        int retVal = EntityDao.delete(id);
        if (retVal != 0) return true;
        return false;
    }

    public List findAll() {

        List retVal = EntityDao.findAll();
        if (null == retVal || retVal.isEmpty()) return null;
        return retVal;

    }

    public Entity findOne(int Entity) {

        Entity Entity = EntityDao.findOne(Entity);

        if (null == Entity) return null;
        return Entity;
    }

}


-- dao

package com.frazed.programming.data.dao;

import com.frazed.programming.data.domain.Entity;
import com.frazed.programming.data.mapper.EntityMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.Types;
import java.util.List;

/**
 * Created by 
 */
@Repository
public class EntityDao {

    private static Logger logger = LoggerFactory.getLogger(EntityDao.class);


    @Autowired
    private JdbcTemplate jdbcTemplate;



    public int save(Entity Entity) {

        try {
            String insertSQL = "INSERT INTO entity_table(\n" +
                    "\tentity, entity_code, entity_name)\n" +
                    "\tVALUES (?, ?, ?)";

            Object[] params = new Object[]{
                    Entity.getEntity(),
                    Entity.getentity_code(),
                    Entity.getentity_name()

            };

            int[] types = new int[]{
                    Types.INTEGER,
                    Types.VARCHAR,
                    Types.VARCHAR
            };

            // return number of row / rows processed by the executed query
            logger.debug(insertSQL + " insertSQL.");
            int row = jdbcTemplate.update(insertSQL, params, types);
            logger.debug(row + " row inserted.");

            return row;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    public int update(Entity Entity) {

        try {
            String updateSQL = "UPDATE entity_table\n" +
                    "\tSET entity_code=?, entity_name=?\n" +
                    "\tWHERE entity=?";
            // define query arguments

            Object[] params = new Object[]{
                    Entity.getentity_code(),
                    Entity.getentity_name(),
                    Entity.getEntity()};
            //  define SQL types of the arguments
            int[] types = new int[]{
                    Types.VARCHAR,
                    Types.VARCHAR,
                    Types.INTEGER,
            };

            int row = jdbcTemplate.update(updateSQL, params, types);

            logger.debug(row + " row(s) updated.");

            return row;

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }

    public int delete(int id) {

        try {
            String deteleSQL = "DELETE FROM entity_table WHERE entity=?";
            Object[] params = new Object[]{id};
            int[] types = new int[]{Types.INTEGER};

            int row = jdbcTemplate.update(deteleSQL, params, types);

            logger.debug(row + " row deleted.");

            return row;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    public List findAll() {

        try {
            String SQL = "select * from entity_table";
            List<Entity> retval = jdbcTemplate.query(SQL, new EntityMapper());

            return retval;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }

    public int count() {

        try {
            String SQL = "select count(*) from entity_table ";
            int retVal = jdbcTemplate.queryForObject(SQL, Integer.class);

            return retVal;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }

    public Entity findOne(int Entity) {
        try {
            String SQL = "select entity, entity_code, entity_name from entity_table WHERE entity=?";
            Object[] params = new Object[]{Entity};
            int[] types = new int[]{Types.INTEGER};
            List<Entity> retVal = jdbcTemplate.query(SQL, params, types, new EntityMapper());

            if (null == retVal || retVal.isEmpty()) return null;

            return retVal.get(0);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }


}


pojo

package com.capitalone.fstelephony.voice.data.domain;

/**
 * Created by 
 */
public class entity {


    private Integer entity;
    private String entity_code;
    private String entity_name;


    public entity() {
        super();
    }

    public entity(Integer entity, String entity_code, String entity_name) {
        this.entity = entity;
        this.entity_code = entity_code;
        this.entity_name = entity_name;
    }

    public String getEntity_code() {
        return entity_code;
    }

    public void setEntity_code(String entity_code) {
        this.entity_code = entity_code;
    }

    public String getEntity_name() {
        return entity_name;
    }

    public void setEntity_name(String entity_name) {
        this.entity_name = entity_name;
    }


    public Integer getEntity() {
        return entity;
    }

    public void setEntity(Integer entity) {
        this.entity = entity;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        entity entitys = (entity) o;

        if (entity != null ? !entity.equals(entitys.entity) : entitys.entity != null) return false;
        return (entity_code != null ? entity_code.equals(entitys.entity_code) : entitys.entity_code == null) && (entity_name != null ? entity_name.equals(entitys.entity_name) : entitys.entity_name == null);
    }

    @Override
    public int hashCode() {
        int result = entity != null ? entity.hashCode() : 0;
        result = 31 * result + (entity_code != null ? entity_code.hashCode() : 0);
        result = 31 * result + (entity_name != null ? entity_name.hashCode() : 0);
        return result;
    }
    @Override
    public String toString() {
        return "entity{" +
                "entity=" + entity +
                ", entity_code='" + entity_code + '\'' +
                ", entity_name='" + entity_name + '\'' +
                '}';
    }
}



deply  the application on tomcat to test API



http://localhost:8080/entity/list


package structure


src/main/
com
farzed
programming
data
constants
---db constants and quries
dao
--- dao classes
domain
-- pojo
mapper
-- jdbc mappers
scripts
-- ddl and DML statements for creatingdb
service
-- service classes
util
-- utility classes
web
-- rest controllers
AppConfig.java
myApplicaiton.java
Servletinitlizer.java
resoruces
applicaton.properties
logback.xml

pom.xml