"Welcome To Ashok IT" "Spring Boot and MicroServices" Topic : Spring Data JPA Date : 03/10/2024 (Session - 38) _____________________________________________________________________________________________________________________________ Today Session ============= * Spring Data JPA is submodule of Spring Data Module. * By using Spring Data JPA we can work with any SQL Database Software (or) Relational Databases Software. Ex:oracle,mysql,postgresql,sqlserver etc., * While working with Spring Data JPA we can avoid writing boiler plate of Code of DAO logic/Persistence logic. Earlier development : ===================== 1.Entity Class 2.DAO/Repoistory Interface 3.DAO/Repoistory Implementation Class programmer need to define those abstract methods and provide the implementation of abstract methods. Spring Data JPA Development : ============================= 1.Entity Class 2.DAO/Repoistory Interface by extending Spring Data JPA provided Interfaces i.e.,CurdRepoistory,JpaRepoistory,PagingAndSortingRepoistory etc., Here Programmer no need to provide implementation class for DAO/Respoistory Interface automatically Spring Data JPA will internally generates dynamic Inmemory Proxy class in JVM Memory. * Spring Data JPA provided Repoistories contains ready made methods for commonly required database operations such as creating Record,Updating Record,Deleting Records,finding the records,finding record based on id etc., Respoistories in Spring data JPA ================================ * In the Spring Data JPA Module the Root Interface is "Respoistory(I)" is a Marker Interface which doesn't have any abstract methods and it will provide additional behaviour to Java Object java.lang.Cloneable,java.io.Serializable,org.springframework.data.Repoistory are marker interfaces and providing extra capabilities/Additional Behaviours to our Java Objects. * We have child interface for above Marker Interface of "Respoistory(I)" i.e., "CrudRepoistory(I)" which provides basic DAO operations i.e, 12 Methods Repoistory(I) <------------------> Parent Inteface ^ | extends | CrudRepoistory(I) <----------------> Child Interface(12 Methods) * We have another child interface for Repoistory interface i.e.,PagingAndSortingRepoistory(I) which provides Pagination feature and Sorting features. Repoistory(I) <------------------> Parent Inteface ^ | extends | PagingAndSortingRepoistory(I) <-----------> Child Inteface (2 Methods) * We have another child interface for CrudRepoistory interface i.e.,JpaRepoistory(I) which are getting services from another main two interfaces ListCrudRepository(I) and ListPagingAndSortingRepoistory * ListCrudRepository(I) is child interface of CrudRepoistory(I) the differences is ListCrudRepository gives results as List Object and CrudRepoistory gives results as Iterable object. * ListPagingAndSortingRepoistory(I) is child interface of PagingAndSortingRepoistory(I) the differences is ListCrudRepository gives results as List Object and CrudRepoistory gives results as Iterable object. NOTE ==== * During the Application Development our DAO Interfaces are extending from CrudRepoistory/PagingAndSortingRepoistory our interfaces will becomes auto discoverable means spring data jpa will create those objects automatically no need for defining @Repository stero type of annotation. interface CustomerDao extends CrudRepoistory{ } Below code is also valid but not recommended because we are already getting spring bean object from root interfaces i.e.,Repoistory(I) @Repoistory interface CustomerDao extends CrudRepoistory{ } * Make sure you need to complete atleast one relational database software in your machine oracle,mysql ****************************************************** Steps for Developing First Spring Data JPA Application ****************************************************** Step-1 : Make sure we need to complete the installation process for at least one SQL Database i.e., Oracle, MySQL. Step-2 : After Installation of Oracle Database Software we need to connect with Oracle Database using CLI Interface i.e.,SQL Command Line (Goto start menu >>>> Search for Word "SQL" >>> Will find & Select the option "Run SQL Command Line"). Step-3 : After opening the Command Line Interface need to connect with Oracle Database using below commands SQL >>>> connect Enter UserName : system Enter Password : manager(Not Visible) and hit on enter Connected Step-4: Creating the table in the Database Software create table shopping_customers(customer_id number primary key, name varchar2(50) not null, location varchar2(50), email varchar2(100) unique, contact_no varchar2(10) ); Step-5 : Open the STS IDE and Create new Project with below two Dependencies 1) Spring-boot-starter-data-jpa 2) Oracle Driver Step-6 : After creating project we need to create the below packages com.ashokit.entity >>>> For Placing Entity classes in our application com.ashokit.dao >>>> For Placing DAO Interfaces in our application com.ashokit.service >>>> For Placing Business classes in our application com.ashokit.controller >>>> For Placing Controller classes in our application Step-7 : Creating Entity Class nothing but Creating Java Class and Map to Database table using annotations @Entity,@Table,@ID,@Column 1) @Entity annotation is used for marking the Java class as Entity Class. 2) @Table annotation is used to map between the Java Class and Database table. 3) @Id annotation is used to mark the Primary Column at Entity Class level. 4) @Column annotation is used to map between the Fields in Entity and Database table column names. Customer.java ============= package com.ashokit.entity; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Table; @Entity @Table(name="shopping_customers") public class Customer { @Id @Column(name = "customer_id") private Integer customerId; @Column(name="name") private String name; @Column(name="location") private String location; @Column(name="email") private String emailId; @Column(name="contact_no") private String contactNo; public Integer getCustomerId() { return customerId; } public void setCustomerId(Integer customerId) { this.customerId = customerId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getContactNo() { return contactNo; } public void setContactNo(String contactNo) { this.contactNo = contactNo; } } Step-8: We need to configure the Database properties in application.properties #Database Configuration spring.datasource.driver-class-name=oracle.jdbc.OracleDriver spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe spring.datasource.username=system spring.datasource.password=manager Step-9: Create Repoistory Interface/DAO interface for our Database Table by extends CrudRepoistory from Spring Data JPA Library CustomerDao.java ================ package com.ashokit.dao; import org.springframework.data.repository.CrudRepository; import com.ashokit.entity.Customer; //Automatically Consider as Spring bean we can autowire anywhere application public interface CustomerDao extends CrudRepository { } Step-10: Creating Service class and injecting DAO interface to call DAO Methods. CustomerService.java ==================== package com.ashokit.service; import com.ashokit.entity.Customer; public interface CustomerService { public Customer creatingNewBrandCustomer(Customer customer); } CustomerServiceImpl.java ======================== package com.ashokit.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ashokit.dao.CustomerDao; import com.ashokit.entity.Customer; @Service public class CustomerServiceImpl implements CustomerService { @Autowired private CustomerDao customerDao; @Override public Customer creatingNewBrandCustomer(Customer customer) { //calling the ORM Method to save customer Information i.e.,inserting the record Customer savedCustomer = customerDao.save(customer); return savedCustomer; } } Step-11: Creating the Controller Class and Call the Service methods from Service Class package com.ashokit.controller; import java.util.Objects; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.ashokit.entity.Customer; import com.ashokit.service.CustomerService; @Controller public class CustomerController { @Autowired private CustomerService customerService; public void createNewCustomer(Customer customer) { Customer customerDetails = customerService.creatingNewBrandCustomer(customer); if(Objects.nonNull(customerDetails)) { System.out.println("Customer Created SuccessFully....."); System.out.println(customerDetails); }else { System.out.println("Customer Not Created......"); } } } Step-12: package com.ashokit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import com.ashokit.controller.CustomerController; import com.ashokit.entity.Customer; @SpringBootApplication public class Application { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); Customer customer = new Customer(123,"Mahesh","Hyderabad","mahesh.ashokit@gmail.com","1232323232"); CustomerController controller = context.getBean(CustomerController.class); controller.createNewCustomer(customer); } } OUTPUT ====== CustomerClass Default Constructor..... Customer Created SuccessFully..... Customer [customerId=123, name=Mahesh, location=Hyderabad, email=mahesh.ashokit@gmail.com, contactNo=1232323232]