"Welcome To Ashok IT" "Spring Boot and MicroServices" Topic : Spring Boot - Layered Application Date : 25/09/2024 (Session - 32) _____________________________________________________________________________________________________________________________ Today Session: NamedParameterJdbcTemplate ========================================= * NamedParameterJdbcTemplate is used to perform the Database Operation through DAO Class. * While working with NamedParameterJdbcTemplate we need to pass the dynamic values to SQL Query using "Named Parameters". * Named Parameters are always represented by ":,:...." EmployeeDao.java ================ package com.ashokit.dao; import java.util.List; import java.util.Map; import com.ashokit.model.Employee; public interface EmployeeDao { //creating the new employee public boolean createNewEmployee(Employee emp); //creating the employees based on List public int creatNewEmployees(List employees); //creating the new employee with NamedParameterJdbcTemplate public boolean createNewEmployeeWithNamedParameterJdbcTemplate(Employee emp); //Performing the select Queries public Map findEmployeeById(int employeeId); public List findAllEmployees(); } EmployeeDaoImpl.java ==================== package com.ashokit.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import com.ashokit.model.Employee; @Repository public class EmployeeDaoImpl implements EmployeeDao { //Will be getting as spring bean through Auto-configuration @Autowired private JdbcTemplate jdbcTemplate; @Autowired private DataSource datasource; @Autowired private NamedParameterJdbcTemplate namedParameterJdbcTemplate; @Override public boolean createNewEmployee(Employee emp) { System.out.println("DataSource Implementation class...." + datasource.getClass().getName()); int rowCount = jdbcTemplate.update("insert into ashokit_employees values(?,?,?)", emp.getEmployeeId(),emp.getEmployeeName(),emp.getEmailId()); //If row inserted successful means will return true otherwise will return as false return rowCount > 0; } @Override public int creatNewEmployees(List employees) { System.out.println("DataSource Implementation class...." + datasource.getClass().getName()); int rowCount=0; for(Employee emp : employees) { rowCount += jdbcTemplate.update("insert into ashokit_employees values(?,?,?)", emp.getEmployeeId(),emp.getEmployeeName(),emp.getEmailId()); } System.out.println("Row Count Checking Variable ::::::" + rowCount); return rowCount; } @Override public boolean createNewEmployeeWithNamedParameterJdbcTemplate(Employee emp) { //Passing the NamedParameters values as Map Object Map employeeMap = new HashMap<>(); employeeMap.put("empId",emp.getEmployeeId()); employeeMap.put("empName",emp.getEmployeeName()); employeeMap.put("emailId",emp.getEmailId()); //passing employeeMap object to update(); int rowCount = namedParameterJdbcTemplate.update("insert into ashokit_employees values(:empId,:empName,:emailId)", employeeMap); return rowCount > 0; } @Override public Map findEmployeeById(int employeeId) { Map employeeInfo = jdbcTemplate.queryForMap("select * from ashokit_employees where employee_id=?",employeeId); return employeeInfo; } @Override public List findAllEmployees() { List employees = jdbcTemplate.query("select * from ashokit_employees",(resultSet,rowNumber)->{ System.out.println("Executing Each Row...."); Employee emp = new Employee(); emp.setEmployeeId(resultSet.getInt(1)); emp.setEmployeeName(resultSet.getString(2)); emp.setEmailId(resultSet.getString(3)); return emp; }); return employees; } } Application.java ================ package com.ashokit; import java.util.List; import java.util.Map; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import com.ashokit.controller.EmployeeController; import com.ashokit.dao.EmployeeDao; import com.ashokit.model.Employee; import com.ashokit.util.EmployeeUtils; @SpringBootApplication public class Application { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); //getting the Spring Bean objects EmployeeController ec = context.getBean(EmployeeController.class); EmployeeUtils emputils = context.getBean(EmployeeUtils.class); List employees = emputils.getAllEmployeeInfo(); //calling the controller class method //ec.addingNewEmployee(employees.get(0)); //calling the controller class method to test list of employees creating //ec.addingNewEmployees(emputils.getAllEmployeeInfo()); //Testing NamedParameterJdbcTemplate Logic EmployeeDao employeeDao = context.getBean(EmployeeDao.class); Employee emp = new Employee(2255,"Raghu","raghu@gmail.com"); boolean empcreatedStatus = employeeDao.createNewEmployeeWithNamedParameterJdbcTemplate(emp); if(empcreatedStatus) { System.out.println("Record Inserted...."); }else { System.out.println("Record Not Inserted....."); } //Getting the Employee information Map employeeInfo = employeeDao.findEmployeeById(1234); System.out.println(employeeInfo); //Getting All the Employees List allEmployees = employeeDao.findAllEmployees(); System.out.println(allEmployees); } } IIQ) Differences between JdbcTemplate class Vs NamedParameterJdbcTemplate class? JdbcTemplate class ================== 1) In JdbcTemplate class the dynamic values to sql query are passed through Indexed parameters/Positional parameters (?). 2) In JdbcTemplate class the values for Indexed parameters/positional parameters always should be passed either in Object[] or Object ... Ex:jdbcTemplate.update("insert into ashokit_emps values(?,?,?)", new Object[]{empId,empName,empLocation}); >>>>>>> Object[] jdbcTemplate.update("insert into ashokit_emps values(?,?,?)",empId,empName,empLocation); >>>>>>> Object ... 3) Injecting the Datasource object either can use setter/constructor injection in JdbcTemplate class. NamedParameterJdbcTemplate class ================================ 1) In NamedParameterJdbcTemplate class the dynamic values to sql query is passed through named parameters(:sid). 2) In NamedParameterJdbcTemplate class the values for named parameter with help of Map object & SqlParameterSource interface implementation classes. 3) Injecting the Datasource object must be constructor injection. Spring Boot Profiles ==================== * Spring Boot Profiles are a feature provided by the Spring Framework and Spring Boot that allows you to define and configure application environments for different deployment scenarios. * Profiles help you customize the behavior of your Spring Boot application based on the specific environment it is running in,such as development, production, testing, or any other custom profile you define. * With profiles, you can have different configurations, beans, and properties activated based on the active profile. This allows you to keep your application codebase unchanged while providing different settings and behaviors depending on the deployment environment. * Here's how you can work with Spring Boot Profiles: 1) Defining Profiles ==================== * We can define the each property file/YAML File for each environment with following syntax "application-.properties/application-.yml" i) application-dev.properties >>>>> Dev environment Configurations ii) application-qa.poperties >>>>> QA environment Configurations. iii) application-preprod.properties >>>>> preprod environment Configurations. iv) application-prod.properties >>>>> prod environment Configurations. application-dev.properties ========================== database.username=ashokit_dev database.password=ashokit_dev application.emails=dev.ashokit@gmail.com application-qa.properties ========================== database.username=ashokit_qa database.password=ashokit_qa application.emails=qa.ashokit@gmail.com application-preprod.properties ============================== database.username=ashokit_preprod database.password=ashokit_preprod application.emails=preprod.ashokit@gmail.com application-prod.properties =========================== database.username=ashokit_prod database.password=ashokit_prod application.emails=ashokitschools@gmail.com * In your Spring Boot application, you can define profiles by using the @Profile annotation on classes or methods. Example ======= @Configuration @Profile("dev") public class DevelopmentConfig { // Configuration specific to the development profile } @Configuration @Profile("prod") public class ProductionConfig { // Configuration specific to the production profile } ------------------------------------------------ @Configuration public class Config{ @Bean @Profile("dev") public DataSource getDataSourceObj(){ DriverManagerDataSource dmd = new DriverManagerDataSource(); dmd.setDriverClassName(MySQLJdbcDriverClassName); dmd.setUrl(MySqlJdbcURL); dmd.setUsername(MySqlUsername); dmd.setPassword(MySqlPassword); } @Bean @Profile("prod") public DataSource getDataSourceObj(){ DriverManagerDataSource dmd = new DriverManagerDataSource(); dmd.setDriverClassName(OracleJdbcDriverClassName); dmd.setUrl(OracleJdbcURL); dmd.setUsername(OracleUsername); dmd.setPassword(OraclePassword); } } 2) Activate Profiles ==================== * Using the "spring.profiles.active" property in the application.properties or application.yml file spring.profiles.active=dev * Using the System Property i.e.,commandLine Arguments -Dspring.profiles.active=dev * Programmatically activating profiles using the SpringApplication class: SpringApplication.setAdditionalProfiles("dev"); NOTE ==== * If there is no profile activated in Spring Boot Application then it will fall into "default" profile. IIQ) Is it possible to activate multiple profiles at a time ? ---> Yes we can activate it with following line of code i.e.,spring.profiles.active=prod,qa It is not recommended approach for activating the multiple profiles in spring boot application Example OUTPUT =============== The following 2 profiles are active: "prod", "qa" ProdConfig Class Constructor ashokit_qa=====ashokit_qa=====qa.ashokit@gmail.com Activated Profile Name :::::[prod, qa]