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
  • API of org.hibernate.query.Query<T>
  • Pagination API
  • Hibernate Criteria API
  • Composite primary key
  1. Languages
  2. Java
  3. 01_Backend
  4. 06_ORM_Hibernate
  5. readmes

Hibernate Query API

PreviousHibernate APINextHibernate Annotations and JPQL

Last updated 4 months ago

API of org.hibernate.query.Query<T>

  • This interface is specified in javax.persistence specification

  1. Iterator iterate() throws HibernateException

    • This api is deprecated since 5.2 version

    • Return the query results as an Iterator.

    • If the query contains multiple results per row, the results are returned Object[].

    • Entities are returned in lazy manner.

    • Read more for difference between list() and iterator().

  2.     List<T> getResultList()
    • Execute query to get List of selected PERSISTENT POJOs

    • API of org.hibernate.query.Query interface, taken from javax.persistence.TypedQuery<T>.

    • Execute a SELECT query and return the query results as a generic List<T>.

    • T is the type of POJO/Result.

          String hql = "select b from BookPOJO b";
          try {
              List<Book> l1 = hs.createQuery(jpql, Book.class)
                              .getResultList();
          }
    • Passing IN parameters to query & execute it.

      • Objective : Display all books from specified author, with price less than the specified price.

      • API from org.hibernate.query.Query interface

            Query<R> setParameter(String name, Object value)
      • Bind a named query parameter using its inferred Type.

        • name : query parameter name

        • value : parameter value

      • How to set IN parameters ?

        • org.hibernate.query.Query<T> API

        • public Query<T> setParameter(String pName, Object val);

      • Example,

            String hql="select b from BookPOJO b where b.price < :sp_price and b.author = :sp_auth";
            List<Book> l1 = hibSession.createQuery(hql,Book.class).setParameter("sp_price", user_price).setParameter("sp_auth", user_auth).getResultList();
  3. Updating POJOs

    • Can be done either with select, followed by update or ONLY with update queries. (following is eg of 2nd option commonly known as bulk update).

    • Objective : Decrease price of all books with author=specified author.

          String jpql = "update BookPOJO b set b.price = b.price - :disc where b.author = :au and b.publishDate < :dt ";
          int updateCount= hs.createQuery(jpql).setParameter("disc", disc).setParameter("dt", d1).executeUpdate();
    • This approach is typically not recommended often, since it bypasses L1 cache. Interesting read

    • Cascading is not supported. Doesn't support optimistic locking directly.

    • Use case, for bulk updations to be performed on a standalone unrelated table.

Pagination API

  1. Query setMaxResults(int maxResults)

    • Set the maximum number of rows to retrieve.

    • If not set, there is no limit to the number of rows retrieved.

  2. Query setFirstResult(int firstResult)

    • Set the first row to retrieve.

    • If not set, rows will be retrieved beginnning from row 0. (NOTE row num starts from 0).

        List<CustomerPOJO> l1=session
            .createQuery("select c from CustomerPOJO c")
            .setFirstResult(30).setMaxResults(10).list();
    • How to count rows & use it in pagination techniques?

        int pageSize = 10;
        String countQ = "Select count (f.id) from Foo f";
        Query countQuery = session.createQuery(countQ);
        Long countResults = (Long) countQuery.uniqueResult();
        int lastPageNumber = (int) ((countResults / pageSize) + 1);
        Query selectQuery = session.createQuery("From Foo");
        selectQuery.setFirstResult((lastPageNumber - 1) * pageSize);
        selectQuery.setMaxResults(pageSize);
        List<Foo> lastPage = selectQuery.list();
  3. <T> T getSingleResult()

    • Executes a SELECT query that returns a single result.

    • Returns a single instance (persistent object) that matches the query.

    • It throws:

      • NoResultException, if there is no result.

      • NonUniqueResultException, if more than one result.

      • IllegalStateException, if called for a JPQL UPDATE or DELETE statement.

  4. How to get Scrollable Result from Query?

    • ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException

    • The scrollability of the returned results depends upon JDBC driver support for scrollable ResultSets.

    • Return the query results as ScrollableResults. Then, one can use methods of ScrollableResults first(), next(), last(), scroll(n).

  5. How to create NamedQuery from Session interface?

    • What is a named query ?

      • It's a technique to group the HQL statements in single location (typically in POJOS) and lately refer them by some name whenever need to use them. It helps largely in code cleanup because these HQL statements are no longer scattered in whole code.

    • It is Fail fast: Their syntax is checked when the session factory is created, making the application fail fast in case of an error.

    • Reusable: They can be accessed and used from several places which increases re-usability.

    • Example, In POJO class, at class level, one can declare Named queries.

        @Entity
        @NamedQueries({
                @NamedQuery(name = "DepartmentEntity.GET_DEPARTMENT_BY_ID", query="select d from DepartmentEntity d where d.id = :id")
        })
        public class Department{....}
    
        //Usage
        Department d1 = (Department) session.getNamedQuery("DepartmentEntity.GET_DEPARTMENT_BY_ID").setInteger("id", 1);
  6. How to invoke native sql from hibernate?

        Query q = hs.createSQLQuery("select * from books").addEntity(BookPOJO.class);
       List<Object[]> l1 = q.list();

Hibernate Criteria API

  • A powerful and elegent alternative to HQL. Well adapted for dynamic search functionalities where complex Hibernate queries have to be generated 'on-the-fly'.

  • Typical steps are,

    • Create a criteria for POJO

    • Add restrictions, projections, add order

    • Fire query (via list() or uniqueResult())

Composite primary key

  • Use annotation @Embeddable (NOT @Entity).

  • Must be Serializable.

  • Must implement hashCode() & equals() as per general contract.

  • In owning Entity class add usual annotation @Id.

here
here
Inheritance Hierarchy