Wednesday, 24 December 2014

Simple example of Spring JMS template

This Blog instruction will help us to access JMS queues using Spring framework JMS api.
Java Messaging Service provide communication between applications systems like peer-to-peer facility.Each client connects to a messaging agent that provides facilities for creating, sending, receiving, and reading messages. JMS enables distributed communication that is loosely coupled. There are three message exchange model.
  • Publish-Subscribe Messaging

  • Point-To-Point Messaging

  • Request-Reply Messaging
This blog instructions will help us to implement simple example of Point-To-Point Messaging.
Please check JMS specification for detailed decription.
Please check spring-jms-<version>.RELEASE speciication for detailed description.

  • Pre-requsite
  • Instructions assumes that jdk, ActiveMQ is installed without any error.
    Following image will guide us to start ActiveMQ and create one Queue name "myQ".

  • Implemenation instructions
    1. Create a Simple spring project name "spring-jms-example". Following image will guide us. Add the required libraries in classpath.
    2. - spring-aop-4.1.3.RELEASE.jar
      - spring-beans-4.1.3.RELEASE.jar
      - spring-context-4.1.3.RELEASE.jar
      - spring-context-support-4.1.3.RELEASE.jar
      - spring-core-4.1.3.RELEASE.jar
      - spring-expression-4.1.3.RELEASE.jar
      - spring-jms-4.1.3.RELEASE.jar
      - activemq-broker-5.10.0.jar
      - activemq-client-5.10.0.jar
      - activemq-jaas-5.10.0.jar
      - geronimo-jms_1.1_spec-1.1.1.jar
      - hawtbuf-1.10.jar
      - activemq-spring-5.10.0.jar
      - geronimo-j2ee-management_1.1_spec-1.0.1.jar
      - log4j-1.2.14.jar
      - slf4j-jcl-1.7.5.jar

    3. Create following packages.
      - example.spring.simple.jms.producer
      - example.spring.simple.jms.consumer
      - example.spring.dao
    4. Create simple pojo class Member in example.spring.dao package and add following snippet.
    5.   /**
        *
        * Copyright © Kaustuv Maji , 2014
        * Repos - https://github.com/kaustuvmaji
        * Blog -  http://kaustuvmaji.blogspot.in
        *
        */
        package example.spring.dao;
      
        import java.io.Serializable;
      
        /**
         * @author KMaji
         *
         */
        public class Member implements Serializable {
      
         /**
          *
          */
         private static final long serialVersionUID = 8944832256293484687L;
      
      
         private String name;
         private Integer id;
         private Integer age;
      
         /**
          * Default constructor
          */
         public Member() {
      
         }
      
         /**
          * Constructor with argument
          * @param name
          * @param age
          */
         public Member(String name, Integer age) {
          super();
          this.name = name;
          this.age = age;
         }
      
         /**
          * @return the name
          */
         public final String getName() {
          return name;
         }
         /**
          * @param name the name to set
          */
         public final void setName(String name) {
          this.name = name;
         }
         /**
          * @return the id
          */
         public final Integer getId() {
          return id;
         }
         /**
          * @param id the id to set
          */
         public final void setId(Integer id) {
          this.id = id;
         }
         /**
          * @return the age
          */
         public final Integer getAge() {
          return age;
         }
         /**
          * @param age the age to set
          */
         public final void setAge(Integer age) {
          this.age = age;
         }
      
         /* (non-Javadoc)
          * @see java.lang.Object#toString()
          */
         @Override
         public String toString() {
          StringBuilder builder = new StringBuilder();
          builder.append("Member [");
          if (name != null)
           builder.append("name=").append(name).append(", ");
          if (id != null)
           builder.append("id=").append(id).append(", ");
          if (age != null)
           builder.append("age=").append(age);
          builder.append("]");
          return builder.toString();
         }
        }
    6. Create SimpleMessageProducer class in example.spring.simple.jms.producer and add following snippet.
    7.   /**
         *
         * Copyright © Kaustuv Maji , 2014
         * Repos - https://github.com/kaustuvmaji
         * Blog -  http://kaustuvmaji.blogspot.in
         *
         */
        package example.spring.simple.jms.producer;
      
        import java.util.Date;
      
        import javax.jms.BytesMessage;
        import javax.jms.JMSException;
        import javax.jms.MapMessage;
        import javax.jms.Message;
        import javax.jms.Session;
      
        import org.apache.log4j.Logger;
        import org.springframework.jms.core.JmsTemplate;
        import org.springframework.jms.core.MessageCreator;
      
        import example.spring.dao.Member;
      
        /**
         * Example spring jms producer.
         *
         * @author KMaji
         *
         */
        public class SimpleMessageProducer {
      
         private static final Logger LOG = Logger.getLogger(SimpleMessageProducer.class.getName());
      
         protected JmsTemplate jmsTemplate;
      
         /**
          * Getter Method of JMSTemplate
          *
          * @return the jmsTemplate
          */
         public final JmsTemplate getJmsTemplate() {
          return jmsTemplate;
         }
      
         /**
          * Setter Method of JMSTemplate
          *
          * @param jmsTemplate
          *            the jmsTemplate to set
          */
         public final void setJmsTemplate(JmsTemplate jmsTemplate) {
          this.jmsTemplate = jmsTemplate;
         }
      
         protected final void sendMessages(String sendType, int i) {
          try {
           if ("textMessage".equalsIgnoreCase(sendType)) {
            jmsSendTextMessages(i);
           } else if ("objectMessage".equalsIgnoreCase(sendType)) {
            jmsSendObjectMessages(i);
           } else if ("ByteMessage".equalsIgnoreCase(sendType)) {
            jmsSendBytesMessages(i);
           } else if ("MapMessage".equalsIgnoreCase(sendType)) {
            jmsSendMapMessages(i);
           }
          } catch (JMSException e) {
           LOG.error("unable to process", e);
          }
         }
      
         /**
          * This method is used to produce TextMessages
          *
          * @throws JMSException
          */
         protected void jmsSendTextMessages(final int i) throws JMSException {
      
          final StringBuilder buffer = new StringBuilder();
      
          buffer.append("jmsSendTextMessages '").append(i).append("' sent at: ").append(new Date());
      
          final String payload = buffer.toString();
          jmsTemplate.send(new MessageCreator() {
           public Message createMessage(Session session) throws JMSException {
            Message message = session.createTextMessage(payload);
            message.setIntProperty("messageCount", i);
            LOG.info("Sending message number ->" + i + " message [" + message + "]");
            return message;
           }
          });
         }
      
         /**
          * This method is used to produce ObjectMessages
          *
          * @throws JMSException
          */
         protected void jmsSendObjectMessages(final int i) {
      
          jmsTemplate.send(new MessageCreator() {
      
           @Override
           public Message createMessage(Session session) throws JMSException {
            Member member = new Member();
            member.setId(i);
            member.setName("jmsSendObjectMessage_" + i);
            member.setAge(10 + i);
            Message message = session.createObjectMessage(member);
            LOG.info("Sending message number ->" + i + " message [" + message + "]");
            return message;
           }
          });
         }
      
         /**
          * This method is used to produce BytesMessages.
          *
          * @throws JMSException
          */
         public void jmsSendBytesMessages(final int i) throws JMSException {
          final StringBuilder buffer = new StringBuilder();
      
          buffer.append("Byte message [").append(i).append("] sent at -> ").append(new Date());
      
          final String payload = buffer.toString();
      
          jmsTemplate.send(new MessageCreator() {
           public Message createMessage(Session session) throws JMSException {
            BytesMessage message = session.createBytesMessage();
            message.writeUTF(payload);
            message.setIntProperty("messageCount", i);
            LOG.info("Sending message number ->" + i + " message [" + message + "]");
            return message;
           }
          });
         }
      
         /**
          * This method is used to produce MapMessages.
          *
          * @throws JMSException
          */
         public void jmsSendMapMessages(final int i) throws JMSException {
          final StringBuilder buffer = new StringBuilder();
      
          buffer.append("Map message [").append(i).append("] sent at -> ").append(new Date());
      
          final String payload = buffer.toString();
      
          jmsTemplate.send(new MessageCreator() {
           public Message createMessage(Session session) throws JMSException {
            MapMessage message = session.createMapMessage();
            message.setString("payload", payload);
            LOG.info("Sending message number ->" + i + " message [" + message + "]");
            return message;
           }
          });
         }
         
         /**
          * This method is used to produce StreamMessages.
          *
          * @throws JMSException
          */
         public void jmsSendStreamMessages(final int i) throws JMSException {
          final StringBuilder buffer = new StringBuilder();
      
          buffer.append("Stream message [").append(i).append("] sent at -> ").append(new Date());
      
          final String payload = buffer.toString();
      
          jmsTemplate.send(new MessageCreator() {
           public Message createMessage(Session session) throws JMSException {
            javax.jms.StreamMessage message = session.createStreamMessage();
            message.writeObject(payload);
            LOG.info("Sending message number ->" + i + " message [" + message + "]");
            return message;
           }
          });
         }
        }

      Following table explains the different types of JMS messages.
      Method name Message Type Body Contains
      jmsSendTextMessages() TextMessage java.lang.String object
      jmsSendMapMessages() MapMessage A set of name-value pairs <String,Object>
      jmsSendBytesMessages() BytesMessage A stream of uninterpreted bytes.
      jmsSendStreamMessages StreamMessage A stream of primitive values, filled and read sequentially.
      jmsSendObjectMessages() ObjectMessage A Serializable object.

    8. Create class ProducerApp in example.spring.simple.jms.producer and add following snippet.
    9.   /**
         *
         * Copyright © Kaustuv Maji , 2014
         * Repos - https://github.com/kaustuvmaji
         * Blog -  http://kaustuvmaji.blogspot.in
         *
         */
        package example.spring.simple.jms.producer;
      
      
        import org.apache.log4j.Logger;
        import org.springframework.context.ApplicationContext;
        import org.springframework.context.support.ClassPathXmlApplicationContext;
      
        /**
         * @author KMaji
         *
         */
        public class ProducerApp implements Runnable {
      
         private static final Logger LOG = Logger
           .getLogger(ProducerApp.class);
      
         /**
          * @param args
          */
         public static void main(String[] args) {
          new ProducerApp().run();
         }
      
         @Override
         public void run() {
          String sendType = "TextMessage";
          @SuppressWarnings("resource")
          ApplicationContext context = new ClassPathXmlApplicationContext(
            "simple-producer-jms-context.xml");
      
          SimpleMessageProducer producer = (SimpleMessageProducer) context
            .getBean("messageProducer");
      
          LOG.info("Using the sendType "+sendType);
          int i = 0 ;
      
          while (true) {
      
           producer.sendMessages(sendType, i++);
           try {
      
            Thread.sleep(1000);
           } catch (InterruptedException e) {
            e.printStackTrace();
           }
          }
         }
        }
    10. Create spring bean configuration simple-producer-jms-context.xml in resource folder. This bean configuration will be used for jms message producer.
    11.   <?xml version="1.0" encoding="UTF-8"?>
        <!-- Copyright © Kaustuv Maji , 2014
          Repos - https://github.com/kaustuvmaji
          Blog - http://kaustuvmaji.blogspot.in
        -->
        <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:jms="http://www.springframework.org/schema/jms"
         xmlns:p="http://www.springframework.org/schema/p"
         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/jms
              http://www.springframework.org/schema/jms/spring-jms.xsd
              http://www.springframework.org/schema/util
              http://www.springframework.org/schema/util/spring-util.xsd">
      
         <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"
         p:brokerURL="tcp://localhost:61616"
         p:userName="admin" p:password="admin"
         p:maxThreadPoolSize="15"/>
      
         <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
          <constructor-arg value="myQ" />
         </bean>
      
         <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"
          p:connectionFactory-ref="connectionFactory"
          p:defaultDestination-ref="destination">
         </bean>
      
         <bean class="example.spring.simple.jms.producer.SimpleMessageProducer" id="messageProducer">
          <property name="jmsTemplate" ref="jmsTemplate" />
         </bean>
      
        </beans>

    12. Create class SimpleMessageReceiver in package example.spring.simple.jms.consumer and add following snippet.
    13.   /**
         *
         * Copyright © Kaustuv Maji , 2014
         * Repos - https://github.com/kaustuvmaji
         * Blog -  http://kaustuvmaji.blogspot.in
         *
         */
        package example.spring.simple.jms.consumer;
      
        import javax.jms.BytesMessage;
        import javax.jms.JMSException;
        import javax.jms.MapMessage;
        import javax.jms.Message;
        import javax.jms.ObjectMessage;
        import javax.jms.StreamMessage;
        import javax.jms.TextMessage;
      
        import org.apache.log4j.Logger;
        import org.springframework.jms.core.JmsTemplate;
      
        import example.spring.dao.Member;
      
        /**
         *
         * @author KMaji
         *
         */
        public class SimpleMessageReceiver {
      
         private static final Logger LOG = Logger.getLogger(SimpleMessageReceiver.class);
      
         protected JmsTemplate jmsTemplate;
      
         public JmsTemplate getJmsTemplate() {
          return jmsTemplate;
         }
      
         public void setJmsTemplate(JmsTemplate jmsTemplate) {
          this.jmsTemplate = jmsTemplate;
         }
      
         public void receive() throws JMSException {
      
          Message message = jmsTemplate.receive();
      
          if (message == null) {
           // do not work for null message ignore
          }
      
          if (message instanceof TextMessage) {
           LOG.info("Received a JMS message:  -> [" + message + "]");
          } else if (message instanceof ObjectMessage) {
           try {
            Member obj = (Member) ((ObjectMessage) message).getObject();
            LOG.info("Received a JMS message: ObjectMessage -> [" + obj.toString() + "]");
           } catch (JMSException e) {
            LOG.error("unable to process message", e);
           }
          } else if (message instanceof MapMessage) {
           MapMessage msg = (MapMessage) message;
           LOG.info("Received a JMS message: MapMessage -> [" + msg.getString("payload") + "]");
          } else if (message instanceof BytesMessage) {
           BytesMessage bInMsg = (BytesMessage) message;
           int msgLength = (int) bInMsg.getBodyLength();
           byte[] msg = new byte[msgLength];
           bInMsg.readBytes(msg);
           LOG.info("Received a JMS message: BytesMessage -> [" + msg + "]");
          }else if (message instanceof StreamMessage) {
           StreamMessage msg = (StreamMessage) message;
           LOG.info("Received a JMS message: MapMessage -> [" + msg.readObject() + "]");
          }else {
           // only 5 type of message will come so relax
          }
         }
        }
    14. Create class customize AttributesMapper name SingleAttributesMapper and add following snippet.
    15.    /**
         *
         * Copyright © Kaustuv Maji , 2014
         * Repos - https://github.com/kaustuvmaji
         * Blog -  http://kaustuvmaji.blogspot.in
         *
         */
        package example.spring.simple.jms.consumer;
      
        import javax.jms.JMSException;
      
        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
        import org.springframework.context.ApplicationContext;
        import org.springframework.context.support.ClassPathXmlApplicationContext;
      
        /**
         * Spring JMS Consumer example.
         *
         * @author KMaji
         *
         */
        public class ConsumerApp implements Runnable {
      
         private static final Logger LOG = LoggerFactory.getLogger(ConsumerApp.class);
      
         /**
          * @param args
          */
         public static void main(String[] args) {
          new ConsumerApp().run();
          LOG.debug("Consumer started ...");
         }
      
         @Override
         public void run() {
          @SuppressWarnings("resource")
          ApplicationContext context = new ClassPathXmlApplicationContext("simple-consumer-jms-context.xml");
          SimpleMessageReceiver receiver = (SimpleMessageReceiver) context.getBean("messageReceiver");
          while (true) {
           try {
            receiver.receive();
            Thread.sleep(5000);
           } catch (InterruptedException | JMSException e) {
            LOG.error("unable to process", e);
           }
          }
         }
        }
    16. Create spring bean configuration simple-consumer-jms-context.xml in resource folder. This bean configuration will be used for jms message consumer.
    17.   <?xml version="1.0" encoding="UTF-8"?>
        <!-- Copyright © Kaustuv Maji , 2014
          Repos - https://github.com/kaustuvmaji
          Blog - http://kaustuvmaji.blogspot.in
        -->
        <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:jms="http://www.springframework.org/schema/jms"
         xmlns:p="http://www.springframework.org/schema/p"
         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/jms
              http://www.springframework.org/schema/jms/spring-jms.xsd
              http://www.springframework.org/schema/util
              http://www.springframework.org/schema/util/spring-util.xsd">
      
         <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"
            p:brokerURL="tcp://localhost:61616"
            p:userName="admin" p:password="admin"
            p:maxThreadPoolSize="15" />
      
         <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
          <constructor-arg value="myQ" />
         </bean>
      
         <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"
          p:connectionFactory-ref="connectionFactory"
          p:defaultDestination-ref="destination"
          p:receiveTimeout="1000"/>
      
      
         <bean id="messageReceiver" class="example.spring.simple.jms.consumer.SimpleMessageReceiver">
          <property name="jmsTemplate" ref="jmsTemplate" />
         </bean>
      
        </beans>

    18. Create log4j.xml in resource folder and add following snippet.
    19.      <?xml version="1.0" encoding="UTF-8"?>
           <!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
           <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true">
      
            <!-- Appenders -->
            <appender name="console" class="org.apache.log4j.ConsoleAppender">
             <param name="Target" value="System.out" />
             <layout class="org.apache.log4j.PatternLayout">
              <param name="ConversionPattern" value="%d{ISO8601} %-5p %-1X{TID} %t [%c] %m%n" />
             </layout>
            </appender>
      
             <!-- Appenders -->
            <appender name="file" class="org.apache.log4j.RollingFileAppender">
             <param name="Threshold" value="ALL" />
             <param name="File" value="diag.log" />
             <param name="Append" value="true" />
             <param name="MaxFileSize" value="500000KB" />
             <param name="MaxBackupIndex" value="10" />
             <layout class="org.apache.log4j.PatternLayout">
              <param name="ConversionPattern" value="%d{ISO8601} %-5p %-1X{TID} %t [%c] %m%n" />
             </layout>
            </appender>
      
            <!-- Root Logger -->
            <root>
             <priority value="ALL" />
             <appender-ref ref="console" />
             <appender-ref ref="file" />
            </root>
      
           </log4j:configuration>

        Post Development testing


    1. Run ProducerApp class in package example.spring.simple.jms.producer. This class will continuously push message to "myQ". Keep in mind until unless we stop this class it will continuously push message to queue. We can check number of messages in queue by activeMQ web app. check following image.
    2. Run ConsumerApp class in package example.spring.simple.jms.consumer. This class will continuously pull message from "myQ". Keep in mind until unless we stop this class it will continuously push message from queue. We can check status of messages processed in queue by activeMQ web app. check following image.
    Click here to download source code of above example

    Source Code


    European Union laws require you to give European Union visitors information about cookies used on your blog. In many cases, these laws also require you to obtain consent.

    As a courtesy, we have added a notice on your blog to explain Google's use of certain Blogger and Google cookies, including use of Google Analytics and AdSense cookies.

    Friday, 19 December 2014

    Simple example of Spring LdapTemplate

    This Blog instruction will help us to do LDAP programming using Spring framework LDAP api. This Blog instruction create simple example of search, create, read, update and delete (SCRUD) using Spring framework LDAP api.
    Please note I am huge fan of ldap command line tool. First I learned ldap command line from Oracle ldap comtool. After I read specification of Spring LDAP I found easy to work with. This blog instruction is simple spring ldap api example. Soon I will also publish another example of spring ldap api usage with spring ldap framework ODM api.
  • Pre-requsite
  • Instructions assume that jdk, Apache DS, Apache Directory Studio is installed without any error.
    We have to start LDAP service. After installation of Apache DS following image will guide us to start default LDAP service. We got check default Apache DS. After starting Apache DS following image will guide us to explore newly started LDAP services.

  • Implemenation instructions
    1. Create a Simple spring project name "spring-ldap-example". Following image will guide us. Add the required libraries in classpath.
    2. - spring-aop-4.1.3.RELEASE.jar
      - spring-beans-4.1.3.RELEASE.jar
      - spring-context-4.1.3.RELEASE.jar
      - spring-context-support-4.1.3.RELEASE.jar
      - spring-core-4.1.3.RELEASE.jar
      - spring-expression-4.1.3.RELEASE.jar
      - spring-ldap-core-2.0.2.RELEASE.jar
      - spring-ldap-core-tiger-2.0.2.RELEASE.jar
      - spring-ldap-ldif-batch-2.0.2.RELEASE.jar
      - spring-ldap-ldif-core-2.0.2.RELEASE.jar
      - spring-ldap-test-2.0.2.RELEASE.jar
      - log4j-1.2.14.jar
      - slf4j-jcl-1.7.5.jar

    3. Create folder name resource and add in classpath. Create test_data.ldif in resource folder and following snippet. This test_data.ldif is used to prepare test data.
    4.      version: 1
      
           dn: dc=example,dc=com
           objectclass: top
           objectclass: domain
           dc: example
      
           dn: ou=groups,dc=example,dc=com
           objectClass: top
           objectClass: organizationalUnit
           ou: groups
           description: this will contains all the groups
      
           dn: uid=kaustuv,ou=users,dc=example,dc=com
           objectClass: organizationalPerson
           objectClass: person
           objectClass: uidObject
           objectClass: top
           cn: kaustuv
           sn: maji
           uid: kaustuv
           postalAddress: GC 207, Sector III, SaltlakeCity, Kolkata 700106, WestBengal, India
           telephoneNumber: 9831198311
           userPassword:: e1NTSEF9OXg3VGxzamNrQkFWZmVRRllRYnBXS25IUFYvV0hpdmtiSFNNMXc9PQ==
      
           dn: cn=testGroup,ou=groups,dc=example,dc=com
           objectClass: top
           objectClass: groupOfUniqueNames
           cn: testGroup
           uniqueMember: uid=kaustuv,ou=users,dc=example,dc=com
           o: kaustuv's blog
      
           dn: ou=users,dc=example,dc=com
           objectClass: top
           objectClass: organizationalUnit
           ou: users
      
           dn: uid=guest,ou=users,dc=example,dc=com
           objectClass: top
           objectClass: uidObject
           objectClass: person
           objectClass: organizationalPerson
           cn: guest
           sn: guest
           uid: guest
           postalAddress: DreamLand
           telephoneNumber: 9830098300
           userPassword:: e1NTSEF9OXg3VGxzamNrQkFWZmVRRllRYnBXS25IUFYvV0hpdmtiSFNNMXc9PQ==
    5. Create package ldap.advance.example
    6. Create simple pojo class User and following snippet.
    7.       /**
            *
            * Copyright © Kaustuv Maji , 2014
            * Repos - https://github.com/kaustuvmaji
            * Blog -  http://kaustuvmaji.blogspot.in
            *
            */
            package ldap.advance.example;
      
            import java.io.Serializable;
      
            /**
             * @author KMaji
             *
             */
            public class User implements Serializable {
      
             /**
              *
              */
             private static final long serialVersionUID = 9081527761576640803L;
      
             private String uid;
             private String cn;
             private String sn;
             private String userPassword;
             private String postalAddress;
             private String telephoneNumber;
      
             /**
              * @return the uid
              */
             public synchronized final String getUid() {
              return uid;
             }
      
             /**
              * @param uid
              *            the uid to set
              */
             public synchronized final void setUid(String uid) {
              this.uid = uid;
             }
      
             /**
              * @return the cn
              */
             public synchronized final String getCn() {
              return cn;
             }
      
             /**
              * @param cn
              *            the cn to set
              */
             public synchronized final void setCn(String cn) {
              this.cn = cn;
             }
      
             /**
              * @return the sn
              */
             public synchronized final String getSn() {
              return sn;
             }
      
             /**
              * @param sn
              *            the sn to set
              */
             public synchronized final void setSn(String sn) {
              this.sn = sn;
             }
      
             /**
              * @return the userPassword
              */
             public synchronized final String getUserPassword() {
              return userPassword;
             }
      
             /**
              * @param userPassword
              *            the userPassword to set
              */
             public synchronized final void setUserPassword(String userPassword) {
              this.userPassword = userPassword;
             }
      
             /**
              * @return the postalAddress
              */
             public synchronized final String getPostalAddress() {
              return postalAddress;
             }
      
             /**
              * @param postalAddress
              *            the postalAddress to set
              */
             public synchronized final void setPostalAddress(String postalAddress) {
              this.postalAddress = postalAddress;
             }
      
             /**
              * @return the telephoneNumber
              */
             public synchronized final String getTelephoneNumber() {
              return telephoneNumber;
             }
      
             /**
              * @param telephoneNumber
              *            the telephoneNumber to set
              */
             public synchronized final void setTelephoneNumber(String telephoneNumber) {
              this.telephoneNumber = telephoneNumber;
             }
      
             /*
              * (non-Javadoc)
              *
              * @see java.lang.Object#toString()
              */
             @Override
             public String toString() {
              StringBuilder builder = new StringBuilder();
              builder.append("User [");
              if (uid != null) {
               builder.append("uid=");
               builder.append(uid);
               builder.append(", ");
              }
              if (cn != null) {
               builder.append("cn=");
               builder.append(cn);
               builder.append(", ");
              }
              if (sn != null) {
               builder.append("sn=");
               builder.append(sn);
               builder.append(", ");
              }
              if (userPassword != null) {
               builder.append("userPassword=");
               builder.append(userPassword);
               builder.append(", ");
              }
              if (postalAddress != null) {
               builder.append("postalAddress=");
               builder.append(postalAddress);
               builder.append(", ");
              }
              if (telephoneNumber != null) {
               builder.append("telephoneNumber=");
               builder.append(telephoneNumber);
              }
              builder.append("]");
              return builder.toString();
             }
            }
    8. Create interface UserRepositoryIntf and add following snippet.
    9. We will define all following methods to implements example of SCRUD functions.
            /**
            *
            * Copyright © Kaustuv Maji , 2014
            * Repos - https://github.com/kaustuvmaji
            * Blog -  http://kaustuvmaji.blogspot.in
            *
            */
            package ldap.advance.example;
      
            import java.util.List;
      
            /**
             * <pre>
             * This interface is used for
             *   a) fetch all the user details as a list of String
             *   b) fetch all the user details as a list of User object
             *   c) fetch user details of particular user.
             * </pre>
             *
             * @author KMaji
             *
             */
            public interface UserRepositoryIntf {
      
             /**
              * This method is responsible to fetch all the user details as a list of
              * String.
              *
              * @return list of String.
              */
             public List<String> getAllUserNames();
      
             /**
              * This method is responsible to fetch all the user details as a list of
              * User object
              *
              * @return list of {@link User}
              */
             public List<User> getAllUsers();
      
             /**
              * This method is responsible to fetch user details of particular user.
              *
              * @return user details {@link User}
              */
             public User getUserDetails(String userName);
      
             /**
              * This method is responsible to fetch user details of particular user as a string.
              *
              * @return user detail {@link User}
              */
             public String getUserDetail(String userName);
      
             /**
              * This method is responsible to authenticate user.
              *
              * @return boolean true|false
              */
             public boolean authenticate(String base,String userName, String password);
      
             /**
              * This method is responsible to update telephone number of user.
              *
              * @return boolean true|false
              */
             public User updateTelePhone(String userName, String newNumber);
      
             /**
              * This method is responsible to create user.
              */
             public boolean createUser(User user);
      
             /**
              * This method is responsible to delete user.
              */
             public boolean remove(String uid);
            }
    10. Create class UserRepositoryImpl implements interface UserRepositoryIntf and add following snippet.
    11.       /**
             *
             * Copyright © Kaustuv Maji , 2014
             * Repos - https://github.com/kaustuvmaji
             * Blog -  http://kaustuvmaji.blogspot.in
             *
             */
            package ldap.advance.example;
      
            import static org.springframework.ldap.query.LdapQueryBuilder.query;
      
            import java.io.UnsupportedEncodingException;
            import java.util.List;
      
            import javax.naming.NamingEnumeration;
            import javax.naming.NamingException;
            import javax.naming.directory.Attribute;
            import javax.naming.directory.Attributes;
            import javax.naming.directory.BasicAttribute;
            import javax.naming.directory.BasicAttributes;
            import javax.naming.directory.DirContext;
            import javax.naming.directory.ModificationItem;
            import javax.naming.directory.SearchControls;
      
            import org.apache.log4j.Logger;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.beans.factory.annotation.Qualifier;
            import org.springframework.ldap.core.AttributesMapper;
            import org.springframework.ldap.core.DistinguishedName;
            import org.springframework.ldap.core.LdapTemplate;
            import org.springframework.ldap.query.LdapQuery;
            import org.springframework.stereotype.Component;
      
            /**
             * This class implements the @see {@link UserRepository}.
             *
             * @author KMaji
             *
             */
            @Component
            public class UserRepositoryImpl implements UserRepository {
      
             private static Logger log = Logger.getLogger(UserRepositoryImpl.class);
      
             public UserRepositoryImpl() {
      
             }
      
             @Autowired(required = true)
             @Qualifier(value = "ldapTemplate")
             private LdapTemplate ldapTemplate;
      
             /**
              * (non-Javadoc)
              *
              * @see ldap.advance.example.UserRepository#getAllUserNames()
              */
             @Override
             public List<String> getAllUserNames() {
              log.info("executing {getAllUserNames}");
              LdapQuery query = query().base("ou=users");
              List<String> list = ldapTemplate.list(query.base());
              log.info("Users -> " + list);
              return ldapTemplate.search(query().base("ou=users").where("objectClass").is("person"), new SingleAttributesMapper());
             }
      
             /**
              * (non-Javadoc)
              *
              * @see ldap.advance.example.UserRepository#getAllUsers()
              */
             @Override
             public List<User> getAllUsers() {
              SearchControls controls = new SearchControls();
              controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
              return ldapTemplate.search(DistinguishedName.EMPTY_PATH, "(objectclass=person)", controls, new UserAttributesMapper());
             }
      
             /**
              * (non-Javadoc)
              *
              * @see ldap.advance.example.UserRepository#getUserDetails(java.lang.String)
              */
             @Override
             public User getUserDetails(String userName) {
              log.info("executing {getUserDetails}");
              List<User> list = ldapTemplate.search(query().base("ou=users").where("uid").is(userName), new UserAttributesMapper());
              if (list != null && !list.isEmpty()) {
               return list.get(0);
              }
              return null;
             }
      
             /**
              * (non-Javadoc)
              *
              * @see ldap.advance.example.UserRepository#getUserDetail(java.lang.String)
              */
             @Override
             public String getUserDetail(String userName) {
              log.info("executing {getUserDetails}");
              List<String> results = ldapTemplate.search(query().base("ou=users").where("uid").is(userName), new MultipleAttributesMapper());
              if (results != null && !results.isEmpty()) {
               return results.get(0);
              }
              return " userDetails for " + userName + " not found .";
             }
      
             /**
              * (non-Javadoc)
              *
              * @see ldap.advance.example.UserRepository#authenticate(java.lang.String,
              * java.lang.String)
              */
             @Override
             public boolean authenticate(String base, String userName, String password) {
              log.info("executing {authenticate}");
              return ldapTemplate.authenticate(base, "(uid=" + userName + ")", password);
             }
      
             /**
              * (non-Javadoc)
              *
              * @see
              * ldap.advance.example.UserRepository#updateTelePhone(java.lang.String)
              */
             @Override
             public User updateTelePhone(String userName, String newNumber) {
              log.info("executing {updateTelePhone}");
              ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("telephoneNumber", newNumber));
              ldapTemplate.modifyAttributes("uid=" + userName + ",ou=users", new ModificationItem[]{item});
              return getUserDetails(userName);
             }
      
             /**
              * (non-Javadoc)
              *
              * @see
              * ldap.advance.example.UserRepository#createUser(ldap.advance.example.User)
              */
             @Override
             public boolean createUser(User user) {
              log.info("executing {createUser}");
              Attribute objectClass = new BasicAttribute("objectClass");
              {
               objectClass.add("top");
               objectClass.add("uidObject");
               objectClass.add("person");
               objectClass.add("organizationalPerson");
              }
              Attributes userAttributes = new BasicAttributes();
              userAttributes.put(objectClass);
              userAttributes.put("cn", user.getCn());
              userAttributes.put("sn", user.getSn());
              userAttributes.put("uid", user.getUid());
              userAttributes.put("postalAddress", user.getPostalAddress());
              userAttributes.put("telephoneNumber", user.getTelephoneNumber());
              userAttributes.put("userPassword", user.getUserPassword().getBytes());
              ldapTemplate.bind(bindDN(user.getUid()), null, userAttributes);
              return true;
             }
      
             /**
              * (non-Javadoc)
              * @see ldap.advance.example.UserRepository#remove(java.lang.String)
              */
             @Override
             public boolean remove(String uid) {
              ldapTemplate.unbind(bindDN(uid));
              return true;
             }
      
             public static javax.naming.Name bindDN(String _x){
              @SuppressWarnings("deprecation")
              javax.naming.Name name = new DistinguishedName("uid=" + _x + ",ou=users");
              return name;
             }
      
             /**
              * This class is responsible to prepare User object after ldap search.
              *
              * @author KMaji
              *
              */
             private class UserAttributesMapper implements AttributesMapper<User> {
      
              @Override
              public User mapFromAttributes(Attributes attributes) throws NamingException {
               User user;
               if (attributes == null) {
                return null;
               }
               user = new User();
               user.setCn(attributes.get("cn").get().toString());
      
               if (attributes.get("userPassword") != null) {
                String userPassword = null;
                try {
                 userPassword = new String((byte[]) attributes.get("userPassword").get(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                 log.error("unable to process", e);
                }
                user.setUserPassword(userPassword);
               }
               if (attributes.get("uid") != null) {
                user.setUid(attributes.get("uid").get().toString());
               }
               if (attributes.get("sn") != null) {
                user.setSn(attributes.get("sn").get().toString());
               }
               if (attributes.get("postalAddress") != null) {
                user.setPostalAddress(attributes.get("postalAddress").get().toString());
               }
               if (attributes.get("telephoneNumber") != null) {
                user.setTelephoneNumber(attributes.get("telephoneNumber").get().toString());
               }
               return user;
              }
             }
      
             /**
              * This class is responsible to print only cn .
              *
              * @author KMaji
              *
              */
             private class SingleAttributesMapper implements AttributesMapper<String> {
      
              @Override
              public String mapFromAttributes(Attributes attrs) throws NamingException {
               Attribute cn = attrs.get("cn");
               return cn.toString();
              }
             }
      
             /**
              * This class is responsible to print all the content in string format.
              *
              * @author KMaji
              *
              */
             private class MultipleAttributesMapper implements AttributesMapper<String> {
      
              @Override
              public String mapFromAttributes(Attributes attrs) throws NamingException {
               NamingEnumeration<? extends Attribute> all = attrs.getAll();
               StringBuffer result = new StringBuffer();
               result.append("\n Result { \n");
               while (all.hasMore()) {
                Attribute id = all.next();
                result.append(" \t |_  #" + id.getID() + "= [ " + id.get() + " ]  \n");
                log.info(id.getID() + "\t | " + id.get());
               }
               result.append("\n } ");
               return result.toString();
              }
             }
            }
      • Following table will explain the methods that used to SCRUD functionalities.

      Methods name Description
      createUser This method is responsible to create user.
      - Example of ldapTemplate.bind() and BasicAttribute.
      updateTelePhone This method is responsible to update telephone number of user.
      - Example of ldapTemplate.modifyAttributes and ModificationItem.
      remove This method is responsible to delete user.
      - Example of ldapTemplate.unbind().
      getAllUserNames This method is responsible to fetch all the user details as a list of String.
      - ldapTemplate.search() is used to search data.
      - Example of LdapQueryBuilder.
      getAllUsers This method is responsible to fetch all the user details as a list of User object.
      - ldapTemplate.search() is used to search data.
      - Example of SearchControls.
      getUserDetails This method is responsible to fetch user details of particular user as User Object.
      - Example of UserAttributesMapper.
      getUserDetail This method is responsible to fetch user details of particular user as a string.
      authenticate This method is responsible to authenticate user.
      - Example of ldapTemplate.authenticate().

      • Create class customize AttributesMapper name UserAttributesMapper and add following snippet.
            /**
             * This class is responsible to prepare User object after ldap search.
             *
             * @author KMaji
             *
             */
            private class UserAttributesMapper implements AttributesMapper<User> {
      
             @Override
             public User mapFromAttributes(Attributes attributes) throws NamingException {
              User user;
              if (attributes == null) {
               return null;
              }
              user = new User();
              user.setCn(attributes.get("cn").get().toString());
      
              if (attributes.get("userPassword") != null) {
               String userPassword = null;
               try {
                userPassword = new String((byte[]) attributes.get("userPassword").get(), "UTF-8");
               } catch (UnsupportedEncodingException e) {
                log.error("unable to process", e);
               }
               user.setUserPassword(userPassword);
              }
              if (attributes.get("uid") != null) {
               user.setUid(attributes.get("uid").get().toString());
              }
              if (attributes.get("sn") != null) {
               user.setSn(attributes.get("sn").get().toString());
              }
              if (attributes.get("postalAddress") != null) {
               user.setPostalAddress(attributes.get("postalAddress").get().toString());
              }
              if (attributes.get("telephoneNumber") != null) {
               user.setTelephoneNumber(attributes.get("telephoneNumber").get().toString());
              }
              return user;
             }
            }
      • Create class customize AttributesMapper name SingleAttributesMapper and add following snippet.
            /**
             * This class is responsible to print only cn .
             *
             * @author KMaji
             *
             */
            private class SingleAttributesMapper implements AttributesMapper<String> {
      
             @Override
             public String mapFromAttributes(Attributes attrs) throws NamingException {
              Attribute cn = attrs.get("cn");
              return cn.toString();
             }
            }
      • Create class customize AttributesMapper name MultipleAttributesMapper and add following snippet.
            /**
             * This class is responsible to print all the content in string format.
             *
             * @author KMaji
             *
             */
            private class MultipleAttributesMapper implements AttributesMapper<String> {
      
             @Override
             public String mapFromAttributes(Attributes attrs) throws NamingException {
              NamingEnumeration<? extends Attribute> all = attrs.getAll();
              StringBuffer result = new StringBuffer();
              result.append("\n Result { \n");
              while (all.hasMore()) {
               Attribute id = all.next();
               result.append(" \t |_  #" + id.getID() + "= [ " + id.get() + " ]  \n");
               log.info(id.getID() + "\t | " + id.get());
              }
              result.append("\n } ");
              return result.toString();
             }
            }
    12. Create spring bean configuration spring-ldap-example.xml in resource folder.
    13.       <?xml version="1.0" encoding="UTF-8"?>
            <!--
            #
            # Copyright © Kaustuv Maji , 2014
            # Repos - https://github.com/kaustuvmaji
            # Blog -  http://kaustuvmaji.blogspot.in
            #
            -->
            <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:p="http://www.springframework.org/schema/p"
                xmlns:ldap="http://www.springframework.org/schema/ldap"
                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/ldap
                     http://www.springframework.org/schema/ldap/spring-ldap.xsd
                     http://www.springframework.org/schema/context
                     http://www.springframework.org/schema/context/spring-context.xsd
                     http://www.springframework.org/schema/util
                     http://www.springframework.org/schema/util/spring-util.xsd">
      
             <context:component-scan base-package="ldap.advance.example" />
      
             <bean id="simpleDirContextAuthenticationStrategy" class="org.springframework.ldap.core.support.SimpleDirContextAuthenticationStrategy" />
      
             <bean id="userReposImpl" class="ldap.advance.example.UserRepositoryImpl" />
      
             <ldap:context-source url="ldap://localhost:10389"
                   base="dc=example,dc=com"
                   username="uid=admin,ou=system"
                   password="secret"
                   authentication-strategy-ref="simpleDirContextAuthenticationStrategy"
                   native-pooling="true"/>
      
             <!-- A bean identifier, used for referring to the bean elsewhere in the context. Default is "ldapTemplate". -->
             <ldap:ldap-template id="ldapTemplate"/>
            </beans>

    14. Create log4j.xml in resource folder and add following snippet.
    15.      <?xml version="1.0" encoding="UTF-8"?>
           <!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
           <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true">
      
            <!-- Appenders -->
            <appender name="console" class="org.apache.log4j.ConsoleAppender">
             <param name="Target" value="System.out" />
             <layout class="org.apache.log4j.PatternLayout">
              <param name="ConversionPattern" value="%d{ISO8601} %-5p %-1X{TID} %t [%c] %m%n" />
             </layout>
            </appender>
      
             <!-- Appenders -->
            <appender name="file" class="org.apache.log4j.RollingFileAppender">
             <param name="Threshold" value="ALL" />
             <param name="File" value="diag.log" />
             <param name="Append" value="true" />
             <param name="MaxFileSize" value="500000KB" />
             <param name="MaxBackupIndex" value="10" />
             <layout class="org.apache.log4j.PatternLayout">
              <param name="ConversionPattern" value="%d{ISO8601} %-5p %-1X{TID} %t [%c] %m%n" />
             </layout>
            </appender>
      
            <!-- Root Logger -->
            <root>
             <priority value="ALL" />
             <appender-ref ref="console" />
             <appender-ref ref="file" />
            </root>
      
           </log4j:configuration>

        Post Development testing


      Following class will be used to test spring ldap template examples.
           /**
            *
            * Copyright © Kaustuv Maji , 2014
            * Repos - https://github.com/kaustuvmaji
            * Blog -  http://kaustuvmaji.blogspot.in
            *
            */
           package ldap.advance.example.test;
      
           import java.util.Date;
      
           import ldap.advance.example.User;
           import ldap.advance.example.UserRepository;
      
           import org.apache.log4j.Logger;
           import org.springframework.context.support.AbstractApplicationContext;
           import org.springframework.context.support.ClassPathXmlApplicationContext;
      
           /**
            * @author KMaji
            *
            */
           public class LdapApp {
      
            private static Logger log = Logger.getLogger(LdapApp.class);
      
            static String username = "kaustuv";
      
            public static void main(String[] args) {
             AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-ldap-example.xml");
             log.info("Test started at "+new Date(context.getStartupDate()));
             UserRepository ldapDao = (UserRepository) context.getBean("userReposImpl");
             {
              // Create
              User user = new User();
              {
               user.setCn("spring_ldap_test");
               user.setSn("spring_ldap_test");
               user.setUid("spring_ldap_test");
               user.setPostalAddress("spring_ldap_test");
               user.setTelephoneNumber("9830098301");
               user.setUserPassword("spring_ldap_test");
              }
              log.info("\n =>" + ldapDao.createUser(user));
      
              // Read
              log.info("\n =>" + ldapDao.getAllUsers());
              log.info("\n =>" + ldapDao.getAllUserNames());
      
              context.refresh();
      
              log.info("\n =>" + ldapDao.getUserDetails("spring_ldap_test"));
              log.info("\n =>" + ldapDao.getUserDetail("spring_ldap_test"));
      
              // Update
              log.info("\n =>" + ldapDao.updateTelePhone("kaustuv", "9831198311"));
      
              // Delete
              log.info("\n =>" + ldapDao.remove("spring_ldap_test"));
             }
             context.registerShutdownHook();
             context.close();
            }
           }
    Click here to download source code of above example

    Source Code


    • References:
    Spring LDAP

    European Union laws require you to give European Union visitors information about cookies used on your blog. In many cases, these laws also require you to obtain consent.

    As a courtesy, we have added a notice on your blog to explain Google's use of certain Blogger and Google cookies, including use of Google Analytics and AdSense cookies.

    Thursday, 18 December 2014

    Simple example of data access with Spring Framework JDBC

    This Blog instruction will help us to access database for performing search, create, read, update and delete (SCRUD) using Spring framework JDBC.
  • Pre-requsite
  • Instructions assume that jdk is installed without any error.

  • Implemenation instructions
    1. Create a Simple spring project name. Following image will guide us. Add the required libraries in classpath.
    2. - mysql-connector-java-5.1.34.jar
      - spring-aop-4.1.3.RELEASE.jar
      - spring-beans-4.1.3.RELEASE.jar
      - spring-context-4.1.3.RELEASE.jar
      - spring-context-support-4.1.3.RELEASE.jar
      - spring-core-4.1.3.RELEASE.jar
      - spring-expression-4.1.3.RELEASE.jar
      - spring-jdbc-4.1.3.RELEASE.jar
      - spring-tx-4.1.3.RELEASE.jar
      - aopalliance-1.0.jar
      - log4j-1.2.14.jar
      - slf4j-jcl-1.7.5.jar

      Workspace will look like following.
    3. Create folder name resource and add in classpath. Create test_data.sql in resource folder and following snippet. This sql script is used to prepare test table and procedure.
    4.      -- #######################################
           -- Copyright © Kaustuv Maji , 2014
           -- Repos - https://github.com/kaustuvmaji
           -- Blog -  http://kaustuvmaji.blogspot.in
           -- #######################################
      
           DROP TABLE if exists `TEST`.`Member` ;
      
           COMMIT;
      
           CREATE TABLE `TEST`.`Member` (
              ID   INT NOT NULL AUTO_INCREMENT,
              NAME VARCHAR(20) NOT NULL,
              AGE  INT NOT NULL,
              PRIMARY KEY (ID)
           );
      
           COMMIT;
      
           SELECT * FROM `TEST`.`Member` ;
      
           DELIMITER //
      
           DROP PROCEDURE IF EXISTS `TEST`.`fetchRecord` //
           CREATE PROCEDURE `TEST`.`fetchRecord` (
           IN in_id INTEGER,
           OUT out_name VARCHAR(20),
           OUT out_age  INTEGER)
           BEGIN
              SELECT NAME, age
              INTO out_name, out_age
              FROM Member WHERE id = in_id;
           END //
      
           DELIMITER ;
      
           COMMIT;
    5. Create package spring.jdbc.template.example
    6. Create simple pojo class Member and following snippet.
    7.       /**
            *
            * Copyright © Kaustuv Maji , 2014
            * Repos - https://github.com/kaustuvmaji
            * Blog -  http://kaustuvmaji.blogspot.in
            *
            */
            package spring.jdbc.template.example;
      
            import java.io.Serializable;
      
            /**
             * @author KMaji
             *
             */
            public class Member implements Serializable {
      
             /**
              *
              */
             private static final long serialVersionUID = 8944832256293484687L;
      
      
             private String name;
             private Integer id;
             private Integer age;
      
             /**
              * Default constructor
              */
             public Member() {
      
             }
      
             /**
              * Constructor with argument
              * @param name
              * @param age
              */
             public Member(String name, Integer age) {
              super();
              this.name = name;
              this.age = age;
             }
      
             /**
              * @return the name
              */
             public final String getName() {
              return name;
             }
             /**
              * @param name the name to set
              */
             public final void setName(String name) {
              this.name = name;
             }
             /**
              * @return the id
              */
             public final Integer getId() {
              return id;
             }
             /**
              * @param id the id to set
              */
             public final void setId(Integer id) {
              this.id = id;
             }
             /**
              * @return the age
              */
             public final Integer getAge() {
              return age;
             }
             /**
              * @param age the age to set
              */
             public final void setAge(Integer age) {
              this.age = age;
             }
      
             /* (non-Javadoc)
              * @see java.lang.Object#toString()
              */
             @Override
             public String toString() {
              StringBuilder builder = new StringBuilder();
              builder.append("Member [");
              if (name != null)
               builder.append("name=").append(name).append(", ");
              if (id != null)
               builder.append("id=").append(id).append(", ");
              if (age != null)
               builder.append("age=").append(age);
              builder.append("]");
              return builder.toString();
             }
            }
    8. Create customize RowMapper implements RowMapper<Member> and add following snippet.
    9.       /**
            *
            * Copyright © Kaustuv Maji , 2014
            * Repos - https://github.com/kaustuvmaji
            * Blog -  http://kaustuvmaji.blogspot.in
            *
            */
            package spring.jdbc.template.example;
      
            import java.sql.ResultSet;
            import java.sql.SQLException;
      
            import org.springframework.jdbc.core.RowMapper;
      
            /**
             * This is custom row mapper for member class.
             * @author KMaji
             *
             */
            public class MemberMapper implements RowMapper {
      
             /**
              * (non-Javadoc)
              *
              * @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet,
              * int)
              */
             @Override
             public Member mapRow(ResultSet rs, int rowNum) throws SQLException {
              Member member = new Member();
              member.setId(rs.getInt("id"));
              member.setName(rs.getString("name"));
              member.setAge(rs.getInt("age"));
              return member;
             }
             
            }
    10. Create interface StudentDAOIntf and add following snippet.
    11. We will define all following methods to implements example of SCRUD functions.
            /**
            *
            * Copyright © Kaustuv Maji , 2014
            * Repos - https://github.com/kaustuvmaji
            * Blog -  http://kaustuvmaji.blogspot.in
            *
            */
            package spring.jdbc.template.example;
      
            import java.util.List;
      
      
            /**
             * This interface is used to show-case example of SCRUD.
             *
             * @author KMaji
             *
             */
            public interface MemberDAOIntf {
      
             /**
              * This is the method to be used to create a record in the Member table.
              */
             public void create(String name, Integer age);
      
             /**
              * This is the method to be used to list down a record from the Member
              * table corresponding to a passed member id.
              *
              * @return {@link Member}
              */
             public Member getMember(Integer id);
      
             /**
              * This is the method to be used to list down a record from the Member
              * table corresponding to a passed member id. print record as string
              *
              */
             public void getMemberAsString(Integer id);
      
             /**
              * This method is used to retrieve row set size.
              * @param sql
              * @return size of row set.
              */
             public int getRowSetSize(String sql);
      
             /**
              * This is the method to be used to list down all the records from the
              * Member table.
              *
              * @return List of {@link Member}
              */
             public List<Member> listMembers();
      
             /**
              * This is the method to be used to delete a record from the Member table
              * corresponding to a passed member id.
              */
             public void delete(Integer id);
      
             /**
              * This is the method to be used to update a record into the Member table.
              */
             public void update(Integer id, Integer age);
      
             /**
              * This method is example of inserting mass data in table.
              *
              * @param members
              */
             public void insertBatch(final List<Member> members);
      
             /**
              * This method is example of inserting mass data in table using sql.
              *
              * @param sql
              */
             public void batchSql(final String sql);
            }
    12. Create class StudentDAOImpl it implements interface StudentDAOIntf and add following snippet.
    13.       /**
             *
             * Copyright © Kaustuv Maji , 2014
             * Repos - https://github.com/kaustuvmaji
             * Blog -  http://kaustuvmaji.blogspot.in
             *
             */
            package spring.jdbc.template.example;
      
            import java.sql.PreparedStatement;
            import java.sql.SQLException;
            import java.util.List;
      
            import org.apache.log4j.Logger;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.jdbc.core.BatchPreparedStatementSetter;
            import org.springframework.jdbc.core.BeanPropertyRowMapper;
            import org.springframework.jdbc.core.JdbcTemplate;
            import org.springframework.stereotype.Component;
            import org.springframework.transaction.annotation.Transactional;
      
            /**
             * This class is used to show-case example of SCRUD functions. This class will
             * also show example of use spring jdbc batch functions.
             *
             * @author KMaji
             *
             */
            @Component
            public class MemberDAOImpl implements MemberDAOIntf {
      
             private static Logger log = Logger.getLogger(MemberDAOImpl.class);
      
             @Autowired
             private JdbcTemplate jdbcTemplate;
      
             @Autowired
             private MemberMapper memberMapper;
      
             /**
              *
              */
             public MemberDAOImpl() {
      
             }
      
             /**
              * (non-Javadoc)
              *
              * @see spring.jdbc.template.example.MemberDAOIntf#create(java.lang.String,
              *      java.lang.Integer)
              */
             @Override
             @Transactional
             public void create(String name, Integer age) {
              final String SQL = "insert into Member (name, age) values (?, ?)";
              // Issue a single SQL update operation (such as an insert, update or
              // delete statement) via a prepared statement, binding the given
              // arguments.
              jdbcTemplate.update(SQL, name, age);
              log.info("Created Record Name = " + name + " Age = " + age);
              return;
             }
      
             /**
              * (non-Javadoc)
              *
              * @see spring.jdbc.template.example.MemberDAOIntf#getMember(java.lang.Integer)
              */
             @Override
             @Transactional(readOnly = true)
             public Member getMember(Integer id) {
              String SQL = "select * from Member where id = ?";
              // Query given SQL to create a prepared statement from SQL and a list of
              // arguments to bind to the query, expecting a result object.
              Member member = jdbcTemplate.queryForObject(SQL, new Object[]{id}, memberMapper);
      
              return member;
             }
      
             /**
              * (non-Javadoc)
              *
              * @see spring.jdbc.template.example.MemberDAOIntf#listMembers()
              */
             @Override
             @Transactional
             public List<Member> listMembers() {
              String SQL = "select * from Member";
              // perfect example for BeanPropertyRowMapper <>
              List<Member> members = jdbcTemplate.query(SQL, new BeanPropertyRowMapper<Member>(Member.class));
              return members;
             }
      
             /**
              * (non-Javadoc)
              *
              * @see spring.jdbc.template.example.MemberDAOIntf#delete(java.lang.Integer)
              */
             @Override
             @Transactional
             public void delete(Integer id) {
              String SQL = "delete from Member where id = ?";
              // Issue a single SQL update operation (such as an insert, update or
              // delete statement) via a prepared statement, binding the given
              // arguments.
              jdbcTemplate.update(SQL, id);
              log.info("Deleted Record with ID = " + id);
              return;
             }
      
             /**
              * (non-Javadoc)
              *
              * @see spring.jdbc.template.example.MemberDAOIntf#update(java.lang.Integer,
              *      java.lang.Integer)
              */
             @Override
             @Transactional
             public void update(Integer id, Integer age) {
              String SQL = "update Member set age = ? where id = ?";
              // Issue a single SQL update operation (such as an insert, update or
              // delete statement) via a prepared statement, binding the given
              // arguments.
              jdbcTemplate.update(SQL, age, id);
              log.info("Updated Record with ID = " + id);
              return;
             }
      
             /**
              * (non-Javadoc)
              *
              * @see spring.jdbc.template.example.MemberDAOIntf#getMemberAsString(java.lang.
              *      Integer)
              */
             @Override
             @Transactional(readOnly = true)
             public void getMemberAsString(Integer id) {
              String SQL = "select NAME from Member where id = ?";
              log.info(jdbcTemplate.queryForObject(SQL, new Object[]{id}, String.class));
             }
      
             /**
              * (non-Javadoc)
              *
              * @see spring.jdbc.template.example.MemberDAOIntf#insertBatch(java.util.List)
              */
             @Override
             public void insertBatch(final List<Member> members) {
              String sql = "INSERT INTO Member " + "( NAME, AGE) VALUES ( ?, ?)";
              // Issue multiple update statements on a single PreparedStatement, using
              // batch updates and a BatchPreparedStatementSetter to set values.
              jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
      
               @Override
               public void setValues(PreparedStatement ps, int arg1) throws SQLException {
                Member member = members.get(arg1);
                ps.setString(1, member.getName());
                ps.setInt(2, member.getAge());
               }
      
               @Override
               public int getBatchSize() {
                return members.size();
               }
              });
      
             }
      
             /**
              * (non-Javadoc)
              *
              * @see spring.jdbc.template.example.MemberDAOIntf#batchSql(java.lang.String)
              */
             @Override
             public void batchSql(final String sql) {
              // Issue multiple SQL updates on a single JDBC Statement using batching.
              jdbcTemplate.batchUpdate(new String[]{sql});
             }
      
             /**
              * (non-Javadoc)
              *
              * @see spring.jdbc.template.example.MemberDAOIntf#getRowSetSize(java.lang.String
              *      )
              */
             @Override
             public int getRowSetSize(String sql) {
              @SuppressWarnings("deprecation")
              // Query given SQL to create a prepared statement from SQL and a list of
              // arguments to bind to the query, resulting in an int value.
              int total = jdbcTemplate.queryForInt(sql);
              return total;
             }
            }
      • Following table will explain the methods that used to SCRUD functionalities.

      Methods name Description
      create This method is used to create a record in the Member table.
      - jdbcTemplate.update() is used to insert data into member table.
      - @Transactional is used to identify this method transaction enable.
      update This method is used to update a record into the Member table.
      - jdbcTemplate.update() is used to update data into member table based on given id.
      - @Transactional is used to identify this method transaction enable.
      delete This method is used to delete a record from the Member table, corresponding to a passed member id.
      - jdbcTemplate.update() is used to delete data into member table based on given id.
      - @Transactional is used to identify this method transaction enable.
      listMembers This method is used to fetch all the records from the Member table.
      This is example of classic select * from.
      - Example of BeanPropertyRowMapper<T>
      getMember This method is used to fetch member details(Member Object) information corresponding to a passed member id.
      - jdbcTemplate.queryForObject() is used to fetch data.
      - Example of customize RowMapper<T>.
      getMemberAsString This method is used to fetch member details(String Object) information corresponding to a passed member id.
      - jdbcTemplate.queryForObject() is used to fetch data.
      getRowSetSize This method is used to retrieve size table.
      - jdbcTemplate.queryForInt () is fetch the data

      • Following table will explain the methods that used to batch functionalities.
      Methods name Description
      insertBatch This method is used to create huge number of record in the Member table.
      - jdbcTemplate.batchUpdate() is used to insert data into member table.
      batchSql This method is example of inserting huge number of data in table using sql query.

    14. Create class MemberStoredProcedureDAOImpl and add following snippet.
    15.       /**
            *
            * Copyright © Kaustuv Maji , 2014
            * Repos - https://github.com/kaustuvmaji
            * Blog -  http://kaustuvmaji.blogspot.in
            *
            */
            package spring.jdbc.template.example;
      
            import java.util.Map;
      
            import javax.sql.DataSource;
      
            import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
            import org.springframework.jdbc.core.namedparam.SqlParameterSource;
            import org.springframework.jdbc.core.simple.SimpleJdbcCall;
      
            /**
             * This class is used to show-case example of calling stored procedure.
             *
             * @author kmaji
             *
             */
            public class MemberStoredProcedureDAOImpl {
      
             private DataSource dataSource;
      
             private SimpleJdbcCall jdbcCall;
      
             /**
              * Example of calling stored procedure.
              *
              * @param id
              * @return
              */
             public Member getMembers(Integer id) {
                SqlParameterSource in = new MapSqlParameterSource().
                      addValue("in_id", id);
      
                Map<String, Object> out = jdbcCall.execute(in);
      
                Member member = new Member();
                member.setId(id);
                member.setName((String) out.get("out_name"));
                member.setAge((Integer) out.get("out_age"));
      
                return member;
                }
      
             /**
              * Setter method for datasource and {@link SimpleJdbcCall}.
              *
              * @param dataSource
              */
               public void setDataSource(DataSource dataSource) {
                this.jdbcCall =  new SimpleJdbcCall(dataSource).
                     withProcedureName("fetchRecord");
                }
            }
    16. Create spring bean configuration Beans.xml in resource folder.
    17.       <?xml version="1.0" encoding="UTF-8"?>
            <!--
            #
            # Copyright © Kaustuv Maji , 2014
            # Repos - https://github.com/kaustuvmaji
            # Blog -  http://kaustuvmaji.blogspot.in
            #
            -->
            <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:c="http://www.springframework.org/schema/c"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xmlns:jdbc="http://www.springframework.org/schema/jdbc"
             xmlns:jee="http://www.springframework.org/schema/jee"
             xmlns:p="http://www.springframework.org/schema/p"
             xmlns:repository="http://www.springframework.org/schema/data/repository"
             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/jdbc
                  http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
                  http://www.springframework.org/schema/jee
                  http://www.springframework.org/schema/jee/spring-jee.xsd
                  http://www.springframework.org/schema/tx
                  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                  http://www.springframework.org/schema/data/repository
                  http://www.springframework.org/schema/data/repository/spring-repository.xsd">
             <!--
              Scans the classpath for annotated components that will be auto-registered as
              Spring beans. By default, the Spring-provided @Component, @Repository,
              @Service, and @Controller stereotypes will be detected.
              Here in base-package section I mentioned spring.jdbc.template.example
             -->
             <context:component-scan base-package="spring.jdbc.template.example" />
      
             <!--
              Indicates whether the implicit annotation post-processors should be enabled.
              Default is "true".
              -->
             <context:annotation-config/>
      
             <!--
              This bean is used to load properties files.
             -->
             <bean id="propLoader"
              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
              <property name="locations">
               <list>
                <value>
                 file:#{ systemEnvironment['config.dir'] }/db.properties
                </value>
               </list>
              </property>
             </bean>
      
             <!--
              This bean is used to connect mySql database.
             -->
             <bean id="dataSource"
              class="org.springframework.jdbc.datasource.DriverManagerDataSource"
              p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
              p:username="${jdbc.username}" p:password="${jdbc.password}" />
      
             <!-- Database script execution maybe we can use it for embed schema -->
             <!--
             <jdbc:initialize-database data-source="dataSource">
              <jdbc:script location="classpath:test-data_1.sql" />
             </jdbc:initialize-database>
             -->
      
             <!-- this beans is going to manage transaction -->
             <bean id="transactionManager"
              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
              <property name="dataSource" ref="dataSource" />
             </bean>
      
             <tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />
      
             <!--
               It simplifies the use of JDBC and helps to avoid common errors.
               It executes core JDBC workflow, leaving application code to
               provide SQL and extract results. This class executes SQL queries or updates,
               initiating iteration over ResultSets and catching JDBC exceptions and
               translating them to the generic, more informative exception hierarchy
               defined in the org.springframework.dao package.
             -->
             <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
              p:dataSource-ref="dataSource" />
      
             <bean id="memberMapper" class="spring.jdbc.template.example.MemberMapper" />
      
             <bean id="memberJDBCTemplate" class="spring.jdbc.template.example.MemberDAOImpl" />
      
             <bean id="memberJDBCImpl" class="spring.jdbc.template.example.MemberStoredProcedureDAOImpl" p:dataSource-ref="dataSource" />
      
            </beans>

      • propLoader bean (org.springframework.beans.factory.config.PropertyPlaceholderConfigurer) is used to load n number of properties file. In following example I mentioned only one file (db.properties) within <value> under <list> . Please not that in path section config.dir is a system Environment. In default scenario spring can read system variable all we need to do where we are mentioning system envrionment we have to mention it in following syntactical way.
        a) for system variable #{ systemEnvironment['<environment variable name>'] } .
        b) for system properties #{ systemProperties['<property variable name>'] } .
             <!--
              This bean is used to load properties files.
             -->
             <bean id="propLoader"
              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
              <property name="locations">
               <list>
                <!-- Mention n number of file paths-->
                <value>
                 file:#{ systemEnvironment['config.dir'] }/db.properties
                </value>
               </list>
              </property>
             </bean>

      • Create db.properties in any location and set environment variable config.dir = "location".

            jdbc.driverClassName=com.mysql.jdbc.Driver
            jdbc.url=jdbc:mysql://localhost/test
            jdbc.username=root
            jdbc.password=

      • Following part is important for creating datasource and jdbcTemplate instances that is used in MemberDAOImpl.
             <!--
              This bean is used to connect mySql database.
             -->
             <bean id="dataSource"
              class="org.springframework.jdbc.datasource.DriverManagerDataSource"
              p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
              p:username="${jdbc.username}" p:password="${jdbc.password}" />
      
             <!-- Database script execution maybe we can use it for embed schema -->
             <!--
             <jdbc:initialize-database data-source="dataSource">
              <jdbc:script location="classpath:test-data_1.sql" />
             </jdbc:initialize-database>
             -->
             lt;!--
               It simplifies the use of JDBC and helps to avoid common errors.
               It executes core JDBC workflow, leaving application code to
               provide SQL and extract results. This class executes SQL queries or updates,
               initiating iteration over ResultSets and catching JDBC exceptions and
               translating them to the generic, more informative exception hierarchy
               defined in the org.springframework.dao package.
             -->
             <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
              p:dataSource-ref="dataSource" />

      • Following part is important for enable @Transactional that is used in MemberDAOImpl.
             <!-- this beans is going to manage transaction -->
             <bean id="transactionManager"
              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
              <property name="dataSource" ref="dataSource" />
             </bean>
      
             <tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />

    18. Create log4j.xml in resource folder and add following snippet.
    19.      <?xml version="1.0" encoding="UTF-8"?>
           <!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
           <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true">
      
            <!-- Appenders -->
            <appender name="console" class="org.apache.log4j.ConsoleAppender">
             <param name="Target" value="System.out" />
             <layout class="org.apache.log4j.PatternLayout">
              <param name="ConversionPattern" value="%d{ISO8601} %-5p %-1X{TID} %t [%c] %m%n" />
             </layout>
            </appender>
      
             <!-- Appenders -->
            <appender name="file" class="org.apache.log4j.RollingFileAppender">
             <param name="Threshold" value="ALL" />
             <param name="File" value="diag.log" />
             <param name="Append" value="true" />
             <param name="MaxFileSize" value="500000KB" />
             <param name="MaxBackupIndex" value="10" />
             <layout class="org.apache.log4j.PatternLayout">
              <param name="ConversionPattern" value="%d{ISO8601} %-5p %-1X{TID} %t [%c] %m%n" />
             </layout>
            </appender>
      
            <!-- Root Logger -->
            <root>
             <priority value="ALL" />
             <appender-ref ref="console" />
             <appender-ref ref="file" />
            </root>
      
           </log4j:configuration>

        Post Development testing


      Following class will be used to test spring jdbc template examples.
           /**
            *
            * Copyright © Kaustuv Maji , 2014
            * Repos - https://github.com/kaustuvmaji
            * Blog -  http://kaustuvmaji.blogspot.in
            *
            */
           package spring.jdbc.template.example;
      
           import java.util.ArrayList;
           import java.util.List;
      
           import org.apache.log4j.Logger;
           import org.springframework.context.support.AbstractApplicationContext;
           import org.springframework.context.support.ClassPathXmlApplicationContext;
      
           /**
            * @author KMaji
            *
            */
           public class ExampleApp {
      
            private static Logger log = Logger.getLogger(ExampleApp.class);
      
            /**
             *
             */
            static {
             // System.out.println(System.getenv());
            }
      
            /**
             * @param args
             */
            public static void main(String... args) {
      
             @SuppressWarnings("resource")
             AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml", ExampleApp.class);
      
             MemberDAOIntf memberDaoImpl = null;
      
             if (context.containsBean("memberJDBCTemplate")) {
              memberDaoImpl = (MemberDAOIntf) context.getBean("memberJDBCTemplate");
             }
      
             MemberStoredProcedureDAOImpl sspDao = null;
      
             if (context.containsBean("memberJDBCImpl")) {
              sspDao = (MemberStoredProcedureDAOImpl) context.getBean("memberJDBCImpl");
             }
      
             log.info(memberDaoImpl.getRowSetSize("select COUNT(*) from Member"));
      
             {
              // SCRUD Example.
              {
               // Create
               log.info("{Executing} ------Records Creation--------");
               memberDaoImpl.create("member_1", 11);
               memberDaoImpl.create("member_2", 2);
               memberDaoImpl.create("member_3", 15);
              }
      
              {
               // Retrieve
               log.info("{Executing} ------Listing Multiple Records--------");
               List<Member> members = memberDaoImpl.listMembers();
               for (Member record : members) {
                log.info("ID : " + record.getId() + " , Name : " + record.getName() + " , Age : " + record.getAge());
               }
      
               log.info("{Executing} ----Listing Record with ID = 3 -----");
               Member member = memberDaoImpl.getMember(3);
               log.info("ID : " + member.getId() + " , Name : " + member.getName() + " , Age : " + member.getAge());
      
               memberDaoImpl.getMemberAsString(3);
              }
      
              {
               // Update
               log.info("{Executing} ---- Updating Record with ID = 3 -----");
               memberDaoImpl.update(3, 20);
              }
      
              {
               // Delete
               log.info("{Executing} ---- Deleting Record with ID = 2 -----");
               memberDaoImpl.delete(2);
               log.info("Deleted member with " + "ID : ");
              }
             }
      
             {
              // Batch Example
              {
               // Insert
               log.info("{Executing} ---- Records Creation as a batch process -----");
               List<Member> members = new ArrayList<>();
               for (int i = 0; i < 10; i++) {
                members.add(new Member("member_batch_" + i, i * 5));
               }
               memberDaoImpl.insertBatch(members);
               log.info(memberDaoImpl.listMembers());
              }
      
              {
               // Update
               log.info("{Executing} ---- Records update as a batch process -----");
               memberDaoImpl.batchSql("UPDATE Member SET NAME ='Mary' where AGE > 35");
               log.info(memberDaoImpl.listMembers());
      
              }
             }
      
             {
              // calling stored procedure
              log.info("{Executing} ---- Records according to stored procedure -----");
              log.info(sspDao.getMembers(3));
             }
      
             // register shutdownhook
             context.registerShutdownHook();
            }
           }
    Click here to download source code of above example

    Source Code


    • References:
    Data access with Spring framework JDBC

    European Union laws require you to give European Union visitors information about cookies used on your blog. In many cases, these laws also require you to obtain consent.

    As a courtesy, we have added a notice on your blog to explain Google's use of certain Blogger and Google cookies, including use of Google Analytics and AdSense cookies.