"Welcome To Ashok IT" "Spring Boot and MicroServices" Topic : Spring Core - Layered Application Development Date : 10/09/2024 (Session - 20) _____________________________________________________________________________________________________________________________ Layered Application ==================== 1) Controller Class <------------> Handling the Request & Response of an Application 2) Service Class <------------> Placing the Business logic 3) DAO Class <------------> Placing the Database Logic 4) Helper Class <------------> Conversion of Objects 5) Utility Class <------------> Placing the Utility specific functions Main class(Controller Class) --------------> Service Class -----------> DAO Class ----------> JdbcTemplate -------> DataSource ----------> Database Software (Oracle,MySQL) Layered Application Development using Spring Core & Spring Jdbc Module ====================================================================== * Spring Core Module : Dependency Injection,Types of Dependency Injection,Autowiring using XML,Annotations,Java Based configuration Development,Component Scan... * Spring Jdbc : If Spring Application needs to communicate with Database for Storing some information, As programmer we need to implement persistence/DAO logic. * Persistence logic / DAO Logic : The Logic which helps for communicating with Database for retreiving & Storing information. * Inorder to implement Persistence logic in Spring Framework using modules "Spring-Jdbc & Spring-ORM" Jdbc ==== * Java Database Connectivity * By using Jdbc Technology we can establish the communication from Java Application to Database Software. * In Jdbc Programming we need to following belows steps 1) Registering the driver with DriverManager Service Class.forName("oracle.jdbc.driver.oracleDriver"); (or) Class.forName("com.mysql.jdbc.Driver"); 2) Getting the Connection with Database Software using DriverManager Service Connection con = DriverManager.getConnection(JDBCURL,USERNAME,PASSWORD); 3) We can create the Statement/PreparedStatement object using con object to execute SQL Queries Statement st = con.createStatement(); PreparedStatement pstmt = con.prepareStatement(SQLQUERY); 4) Programmer need to be takencare of Handling Exceptions. 5) JDBC Technology we can get connection object using below techniques * DriverManager * DataSource >>>>> Spring Supplied Connection object using this technique. * Inorder overcome the above problems Spring provided the Abstraction on Jdbc Technology i.e.,Spring-Jdbc Module. * The Advantage of using Spring Jdbc Module are as follows 1) Programmer no need to worry about Registering the Driver With DriverManager Service. 2) Programmer no need to worry about getting database connection using DriverManager Service. 3) Spring Jdbc Module Provided some Centralized class to execute SQL Queries which are commonly required for every project Ex: JdbcTemplate,NamedParameterJdbcTemplate,SimpleJdbcCall etc., 4) Programmer no need to worry about handling exceptions & Resource Clean-up Activity while writing the Database logics. 5) Spring JDBC Always gets the Database Connection Object using Datasource. * DataSource is an Interface from javax.sql given by sun microsystem and will have different implementation from different vendors. DataSource(I) <--------------------- DriverManagerDataSource(IC) <------------------------- Spring DataSource(I) <--------------------- BasicDataSource(IC) <---------------------------------- Apache software Foundation Getting DataSource Object using xml approach ============================================ Java Based Configuration for DriverManagerDataSource ==================================================== @Bean public DriverManagerDataSource getDataSource(){ DriverManagerDataSource ds = new DriverManagerDataSource(); //setting the properties } Configuring the JdbcTemplate Class As Spring Bean ================================================= XML === JavaBased Configuration ======================= @Bean public JdbcTemplate getJdbcTemplate(){ JdbcTempate jt = new JdbcTemplate(); jt.setDataSource(getDataSource()); return jt; } NOTE ==== * You need to install MYSQL Database Software in your machine.. Database configuration ====================== * After completion of MYSQL Database Installation, Goto Start Menu and search for "MySQL Workbench". * After opening the MYSQL Database we need to create one connection with some name "springboot_microservices". * Click on Required Connection Tab in MYSQL Home Page and we can observe the existing databases in navigator section. * Creating Database : In Tool bar from left side to 4th Icon(Database) Just click on it >>>> will provide some "Database Schema Name" and click on "Finish button". * After creating Database schema just double click on it for Activating as "current Database Schema". * After Activating the schema we need to create database table with help of SQL Worksheet from Tool Bar to First Icon. * Onces Worksheet Page got opened we need to create the below Database Table CREATE TABLE `ashokit_emps` ( `emp_id` bigint primary key, `emp_name` varchar(50), `emp_email` varchar(50), `created_dt` date, `created_by` varchar(50) ); Application Code ================ pom.xml ======= 4.0.0 com.ashokit 07_SpringJdbc_App 0.0.1-SNAPSHOT 17 17 org.springframework spring-context-support 6.1.2 org.springframework spring-jdbc 6.1.2 com.mysql mysql-connector-j 8.2.0 DatabaseConfig.java =================== package com.ashokit.config; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; @Configuration @PropertySource(value = "classpath:database.properties") public class DatabaseConfig { @Value("${MySqlDriverClassName}") private String driverClass; @Value("${MySqlDriverUrl}") private String driverUrl; @Value("${MySqlUsername}") private String username; @Value("${MySqlPassword}") private String password; //DataSource Configuration @Bean public DataSource getDataSource() { DriverManagerDataSource dds = new DriverManagerDataSource(); dds.setDriverClassName(driverClass); dds.setUrl(driverUrl); dds.setUsername(username); dds.setPassword(password); return dds; } @Bean public JdbcTemplate getJdbcTemplate() { JdbcTemplate jt = new JdbcTemplate(); jt.setDataSource(getDataSource()); return jt; } } EmployeeDao.java ================ package com.ashokit.dao; import com.ashokit.dtos.Employee; public interface EmployeeDao { public boolean createEmployee(Employee emp); public List> getAllEmployees(); } EmployeeDaoImpl.java ==================== package com.ashokit.dao; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.ashokit.dtos.Employee; @Repository public class EmployeeDaoImpl implements EmployeeDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public boolean createEmployee(Employee emp) { int insertCount = jdbcTemplate.update("insert into ashokit_emps values(?,?,?,?,?)", new Object[] {emp.getEmpId(),emp.getEname(),emp.getEmail(), emp.getCreateDate(),emp.getCreatedBy()}); return insertCount > 0; } @Override public List> getAllEmployees() { List> employees = jdbcTemplate.queryForList("select * from ashokit_emps"); return employees; } } EmployeeService.java ==================== package com.ashokit.service; import com.ashokit.dtos.Employee; public interface EmployeeService { public boolean createNewEmployee(Employee emp); public void retrieveAllEmployees(); } EmployeeServiceImpl.java ========================= package com.ashokit.service; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ashokit.dao.EmployeeDao; import com.ashokit.dtos.Employee; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeDao employeeDao; @Override public boolean createNewEmployee(Employee emp) { //calling from Service to Dao Class return employeeDao.createEmployee(emp); } @Override public void retrieveAllEmployees() { List> allEmployees = employeeDao.getAllEmployees(); System.out.println("List::::" + allEmployees); allEmployees.stream().forEach(eachMap ->{ eachMap.entrySet().stream().forEach(eachEntry -> { System.out.print(eachEntry.getKey() +"----->"+ eachEntry.getValue()); }); System.out.println(); }); } } EmployeeController.java ======================== package com.ashokit.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.ashokit.dtos.Employee; import com.ashokit.service.EmployeeService; @Controller public class EmployeeController { @Autowired private EmployeeService employeeService; public void addNewEmployee(Employee emp) { boolean insertStatus = employeeService.createNewEmployee(emp); //checking status if(insertStatus) { System.out.println("Employee Created Successfilly......"); }else { System.out.println("Employee Not Created......."); } } public void getAllEmployeeInformation() { employeeService.retrieveAllEmployees(); } } database.properties =================== #Database Configuration MySqlDriverClassName=com.mysql.cj.jdbc.Driver MySqlDriverUrl=jdbc:mysql://localhost:3306/springboot_microservices MySqlUsername=root MySqlPassword=root SpringClient.java ================= package com.ashokit; import java.time.LocalDate; import java.util.Random; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.ashokit.config.ApplicationConfig; import com.ashokit.controller.EmployeeController; import com.ashokit.dtos.Employee; public class SpringClient { public static void main(String[] args) { //Activating the Container ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class); //Setting as some data for inserting record into employee table Employee emp = new Employee(); emp.setEmpId(new Random().nextInt(9000)); emp.setEname("Sarath"); emp.setEmail("sarthashokitschools@gmail.com"); emp.setCreateDate(LocalDate.now()); emp.setCreatedBy("Sarath"); //Requesting the controller bean EmployeeController ec = context.getBean(EmployeeController.class); //calling the method from Controller class ec.addNewEmployee(emp); System.out.println("******************************************"); //calling the method for Controller class ec.getAllEmployeeInformation(); } } OUTPUT ====== Employee Data Transfer Object..... Employee Created Successfully...... ****************************************** List::::[{emp_id=427, emp_name=Sarath, emp_email=sarthashokitschools@gmail.com, created_dt=2023-06-11, created_by=Sarath}, {emp_id=472, emp_name=Mahesh, emp_email=mahesh.ashokit@gmail.com, created_dt=2023-06-11, created_by=Mahesh}, {emp_id=8961, emp_name=Sarath, emp_email=sarthashokitschools@gmail.com, created_dt=2023-06-12, created_by=Sarath}] emp_id----->427emp_name----->Sarathemp_email----->sarthashokitschools@gmail.comcreated_dt----->2023-06-11created_by----->Sarath emp_id----->472emp_name----->Maheshemp_email----->mahesh.ashokit@gmail.comcreated_dt----->2023-06-11created_by----->Mahesh emp_id----->8961emp_name----->Sarathemp_email----->sarthashokitschools@gmail.comcreated_dt----->2023-06-12created_by----->Sarath