TechWriterDev
  • Cloud
    • AWS
      • 00_Doubts
      • CloudPractitioner
        • Cloud Computing
        • AWS Global Infrastructure
        • Introduction to AWS EC2
        • Elastic load balancer(ELB)
        • 04_Messaging_Queuing
        • Aditional Computing Service
        • Accessing AWS resources
        • AWS Networking
        • Storage
        • Amazon Database Solutions
        • Monitoring Tools
        • AWS Security
        • Distributed Denial Of Service Attacks
      • DeveloperAssociate
        • References
        • AWS DVA-C02 Services Index
        • Services
          • 00_IAM
            • Identity and Access Management (IAM)
            • Account Protection Mechanisms
            • Access Mechanism of AWS Resources
            • Security Tools
            • Responsibility Model
            • Advanced Concepts
          • 01_EC2
            • Elastic Compute Cloud (EC2)
            • EC2 Volume Types
            • Amazon Machine Image (AMI)
            • AWS charges for IPv4 address
          • 02_SecurityGroups
            • Security Groups
          • 03_Elastic_LoadBalancing
            • Terminology
            • Elastic load balancer
            • Features
            • Basics
          • 04_AutoScaling
            • Auto Scaling
          • 05_RDS
            • Relational Database Service (RDS)
            • Aurora
            • Security
            • RDS Proxy
          • 06_ElastiCache
            • Cache
            • Cache Offerings
          • 07_Route53
            • Basics of DNS
            • Route 53
          • 08_VPC
            • Virtual Private Cloud (VPC)
          • 09_S3
            • Simple Storage Service (S3)
            • S3 Features
            • S3 Encryption
            • S3 Features
            • S3 Bucket Policy and IAM Policy
          • 10_ECS
            • Elastic Container Service (ECS)
            • Elastic Container Registry (ECR)
            • AWS Copilot
          • 11_EKS
            • Elastic Kubernetes Service (EKS)
          • 12_SDK_CLI_Tips
            • Access AWS Resources
          • 13_CloudFront
            • Cloud Front
          • 14_Messaging
            • Simple Queue Service (SQS)
            • Simple Notification Service (SNS)
            • Fan Out Pattern
            • Kinesis
            • Compare and Contrast
          • 15_ElasticBeanStalk
            • Elastic Beanstalk
          • 16_CloudFormation
            • CloudFormation
            • Dynamic References
          • 17_Monitoring
            • AWS Monitoring
            • AWS CloudWatch
            • CloudWatch Alarms
            • Synthetics Canary
            • Amazon EventBridge (formerly CloudWatch Events)
            • X-Ray
            • OpenTelemetry
            • CloudTrail
          • 18_Lambda
            • Lambda
            • Lambda Integrations
            • Configuring Lambda
            • Lambda Layers
          • 19_API_Gateway
            • API Gateway
            • API Gateway Integrations
          • 20_DynamoDB
            • DynamoDB
            • Operations
            • Indexes
            • DynamoDB Accelerator (DAX)
            • DynamoDB Streams
            • Transactions
            • Integrations
          • 21_CICD
            • CICD
            • CodeCommit
            • CodePipeline
            • CodeBuild
            • CodeDeploy
            • CodeArtifact
            • CloudGuru
          • 22_SAM
            • Serverless Application Model (SAM)
          • 23_CDK
            • Cloud Development Kit (CDK)
          • 24_StepFunctions
            • Step Functions
            • Types of step function
          • 25_AppSync
            • AppSync
          • 26_Amplify
            • Amplify
          • 27_STS
            • Security Token Service (STS)
          • 28_DirectoryService
            • Active Directory
          • 29_KMS
            • Encryption
            • KMS API
            • Features
            • Cloud Hardware Security Module (HSM)
          • 30_SSM_Store
            • SSM Parameter Store
          • 31_SecretsManager
            • Secrets Manager
          • 32_Cognito
            • Cognito
      • Questions
        • AWS_Region
        • EC2
        • IAM
  • Database
    • MongoDb
      • Mongo db Basics
      • Mongo DB Atlas
      • Document
      • Import-Export based on Data Format
      • Mongo Shell Commands
      • Query Operators
      • Indexes
      • Upsert
      • MongoDB Aggregation Framework
      • Aggregation Framework Operators
    • PostgreSQL
      • POSTGRE SQL DataTypes
      • About table
      • Constraints
  • Technologies
    • RabbitMQ
      • RabbitMQ Concepts
      • Introduction to Exchanges
      • Introduction to Queues
    • Terraform
      • 00_Introduction
      • Configuration blocks
      • Commands
      • Variables
      • Terraform Cloud
      • Modules
  • Languages
    • Java
      • Logging
        • Getting Started
      • 00_Core
        • 00_Basics
          • Java Vs C++
          • Object oriented principles
          • Steps to compile a java program
          • JVM Internals
          • Understanding Java Development Kit
          • What is JIT Compiler?
          • Java data types
          • 07_identifiers_type_conversion
          • 08_references_and_packages
          • Steps for attaching scanner
        • Concurrency
          • 00_Threads
            • Threads
          • 01_ExecutorFramework
            • Executor Framework
            • Asynchronous Computation
      • 01_Backend
        • 01_HttpAndWebServerBasics
          • HTTP
          • Content Type
          • Web Server
        • 02_J2EE_Basics
          • J2EE_Basics
          • Why HttpServlet classs is declared as abstract class BUT with 100 % concrete functionality ?
        • 03_TomCatAndSession
          • What is a Session?
          • WebContainer
        • 04_PageNavigation
          • Cookies Additional Information
          • Page Navigation Techniques
        • 05_AboutServlet
          • CGI v/s Servlet
          • Executor Framework
          • Servlet Life cycle
          • SERVLET CONFIG
          • Servlet Context
          • Servlet Listener (web application listener)
        • 08_SpringBoot
          • Spring Boot
          • Some common annotations used in spring eco system
        • 09_SpringDataJPA
          • Spring Data JPA
        • Java_Language_Changes
          • JDK enhancement tracking reference
        • 06_ORM_Hibernate
          • readmes
            • Hibernate
            • Advantages of Hibernate
            • Hibernate Caching
            • Hibernate API
            • Hibernate Query API
            • Hibernate Annotations and JPQL
            • Entity and Value Type
        • 07_SpringFramework
          • bean_validation
            • Bean Validation
          • core
            • readme
              • Spring
              • Spring Framework Modules
              • Spring MVC Request flow
              • Dependency Injection
              • Spring Beans
              • 06_Spring_Framework_Annotations
      • 03_Tools
        • Maven
          • Maven
  • SoftwareEngineering
    • DesignPatterns
      • Notes
        • Basics
        • OOP
        • SOLID Principles
        • 03_Creational
          • Abstract Factory (aka Kit)
          • Builder
          • Factory Method (aka Virtual constructor)
          • Prototype
          • Singleton
        • 04_Structural
          • Adapter (aka Wrapper)
          • Bridge (aka Handle | Body)
          • Composite
          • Decorator (aka Wrapper)
          • Facade
          • Flyweight
          • Proxy (aka Surrogate)
        • 05_Behavioral
          • Chain of Responsibility
          • Command (aka Action | Transaction)
          • Iterator (aka Cursor)
          • Observer (aka Publish-Subscribe | Dependents)
          • Strategy (aka Policy)
    • Principles
      • REST
        • REST
  • Tools
    • Containers
      • Docker
        • Docker
        • Docker Image
        • Commands
        • Compose
        • Best Practices
      • Kubernetes
        • Kubernetes
    • VCS
      • Git
        • Quick reference of useful Git commands
Powered by GitBook
On this page
  • Crud Repository
  • Jpa Repository
  • Custom Access Method and Queries
  • Transaction Configuration
  • Exception Translation
  1. Languages
  2. Java
  3. 01_Backend
  4. 09_SpringDataJPA

Spring Data JPA

  • In entire web application, the DAO layer usually consists of a lot of boilerplate code that can be simplified.

  • Benefits of simplification

    1. Decrease in the number of artifacts that we need to define and maintain.

    2. Consistency of data access patterns and consistency of configuration.

  • Spring Data JPA framework takes this simplification one step forward and makes it possible to remove the DAO implementations entirely. The interface of the DAO is now the only artifact that we need to explicitly define.

  • For this, a DAO interface needs to extend the JPA specific Repository interface JpaRepository or its super interface CrudRepository. This will enable Spring Data to find this interface and automatically create an implementation for it.

  • By extending the interface we get the most required CRUD methods for standard data access available in a standard DAO.

Crud Repository

  • org.springframework.data.repository.CrudRepository<T, ID> methods are as follows,

  long 	count() // Returns the number of entities available.
  void 	delete(T entity) // Deletes a given entity.
  void 	deleteAll() // Deletes all entities managed by the repository.
  void 	deleteAll(Iterable<? extends T> entities) // Deletes the given entities.
  void 	deleteById(ID id) // Deletes the entity with the given id.
  boolean 	existsById(ID id) // Returns whether an entity with the given id exists.
  Iterable<T> 	findAll() // Returns all instances of the type.
  Iterable<T> 	findAllById(Iterable<ID> ids) // Returns all instances of the type with the given IDs.
  Optional<T> 	findById(ID id) // Retrieves an entity by its id.
  <S extends T> S save(S entity) // Saves a given entity.
  <S extends T> Iterable<S> saveAll(Iterable<S> entities) // Saves all given entities.

Jpa Repository

  • org.springframework.data.jpa.repository.JpaRepository<T, ID>

  void 	deleteAllInBatch() //Deletes all entities in a batch call.
  void 	deleteInBatch(Iterable<T> entities) // Deletes the given entities in a batch which means it will create a single Query.
  List<T> findAll() 
  <S extends T> List<S> findAll(Example<S> example) 
  <S extends T> List<S> findAll(Example<S> example, Sort sort) 
  List<T> findAll(Sort sort) 
  List<T> findAllById(Iterable<ID> ids) 
  void flush() // Flushes all pending changes to the database.
  T getOne(ID id) //Returns a reference to the entity with the given identifier.
  <S extends T> List<S> saveAll(Iterable<S> entities) 

Custom Access Method and Queries

  • By extending one of the Repository interfaces, the DAO will already have some basic CRUD methods (and queries) defined and implemented.

  • To define more specific access methods, Spring JPA supports quite a few options:

  1. When Spring Data creates a new Repository implementation, it analyses all the methods defined by the interfaces and tries to automatically generate queries from the method names. While this has some limitations, it’s a very powerful and elegant way of defining new custom access methods with very little effort.

  • Consider following examples,

    • findBy, And, Or, Distinct example queries.

        /* 
          select * from Customer c where c.name = name;
          -- gives only one customer
        */
        Customer findByName(String name);
        
        /*
          select * from Person p where p.emailAddress = emailAddress AND p.lastname = lastname
          -- returns multiple person, if more than one present
        */
        List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);
      
        /*
          select DISTINCT(p) from Person p where p.lastname = lastname OR p.firstname = firstname
        */
        // Enables the distinct flag for the query
        List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
          
          // Enabling ignoring case for an individual property
        List<Person> findByLastnameIgnoreCase(String lastname);
      
          // Enabling static ORDER BY for a query
        List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
        List<Person> findByAddressZipCode(ZipCode zipCode);
        // Assuming a Person has an Address with a ZipCode. In that case, the method creates the property traversal x.address.zipCode.
      
    • Limiting the result size of a query with Top and First.

        // select * from User u order by u.lastname asc limit 1;
        User findFirstByOrderByLastnameAsc();
        // select * from User u order by u.lastname desc limit 10;
        User findTopByOrderByAgeDesc();
      
        Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);
      
        Slice<User> findTop3ByLastname(String lastname, Pageable pageable);
      
        List<User> findFirst10ByLastname(String lastname, Sort sort);
      
        List<User> findTop10ByLastname(String lastname, Pageable pageable);
  1. Simply define a new method in the interface and provide the actual JPQL query by using the org.springframework.data.jpa.repository.@Query annotation. This methods is used to write custom query.


  @Query("select u from User u where u.emailAddress = :emailAddress")
  User findByEmailAddress(String emailAddress);

  @Query("SELECT p FROM Person p WHERE LOWER(p.name) = LOWER(:nm)")
  Foo retrieveByName(@Param("nm") String name);
  • the : before arguments is use to specify named Parameters, which acts as place holder. Just like ? in jdbc.

  • org.springframework.data.repository.query.@Param is used to bind named parameters with query method param.

Transaction Configuration

  • The actual implementation of the Spring Data managed DAO layer is hidden since we don’t work with it directly. JpaRepository interface through JpaRepositoryImplementation interface is implemented by the org.springframework.data.jpa.repository.support.SimpleJpaRepository<T, ID>, which defines default transaction mechanism using annotations.

    • The annotation used is @Transacational from org.springframework.transaction.annotation.

    • These tansaction can be easily overridden manually per method as well by supplying your own configurations.

Exception Translation

  • Exception translation is still enabled by the use of the @Repository annotation internally applied on the DAO implementation class.

Previous09_SpringDataJPANextJava_Language_Changes

Last updated 4 months ago