Impact on using Spring Data native query @Query to Persistence Context?

Using Spring Data’s @Query annotation with native SQL queries can have several impacts on Hibernate or JPA persistence context:

Bypassing JPQL Translation: When you use a native SQL query with @Query, you bypass JPQL (Java Persistence Query Language) translation. This means that the query is written in the native SQL dialect of the underlying database, rather than in JPQL, which is database agnostic. While this can provide more flexibility in complex queries or when leveraging database-specific features, it also ties your application more tightly to the underlying database, potentially reducing portability.

Direct Interaction with Database: Native queries bypass the entity manager’s persistence context, as they don’t involve managed entities directly. This means that Hibernate or JPA typically not manage the entities returned by a native query. As a result, changes to these entities won’t be automatically synchronized with the database unless you manually manage them using entity manager operations.

Performance Considerations: Native queries might offer performance benefits in certain cases, especially when dealing with complex queries or when JPQL is not sufficient to express the logic efficiently. However, they also come with potential drawbacks such as decreased portability and increased maintenance complexity.

Mapping to Entities: While native queries return results in the form of arrays or lists of objects, you can still map these results to entities manually if needed. However, this requires additional code for mapping the columns returned by the native query to the fields of your entity classes.

Security Risks: Using native queries opens up potential security risks such as SQL injection if the queries involve user input. You need to be careful to properly sanitize and validate any user-provided parameters before incorporating them into native queries to prevent such vulnerabilities.

Testing and Maintenance: Native queries can make your code harder to test and maintain, especially when compared to JPQL queries. Since JPQL queries are language agnostic and are validated by JPA providers during application startup, they offer better compile-time safety and easier refactoring.

In summary, while native queries can be powerful and useful in certain scenarios, they should be used judiciously, considering the trade-offs in terms of performance, portability, security, and maintenance complexity. It’s often preferable to use JPQL queries where possible and resort to native queries only when necessary for performance optimization or when dealing with database-specific features.

Do we need to explicitly call save() method in Hibernate or JPA to save entities?

No, you typically don’t need to explicitly call the save() method in Hibernate or JPA to save entities. In JPA, when you modify a managed entity (an entity that was retrieved or persisted by the entity manager), the changes are automatically synchronized with the database when the transaction commits. Hibernate, being an implementation of JPA, follows this behavior.

Here’s how it generally works:

  1. Persisting new entities: When you create a new entity object and persist it using EntityManager.persist() (or Session.save() in Hibernate), the entity becomes managed by the persistence context. Any changes made to this entity within the scope of the transaction will be automatically synchronized with the database upon transaction commit.
    entityManager.persist(entity);
    
  2. Updating existing entities: When you retrieve an entity from the database (either by EntityManager.find() or through a query), any changes made to this managed entity will also be synchronized with the database upon transaction commit. You don’t need to call any explicit save method.
    Entity entity = entityManager.find(Entity.class, id);
    entity.setSomeProperty(newValue);
    // Changes to 'entity' are automatically synchronized with the database upon transaction commit
    
  3. Automatic dirty checking: Hibernate/JPA employs the concept of dirty checking. It tracks the changes made to managed entities within a transaction. When the transaction commits, it automatically detects the changes and synchronizes them with the database.
    // Entity retrieved and modified within a transaction
    Entity entity = entityManager.find(Entity.class, id);
    entity.setSomeProperty(newValue);
    // Changes to 'entity' are automatically tracked and synchronized with the database upon transaction commit
    

Explicitly calling save() might be necessary in specific cases where you’re dealing with detached entities (entities that are not managed by the persistence context) or if you’re operating outside a transaction boundary, but in general usage within a transaction, it’s not required.

How do I use Hibernate’s Restriction.in criterion?

This example demonstrate the use of Hibernate’s Restriction.in criterion. This restriction will query for some record based on a collection of parameter defined for a specific property of the bean.

package org.kodejava.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.hibernate.Criteria;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.kodejava.hibernate.model.Genre;

import java.util.List;

public class RestrictionInDemo {
    public static Session getSession() throws HibernateException {
        String cfg = "hibernate.cfg.xml";
        SessionFactory sessionFactory = new Configuration().configure(cfg)
                .buildSessionFactory();
        return sessionFactory.openSession();
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        try (Session session = getSession()) {
            // Create a Criteria an add an in constraint for the property
            // id. This in restrictions will return genre with id 1, 2, 3
            // and 4.
            Criteria criteria = session.createCriteria(Genre.class)
                    .add(Restrictions.in("id", 1L, 2L, 3L, 4L));

            List<Genre> result = criteria.list();
            for (Genre genre : result) {
                System.out.println(genre);
            }
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I use min, max, avg and sum Projections?

The code below demonstration the use of Projections.min(), Projections.max(), Projections.avg() and Projections.sum().

package org.kodejava.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.hibernate.Criteria;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Projections;
import org.kodejava.hibernate.model.Track;

public class MinMaxAvgSumProjectionsDemo {
    public static Session getSession() throws HibernateException {
        String cfg = "hibernate.cfg.xml";
        SessionFactory sessionFactory = new Configuration().configure(cfg)
                .buildSessionFactory();
        return sessionFactory.openSession();
    }

    public static void main(String[] args) {
        try (Session session = getSession()) {
            Criteria criteria = session.createCriteria(Track.class)
                    .setProjection(Projections.max("duration"));
            Integer maxDuration = (Integer) criteria.uniqueResult();
            System.out.println("Max Track Duration = " + maxDuration);

            criteria.setProjection(Projections.min("duration"));
            Integer minDuration = (Integer) criteria.uniqueResult();
            System.out.println("Min Track Duration = " + minDuration);

            criteria.setProjection(Projections.avg("duration"));
            Double avgDuration = (Double) criteria.uniqueResult();
            System.out.println("Avg Track Duration = " + avgDuration);

            criteria.setProjection(Projections.sum("duration"));
            Long totalDuration = (Long) criteria.uniqueResult();
            System.out.println("Total Track Duration = " + totalDuration);
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I select a single record using Hibernate Criteria?

The Criteria.uniqueResult() method make it easier to query a single instance of a persistence object. When no persistence found this method will return a null value.

package org.kodejava.hibernate;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.kodejava.hibernate.model.Genre;

public class UniqueResultExample {
    public static Session getSession() throws HibernateException {
        String cfg = "hibernate.cfg.xml";
        SessionFactory sessionFactory = new Configuration().configure(cfg)
                .buildSessionFactory();
        return sessionFactory.openSession();
    }

    public static void main(String[] args) {
        try (Session session = getSession()) {
            Criteria criteria = session.createCriteria(Genre.class)
                    .add(Restrictions.eq("id", 1L));

            // Convenience method to return a single instance that matches
            // the query, or null if the query returns no results.
            Object result = criteria.uniqueResult();
            if (result != null) {
                Genre genre = (Genre) result;
                System.out.println("Genre = " + genre.getName());
            }
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central