Search This Blog

Thursday, July 23, 2020

Spring 4 JdbcTemplate Annotation with Example

 In this tutorial, we will learn how to connect to the database and execute CRUD SQL queries using Spring 4 JdbcTemplate. Java base configuration is used to load the JdbcTemplate, here we are not using XML base configuration for JdbcTemplate.

Spring 4 jdbctemplate annotation example eclipse project setup

Tools and Technologies

  1. Apache Maven 3.0.4
  2. JDK 1.8
  3. Spring core, Spring webmvc and Spring context (4.1.4.RELEASE)
  4. mysql(5.1.31)

Database table

Use below SQL script to create "trn_person" table in the database.

  1. CREATE TABLE `technicalkeeda`.`trn_person` (
  2. `person_id` int(10) unsigned NOT NULL auto_increment,
  3. `first_name` varchar(45) collate latin1_general_ci NOT NULL,
  4. `last_name` varchar(45) collate latin1_general_ci NOT NULL,
  5. `age` int(10) unsigned NOT NULL,
  6. PRIMARY KEY USING BTREE (`person_id`)
  7. ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

pom.xml

As we are using Maven project. Let's define the spring 4 specific maven dependencies.

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  2. <modelVersion>4.0.0</modelVersion>
  3. <groupId>com.technicalkeeda</groupId>
  4. <artifactId>Spring4Examples</artifactId>
  5. <packaging>jar</packaging>
  6. <version>1.0</version>
  7. <name>Spring4Examples</name>
  8. <description></description>
  9. <build>
  10. <plugins>
  11. <plugin>
  12. <artifactId>maven-compiler-plugin</artifactId>
  13. <configuration>
  14. <source>1.8</source>
  15. <target>1.8</target>
  16. </configuration>
  17. </plugin>
  18. </plugins>
  19. </build>
  20.  
  21. <properties>
  22. <spring.version>4.1.4.RELEASE</spring.version>
  23. </properties>
  24.  
  25. <dependencies>
  26.  
  27. <dependency>
  28. <groupId>org.springframework</groupId>
  29. <artifactId>spring-core</artifactId>
  30. <version>${spring.version}</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework</groupId>
  34. <artifactId>spring-context</artifactId>
  35. <version>${spring.version}</version>
  36. </dependency>
  37.  
  38. <dependency>
  39. <groupId>org.springframework</groupId>
  40. <artifactId>spring-context-support</artifactId>
  41. <version>${spring.version}</version>
  42. </dependency>
  43.  
  44. <dependency>
  45. <groupId>org.springframework</groupId>
  46. <artifactId>spring-jdbc</artifactId>
  47. <version>${spring.version}</version>
  48. </dependency>
  49.  
  50. <dependency>
  51. <groupId>mysql</groupId>
  52. <artifactId>mysql-connector-java</artifactId>
  53. <version>5.1.31</version>
  54. </dependency>
  55.  
  56.  
  57. </dependencies>
  58. </project>

Person Pojo

This is simple Person pojo class which contains different attributes like personId, firstName, lastName and age.

  1. package com.technicalkeeda.bean;
  2.  
  3. public class Person {
  4.  
  5. private int personId;
  6. private String firstName;
  7. private String lastName;
  8. private int age;
  9.  
  10. public Person() {
  11.  
  12. }
  13.  
  14. public Person(int personId, String firstName, String lastName, int age) {
  15. super();
  16. this.personId = personId;
  17. this.firstName = firstName;
  18. this.lastName = lastName;
  19. this.age = age;
  20. }
  21.  
  22. public int getPersonId() {
  23. return personId;
  24. }
  25.  
  26. public void setPersonId(int personId) {
  27. this.personId = personId;
  28. }
  29.  
  30. public String getFirstName() {
  31. return firstName;
  32. }
  33.  
  34. public void setFirstName(String firstName) {
  35. this.firstName = firstName;
  36. }
  37.  
  38. public String getLastName() {
  39. return lastName;
  40. }
  41.  
  42. public void setLastName(String lastName) {
  43. this.lastName = lastName;
  44. }
  45.  
  46. public int getAge() {
  47. return age;
  48. }
  49.  
  50. public void setAge(int age) {
  51. this.age = age;
  52. }
  53.  
  54. @Override
  55. public String toString() {
  56. StringBuilder builder = new StringBuilder();
  57. builder.append("Person Id:- " + getPersonId() + " First Name:- " + getFirstName() + " Last Name:- " +
  58. getLastName() + " Age:- " + getAge());
  59. return builder.toString();
  60. }
  61.  
  62. }

application.properties

Create "application.properties" file under /resources folder. Define data source configuration properties like jdbc driverClassName, url, username and password.

  1. jdbc.driverClassName=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/technicalkeeda
  3. jdbc.username=root
  4. jdbc.password=

Spring 4 Application Configuration

@Configuration annotation imports the Spring configuration. @Configuration objects are managed as Spring beans within the container, imported configurations are used to injected using @Autowired or @Inject.

@ComponentScan is equivalent to <context:component-scan base-package="..." used to lookup the beans and components classes in the spring context.

@PropertySource Annotation use to provide a convenient and declarative mechanism for adding a PropertySource to Spring's Environment.

To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory. Here we have registered JdbcTemplate and DataSource beans.

  1. package com.technicalkeeda.configuration;
  2.  
  3. import javax.sql.DataSource;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.ComponentScan;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.context.annotation.PropertySource;
  10. import org.springframework.core.env.Environment;
  11. import org.springframework.jdbc.core.JdbcTemplate;
  12. import org.springframework.jdbc.datasource.DriverManagerDataSource;
  13.  
  14. @Configuration
  15. @ComponentScan(basePackages = "com.technicalkeeda")
  16. @PropertySource(value = { "classpath:application.properties" })
  17. public class ApplicationConfig {
  18.  
  19. @Autowired
  20. private Environment env;
  21.  
  22. @Bean
  23. public DataSource dataSource() {
  24. DriverManagerDataSource dataSource = new DriverManagerDataSource();
  25. dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName"));
  26. dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
  27. dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
  28. dataSource.setPassword(env.getRequiredProperty("jdbc.password"));
  29. return dataSource;
  30. }
  31.  
  32. @Bean
  33. public JdbcTemplate jdbcTemplate(DataSource dataSource) {
  34. JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
  35. jdbcTemplate.setResultsMapCaseInsensitive(true);
  36. return jdbcTemplate;
  37. }
  38.  
  39. }

PersonService Interface

Creates PersonService interface along with CRUD methods.

  1. Create new Person entity.
  2. Edit Person entity.
  3. Delete Person entity.
  4. Returns Person entity identified by the given id.
  5. Returns all Person entities
  1. package com.technicalkeeda.services;
  2.  
  3. import java.util.List;
  4.  
  5. import com.technicalkeeda.bean.Person;
  6.  
  7. public interface PersonService {
  8.  
  9. public void addPerson(Person person);
  10.  
  11. public void editPerson(Person person, int personId);
  12.  
  13. public void deletePerson(int personId);
  14.  
  15. public Person find(int personId);
  16.  
  17. public List < Person > findAll();
  18. }

PersonService Implementation

Mark PersonServiceImpl class as "personService" using @Service annotation. Use @Autowired annotation to autowire PersonDao bean.

  1. package com.technicalkeeda.services;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7.  
  8. import com.technicalkeeda.bean.Person;
  9. import com.technicalkeeda.dao.PersonDao;
  10.  
  11. @Service("personService")
  12. public class PersonServiceImpl implements PersonService {
  13.  
  14. @Autowired
  15. PersonDao personDao;
  16.  
  17. public void addPerson(Person person) {
  18. personDao.addPerson(person);
  19.  
  20. }
  21.  
  22. public void editPerson(Person person, int personId) {
  23. personDao.editPerson(person, personId);
  24. }
  25.  
  26. public void deletePerson(int personId) {
  27. personDao.deletePerson(personId);
  28. }
  29.  
  30. public Person find(int personId) {
  31. return personDao.find(personId);
  32. }
  33.  
  34. public List < Person > findAll() {
  35. return personDao.findAll();
  36. }
  37. }

PersonDao Interface

Creates PersonDao interface.

  1. package com.technicalkeeda.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import com.technicalkeeda.bean.Person;
  6.  
  7. public interface PersonDao {
  8.  
  9. public void addPerson(Person person);
  10.  
  11. public void editPerson(Person person, int personId);
  12.  
  13. public void deletePerson(int personId);
  14.  
  15. public Person find(int personId);
  16.  
  17. public List < Person > findAll();
  18. }

PersonDao implementation

PersonDaoImpl marked with @Repository annotation, It allows the component scanning to find and configure the respected DAO. @Autowired JdbcTemplate to access to a persistence resource.

  1. package com.technicalkeeda.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  8. import org.springframework.jdbc.core.JdbcTemplate;
  9. import org.springframework.stereotype.Repository;
  10.  
  11. import com.technicalkeeda.bean.Person;
  12.  
  13. @Repository
  14. @Qualifier("personDao")
  15. public class PersonDaoImpl implements PersonDao {
  16.  
  17. @Autowired
  18. JdbcTemplate jdbcTemplate;
  19.  
  20. public void addPerson(Person person) {
  21. jdbcTemplate.update("INSERT INTO trn_person (person_id, first_name, Last_name, age) VALUES (?, ?, ?, ?)",
  22. person.getPersonId(), person.getFirstName(), person.getLastName(), person.getAge());
  23. System.out.println("Person Added!!");
  24. }
  25.  
  26. public void editPerson(Person person, int personId) {
  27. jdbcTemplate.update("UPDATE trn_person SET first_name = ? , last_name = ? , age = ? WHERE person_id = ? ",
  28. person.getFirstName(), person.getLastName(), person.getAge(), personId);
  29. System.out.println("Person Updated!!");
  30. }
  31.  
  32. public void deletePerson(int personId) {
  33. jdbcTemplate.update("DELETE from trn_person WHERE person_id = ? ", personId);
  34. System.out.println("Person Deleted!!");
  35. }
  36.  
  37. public Person find(int personId) {
  38. Person person = (Person) jdbcTemplate.queryForObject("SELECT * FROM trn_person where person_id = ? ",
  39. new Object[] { personId }, new BeanPropertyRowMapper(Person.class));
  40.  
  41. return person;
  42. }
  43.  
  44. public List < Person > findAll() {
  45. List < Person > persons = jdbcTemplate.query("SELECT * FROM trn_person", new BeanPropertyRowMapper(Person.class));
  46. return persons;
  47. }
  48. }

App.java

To create standalone Spring Application Context, We are using AnnotationConfigApplicationContext which helps to register all the beans generated by the configuration class (@Configuration) at Spring runtime.

Use AbstractApplicationContext.getBean(String name) method is used to get bean object( "personService") from Spring application context.

Once you get the "personService" instance perform different CRUD operations.

  1. package com.technicalkeeda.test;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  6. import org.springframework.context.support.AbstractApplicationContext;
  7.  
  8. import com.technicalkeeda.bean.Person;
  9. import com.technicalkeeda.configuration.ApplicationConfig;
  10. import com.technicalkeeda.services.PersonService;
  11.  
  12. public class App {
  13.  
  14. public static void main(String args[]) {
  15.  
  16. AbstractApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
  17. PersonService personService = (PersonService) context.getBean("personService");
  18.  
  19. Person yashwant = new Person(1, "Yashwant", "Chavan", 32);
  20. Person mahesh = new Person(2, "Mahesh", "Patil", 25);
  21. Person vishal = new Person(3, "Vishal", "Naik", 40);
  22.  
  23. personService.addPerson(yashwant);
  24. personService.addPerson(mahesh);
  25. personService.addPerson(vishal);
  26.  
  27. System.out.println("Find All");
  28. List < Person > persons = personService.findAll();
  29. for (Person person: persons) {
  30. System.out.println(person);
  31. }
  32.  
  33. System.out.println("Delete person Id = 3");
  34. int deleteMe = 3;
  35. personService.deletePerson(deleteMe);
  36.  
  37. yashwant.setFirstName("Yashwant - Updated");
  38. yashwant.setLastName("Chavan - Updated");
  39. yashwant.setAge(40);
  40.  
  41. System.out.println("Update person Id = 1");
  42. int updateMe = 1;
  43. personService.editPerson(yashwant, updateMe);
  44.  
  45. System.out.println("Find person Id = 2");
  46. Person person = personService.find(2);
  47. System.out.println(person);
  48.  
  49. System.out.println("Find All Again");
  50. persons = personService.findAll();
  51. for (Person p: persons) {
  52. System.out.println(p);
  53. }
  54.  
  55. context.close();
  56. }
  57.  
  58. }

Output

  1. Dec 12, 2016 8:06:19 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
  2. INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@3d646c37: startup date [Mon Dec 12 20:06:19 IST 2016]; root of context hierarchy
  3. Dec 12, 2016 8:06:19 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
  4. INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
  5.  
  6. Person Added!!
  7. Person Added!!
  8. Person Added!!
  9.  
  10. Find All
  11. Person Id:- 1 First Name:- Yashwant Last Name:- Chavan Age:- 32
  12. Person Id:- 2 First Name:- Mahesh Last Name:- Patil Age:- 25
  13. Person Id:- 3 First Name:- Vishal Last Name:- Naik Age:- 40
  14.  
  15. Delete person Id = 3
  16. Person Deleted!!
  17.  
  18. Update person Id = 1
  19. Person Updated!!
  20.  
  21. Find person Id = 2
  22. Person Id:- 2 First Name:- Mahesh Last Name:- Patil Age:- 25
  23.  
  24. Find All Again
  25. Person Id:- 1 First Name:- Yashwant - Updated Last Name:- Chavan - Updated Age:- 40
  26. Person Id:- 2 First Name:- Mahesh Last Name:- Patil Age:- 25
  27.  
  28. Dec 12, 2016 8:06:20 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
  29. INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@3d646c37: startup date [Mon Dec 12 20:06:19 IST 2016]; root of context hierarchy

No comments:

Post a Comment