DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Implement Hibernate Second-Level Cache With NCache
  • Architectural Miscalculation and Hibernate Problem "Type UUID but Expression Is of Type Bytea"
  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps
  • Simplify Java Persistence Using Quarkus and Hibernate Reactive

Trending

  • Unlocking AI Coding Assistants Part 4: Generate Spring Boot Application
  • Docker Base Images Demystified: A Practical Guide
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Java Virtual Threads and Scaling
  1. DZone
  2. Data Engineering
  3. Databases
  4. Writing effective custom queries in Hibernate

Writing effective custom queries in Hibernate

By 
Amar Mattey user avatar
Amar Mattey
·
Apr. 21, 14 · Interview
Likes (0)
Comment
Save
Tweet
Share
26.9K Views

Join the DZone community and get the full member experience.

Join For Free
There are many instances where we will have to write custom queries with hibernate.

I always hated writing custom queries due to following reasons
  1. Hibernate returns List of Object arrays (List<Object>.)
  2. Lots of ugly mapping code.
  3. Every Object has to be casted.
  4. Maintain indexes in code, so if I add a new column, I have to ensure I use the right index.
and here is an example how the code generally looks like
 public List<SalaryByDepartment> getSalaryByDepartment() {
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
      List<Object> contactList = session.createQuery("select " +
              "department.id, " +
              "department.departmentName, " +
              "sum(employee.salary) from Employee employee, Department department " +
              "where employee.department.id = department.id group by department.id")
              .list();

      List<SalaryByDepartment> salaryByDepartments = new ArrayList<SalaryByDepartment>();

      for (Object object : contactList) {
        Object[] result = (Object[]) object;
        SalaryByDepartment salaryByDepartment = new SalaryByDepartment();
        salaryByDepartment.setDeptId((Integer) result[0]);
        salaryByDepartment.setDepartmentName((String) result[1]);
        salaryByDepartment.setSalary((Double) result[2]);
        salaryByDepartments.add(salaryByDepartment);
      }
      return salaryByDepartments;
    } catch (HibernateException e) {
      e.printStackTrace();
      return null;
    } finally {
      session.close();
    }
  }
There is a better mechanism for writing the custom queries called 'select new' but it is not widely used for some reason.


It might be an overkill to write all custom queries using this mechanism, but is good for queries which return more than 2 columns.

 public List<SalaryByDepartment> getNewSalaryByDepartment() {
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
      List<SalaryByDepartment> salaryByDept = session.createQuery("select " +
              "new hsqldb.results.SalaryByDepartment(department.id, department.departmentName, sum(employee.salary)) " +
              "from Employee employee, Department department " +
              "where employee.department.id = department.id group by department.id")
              .list();
      return salaryByDept;
    } catch (HibernateException e) {
      e.printStackTrace();
      return null;
    } finally {
      session.close();
    }
  }
Database Hibernate

Opinions expressed by DZone contributors are their own.

Related

  • Implement Hibernate Second-Level Cache With NCache
  • Architectural Miscalculation and Hibernate Problem "Type UUID but Expression Is of Type Bytea"
  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps
  • Simplify Java Persistence Using Quarkus and Hibernate Reactive

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: