Hibernate es una de las herramientas ORM más utilizadas para aplicaciones Java. Se utiliza mucho en aplicaciones empresariales para operaciones de bases de datos. Por eso, decidí escribir una publicación sobre preguntas de entrevistas sobre Hibernate para repasar tus conocimientos antes de la entrevista. Tanto si eres novato como si tienes experiencia, tener un buen conocimiento de la herramienta ORM de Hibernate te ayudará a superar la entrevista. Aquí te doy importantes preguntas de entrevistas sobre Hibernate con respuestas para ayudarte a repasar tus conocimientos e impresionar a tu entrevistador. Al igual que otras publicaciones sobre preguntas de entrevistas, es probable que añada más preguntas a esta lista en el futuro, por lo que es posible que quieras marcarla como favorita para futuras referencias. Recientemente he escrito muchas publicaciones sobre Hibernate, la mayoría de ellas contienen proyectos completos descargables. Te proporcionaré referencias a ellas cuando sea necesario y podrás consultarlas para refrescar tus conocimientos.
Preguntas de la entrevista de Hibernate
- ¿Qué es Hibernate Framework?
- ¿Qué es Java Persistence API (JPA)?
- ¿Cuáles son los beneficios importantes de utilizar Hibernate Framework?
- ¿Cuáles son las ventajas de Hibernate sobre JDBC?
- Nombra algunas interfaces importantes del framework Hibernate.
- ¿Qué es el archivo de configuración de hibernación?
- ¿Qué es el archivo de mapeo de hibernación?
- Nombra algunas anotaciones importantes utilizadas para el mapeo de Hibernate.
- ¿Qué es Hibernate SessionFactory y cómo configurarlo?
- ¿Hibernate SessionFactory es seguro para subprocesos?
- ¿Qué es la sesión de Hibernación y cómo obtenerla?
- ¿La sesión de Hibernate es segura para subprocesos?
- ¿Cuál es la diferencia entre openSession y getCurrentSession?
- ¿Cuál es la diferencia entre el método get() y load() de Hibernate Session?
- ¿Qué es el almacenamiento en caché de Hibernate? ¿Qué es el almacenamiento en caché de primer nivel de Hibernate?
- ¿Cómo configurar el caché de segundo nivel de Hibernate usando EHCache?
- ¿Cuáles son los diferentes estados de un bean de entidad?
- ¿Para qué sirve la llamada merge() de Hibernate Session?
- ¿Cuál es la diferencia entre los métodos save(), saveOrUpdate() y persist() de Hibernate?
- ¿Qué pasará si no tenemos un constructor sin argumentos en el bean de entidad?
- ¿Cuál es la diferencia entre una colección ordenada y una colección ordenada? ¿Cuál es mejor?
- ¿Cuáles son los tipos de colecciones en Hibernate?
- ¿Cómo implementar Joins en Hibernate?
- ¿Por qué no deberíamos hacer que la clase Entidad sea final?
- ¿Qué es HQL y cuáles son sus beneficios?
- ¿Qué es la caché de consultas en Hibernate?
- ¿Podemos ejecutar consultas SQL nativas en Hibernate?
- ¿Cuál es el beneficio del soporte de consultas SQL nativas en Hibernate?
- ¿Qué es una consulta SQL con nombre?
- ¿Cuáles son los beneficios de una consulta SQL con nombre?
- ¿Cuál es el beneficio de la API de criterios de Hibernate?
- ¿Cómo registrar consultas SQL generadas por Hibernate en archivos de registro?
- ¿Qué es Hibernate Proxy y cómo ayuda en la carga diferida?
- ¿Cómo implementar relaciones en hibernación?
- ¿Cómo funciona la gestión de transacciones en Hibernate?
- ¿Qué es la cascada y cuáles son los diferentes tipos de cascada?
- ¿Cómo integrar el registro de log4j en la aplicación Hibernate?
- ¿Cómo utilizar el servidor de aplicaciones JNDI DataSource con el marco Hibernate?
- ¿Cómo integrar los frameworks Hibernate y Spring?
- ¿Qué es la clase HibernateTemplate?
- ¿Cómo integrar Hibernate con aplicaciones web Servlet o Struts2?
- ¿Qué patrones de diseño se utilizan en el marco Hibernate?
- ¿Cuáles son las mejores prácticas a seguir con el marco Hibernate?
- ¿Qué es Hibernate Validator Framework?
- ¿Cuál es el beneficio del complemento Hibernate Tools para Eclipse?
Preguntas y respuestas de la entrevista de Hibernate
-
¿Qué es Hibernate Framework?
El mapeo relacional de objetos u ORM es la técnica de programación para mapear objetos del modelo de dominio de aplicación a las tablas de bases de datos relacionales. Hibernate es una herramienta ORM basada en Java que proporciona un marco para mapear objetos del dominio de aplicación a las tablas de bases de datos relacionales y viceversa. Hibernate proporciona una implementación de referencia de la API de persistencia de Java, lo que la convierte en una gran opción como herramienta ORM con los beneficios del acoplamiento flexible. Podemos usar la API de persistencia de Hibernate para operaciones CRUD. El marco de Hibernate proporciona la opción de mapear objetos java simples a tablas de bases de datos tradicionales con el uso de anotaciones JPA, así como una configuración basada en XML. De manera similar, las configuraciones de Hibernate son flexibles y se pueden realizar desde un archivo de configuración XML, así como mediante programación. Para obtener una descripción general rápida del uso del marco de Hibernate, puede consultar el Tutorial para principiantes de Hibernate .
-
¿Qué es Java Persistence API (JPA)?
La API de persistencia de Java (JPA) proporciona especificaciones para gestionar los datos relacionales en las aplicaciones. La versión actual de JPA 2.1 se inició en julio de 2011 como JSR 338. La versión final de JPA 2.1 se aprobó el 22 de mayo de 2013. Las especificaciones de JPA se definen con anotaciones en el paquete javax.persistence. El uso de anotaciones de JPA nos ayuda a escribir código independiente de la implementación.
-
¿Cuáles son los beneficios importantes de utilizar Hibernate Framework?
Algunos de los beneficios importantes de utilizar el marco de hibernación son:
- Hibernate elimina todo el código repetitivo que viene con JDBC y se encarga de administrar los recursos, para que podamos centrarnos en la lógica empresarial.
- El marco Hibernate proporciona soporte para XML y anotaciones JPA, lo que hace que nuestra implementación de código sea independiente.
- Hibernate ofrece un potente lenguaje de consulta (HQL) similar a SQL. Sin embargo, HQL está totalmente orientado a objetos y comprende conceptos como herencia, polimorfismo y asociación.
- Hibernate es un proyecto de código abierto de Red Hat Community y se utiliza en todo el mundo. Esto lo convierte en una mejor opción que otras porque la curva de aprendizaje es corta y hay toneladas de documentación en línea y ayuda disponible fácilmente en foros.
- Hibernate es fácil de integrar con otros marcos Java EE, es tan popular que Spring Framework proporciona soporte integrado para integrar Hibernate con aplicaciones Spring.
- Hibernate admite la inicialización diferida mediante objetos proxy y realiza consultas de base de datos reales solo cuando es necesario.
- La caché de hibernación nos ayuda a obtener un mejor rendimiento.
- Para las características específicas del proveedor de la base de datos, Hibernate es adecuado porque también podemos ejecutar consultas SQL nativas. En general, Hibernate es la mejor opción en el mercado actual para la herramienta ORM, contiene todas las características que necesitará en una herramienta ORM.
-
¿Cuáles son las ventajas de Hibernate sobre JDBC?
Algunas de las ventajas importantes del framework Hibernate sobre JDBC son:
- Hibernate elimina gran parte del código repetitivo que viene con la API JDBC, el código se ve más limpio y legible.
- Hibernate admite herencia, asociaciones y colecciones. Estas funciones no están presentes en la API de JDBC.
- Hibernate proporciona de forma implícita la gestión de transacciones; de hecho, la mayoría de las consultas no se pueden ejecutar fuera de la transacción. En la API de JDBC, necesitamos escribir código para la gestión de transacciones mediante confirmación y reversión. Obtenga más información en Gestión de transacciones de JDBC .
- La API de JDBC genera
SQLExceptionuna excepción que es una excepción comprobada, por lo que necesitamos escribir una gran cantidad de código de bloque try-catch. La mayoría de las veces, es redundante en cada llamada JDBC y se utiliza para la gestión de transacciones. Hibernate encapsula las excepciones JDBC y las excepciones que se generanJDBCExceptionoHibernateExceptionno se comprueban, por lo que no necesitamos escribir código para manejarlas. La gestión de transacciones integrada de Hibernate elimina el uso de bloques try-catch. - El lenguaje de consulta Hibernate (HQL) está más orientado a objetos y es similar al lenguaje de programación Java. Para JDBC, necesitamos escribir consultas SQL nativas.
- Hibernate admite el almacenamiento en caché, lo que es mejor para el rendimiento; las consultas JDBC no se almacenan en caché, por lo tanto, el rendimiento es bajo.
- Hibernate proporciona una opción a través de la cual también podemos crear tablas de bases de datos, porque las tablas JDBC deben existir en la base de datos.
- La configuración de Hibernate nos ayuda a utilizar conexiones tipo JDBC, así como también JNDI DataSource para el grupo de conexiones. Esta es una característica muy importante en las aplicaciones empresariales y no está presente en la API de JDBC.
- Hibernate admite anotaciones JPA, por lo que el código es independiente de la implementación y se puede reemplazar fácilmente con otras herramientas ORM. El código JDBC está estrechamente vinculado a la aplicación.
-
Nombra algunas interfaces importantes del framework Hibernate.
Some of the important interfaces of Hibernate framework are:1. **SessionFactory (org.hibernate.SessionFactory)**: SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We need to initialize SessionFactory once and then we can cache and reuse it. SessionFactory instance is used to get the Session objects for database operations.2. **Session (org.hibernate.Session)**: Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC `java.sql.Connection` and works as a factory for `org.hibernate.Transaction`. We should open session only when it's required and close it as soon as we are done using it. Session object is the interface between java application code and hibernate framework and provide methods for CRUD operations.3. **Transaction (org.hibernate.Transaction)**: Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. A org.hibernate.Session might span multiple org.hibernate.Transaction in some cases.
-
¿Qué es el archivo de configuración de hibernación?
Hibernate configuration file contains database specific configurations and used to initialize SessionFactory. We provide database credentials or JNDI resource information in the hibernate configuration xml file. Some other important parts of hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.
-
¿Qué es el archivo de mapeo de hibernación?
Hibernate mapping file is used to define the entity bean fields and database table column mappings. We know that JPA annotations can be used for mapping but sometimes XML mapping file comes handy when we are using third party classes and we can't use annotations.
-
Nombra algunas anotaciones importantes utilizadas para el mapeo de Hibernate.
Hibernate supports JPA annotations and it has some other annotations in `org.hibernate.annotations` package. Some of the important JPA and hibernate annotations used are:1. **javax.persistence.Entity**: Used with model classes to specify that they are entity beans.2. **javax.persistence.Table**: Used with entity beans to define the corresponding table name in database.3. **javax.persistence.Access**: Used to define the access type, either field or property. Default value is field and if you want hibernate to use getter/setter methods then you need to set it to property.4. **javax.persistence.Id**: Used to define the primary key in the entity bean.5. **javax.persistence.EmbeddedId**: Used to define composite primary key in the entity bean.6. **javax.persistence.Column**: Used to define the column name in database table.7. **javax.persistence.GeneratedValue**: Used to define the strategy to be used for generation of primary key. Used in conjunction with `javax.persistence.GenerationType` enum.8. **javax.persistence.OneToOne**: Used to define the one-to-one mapping between two entity beans. We have other similar annotations as `OneToMany`, `ManyToOne` and `ManyToMany`9. **org.hibernate.annotations.Cascade**: Used to define the cascading between two entity beans, used with mappings. It works in conjunction with `org.hibernate.annotations.CascadeType`10. **javax.persistence.PrimaryKeyJoinColumn**: Used to define the property for foreign key. Used with `org.hibernate.annotations.GenericGenerator` and `org.hibernate.annotations.Parameter`Here are two classes showing usage of these annotations.```package com.journaldev.hibernate.model;import javax.persistence.Access;import javax.persistence.AccessType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.OneToOne;import javax.persistence.Table;import org.hibernate.annotations.Cascade;@Entity@Table(name = "EMPLOYEE")@Access(value=AccessType.FIELD)public class Employee {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "emp_id")private long id;@Column(name = "emp_name")private String name;@OneToOne(mappedBy = "employee")@Cascade(value = org.hibernate.annotations.CascadeType.ALL)private Address address;//getter setter methods}``````package com.journaldev.hibernate.model;import javax.persistence.Access;import javax.persistence.AccessType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.OneToOne;import javax.persistence.PrimaryKeyJoinColumn;import javax.persistence.Table;import org.hibernate.annotations.GenericGenerator;import org.hibernate.annotations.Parameter;@Entity@Table(name = "ADDRESS")@Access(value=AccessType.FIELD)public class Address {@Id@Column(name = "emp_id", unique = true, nullable = false)@GeneratedValue(generator = "gen")@GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") })private long id;@Column(name = "address_line1")private String addressLine1;@OneToOne@PrimaryKeyJoinColumnprivate Employee employee;//getter setter methods}```
-
¿Qué es Hibernate SessionFactory y cómo configurarlo?
SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible to read the hibernate configuration parameters and connect to the database and provide Session objects. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory. The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping. SessionFactory also provide methods to get the Class metadata and Statistics instance to get the stats of query executions, second level cache details etc.
-
¿Hibernate SessionFactory es seguro para subprocesos?
Internal state of SessionFactory is immutable, so it's thread safe. Multiple threads can access it simultaneously to get Session instances.
-
¿Qué es la sesión de Hibernación y cómo obtenerla?
Hibernate Session is the interface between java application layer and hibernate. This is the core interface used to perform database operations. Lifecycle of a session is bound by the beginning and end of a transaction. Session provide methods to perform create, read, update and delete operations for a persistent object. We can execute HQL queries, SQL native queries and create criteria using Session object.
-
¿La sesión de Hibernate es segura para subprocesos?
Hibernate Session object is not thread safe, every thread should get it's own session instance and close it after it's work is finished.
-
¿Cuál es la diferencia entre openSession y getCurrentSession?
Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file. Since this session object belongs to the hibernate context, we don't need to close it. Once the session factory is closed, this session object gets closed.```property name="hibernate.current_session_context_class"thread/property```Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment. There is another method openStatelessSession() that returns stateless session, for more details with examples please read [Hibernate openSession vs getCurrentSession](/community/tutorials/hibernate-sessionfactory).
-
¿Cuál es la diferencia entre el método get() y load() de Hibernate Session?
Hibernate session comes with different methods to load data from database. get and load are most used methods, at first look they seems similar but there are some differences between them.1. get() loads the data as soon as it's called whereas load() returns a proxy object and loads data only when it's actually required, so load() is better because it support lazy loading.2. Since load() throws exception when data is not found, we should use it only when we know data exists.3. We should use get() when we want to make sure data exists in the database.For clarification regarding the differences, please read [Hibernate get vs load](/community/tutorials/hibernate-session-get-vs-load-difference-with-examples).
-
¿Qué es el almacenamiento en caché de Hibernate? ¿Qué es el almacenamiento en caché de primer nivel de Hibernate?
As the name suggests, hibernate caches query data to make our application faster. Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application. Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely. Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost. For better explanation, please read [Hibernate First Level Cache](/community/tutorials/hibernate-caching-first-level-cache).
-
¿Cómo configurar el caché de segundo nivel de Hibernate usando EHCache?
EHCache is the best choice for utilizing hibernate second level cache. Following steps are required to enable EHCache in hibernate application.- Add hibernate-ehcache dependency in your maven project, if it's not maven then add corresponding jars. ``` dependency groupIdorg.hibernate/groupId artifactIdhibernate-ehcache/artifactId version4.3.5.Final/version /dependency ``` - Add below properties in hibernate configuration file. ``` property name="hibernate.cache.region.factory_class"org.hibernate.cache.ehcache.EhCacheRegionFactory/property !-- For singleton factory -- !-- property name="hibernate.cache.region.factory_class"org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory/property -- !-- enable second level cache and query cache -- property name="hibernate.cache.use_second_level_cache"true/property property name="hibernate.cache.use_query_cache"true/property property name="net.sf.ehcache.configurationResourceName"/myehcache.xml/property ``` - Create EHCache configuration file, a sample file myehcache.xml would look like below. ``` ?xml version="1.0" encoding="UTF-8"? ehcache xmlns_xsi="https://www.w3.org/2001/XMLSchema-instance" xsi_noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true" diskStore path="java.io.tmpdir/ehcache" / defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" statistics="true" persistence strategy="localTempSwap" / /defaultCache cache name="employee" maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="10" persistence strategy="localTempSwap" / /cache cache name="org.hibernate.cache.internal.StandardQueryCache" maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120" persistence strategy="localTempSwap" / /cache cache name="org.hibernate.cache.spi.UpdateTimestampsCache" maxEntriesLocalHeap="5000" eternal="true" persistence strategy="localTempSwap" / /cache /ehcache ``` - Annotate entity beans with @Cache annotation and caching strategy to use. For example, ``` import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name = "ADDRESS") @Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee") public class Address { } ``` That's it, we are done. Hibernate will use the EHCache for second level caching, read [Hibernate EHCache Example](/community/tutorials/hibernate-ehcache-hibernate-second-level-cache) for a complete example with explanation.
-
¿Cuáles son los diferentes estados de un bean de entidad?
An entity bean instance can exist is one of the three states.1. **Transient**: When an object is never persisted or associated with any session, it's in transient state. Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete().2. **Persistent**: When an object is associated with a unique session, it's in persistent state. Any instance returned by a get() or load() method is persistent.3. **Detached**: When an object is previously persistent but not associated with any session, it's in detached state. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().
-
¿Para qué sirve la llamada merge() de Hibernate Session?
Hibernate merge can be used to update existing values, however this method create a copy from the passed entity object and return it. The returned object is part of persistent context and tracked for any changes, passed object is not tracked. For example program, read [Hibernate merge](/community/tutorials/hibernate-session-merge-vs-update-save-saveorupdate-persist-example).
-
¿Cuál es la diferencia entre los métodos save(), saveOrUpdate() y persist() de Hibernate?
Hibernate save can be used to save entity to database. Problem with save() is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also save returns the generated id immediately. Hibernate persist is similar to save with transaction. I feel it's better than save because we can't use it outside the boundary of transaction, so all the object mappings are preserved. Also persist doesn't return the generated id immediately, so data persistence happens when needed. Hibernate saveOrUpdate results into insert or update queries based on the provided data. If the data is present in the database, update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if session is not flushed. For example usage of these methods, read [Hibernate save vs persist](/community/tutorials/hibernate-session-merge-vs-update-save-saveorupdate-persist-example).
-
¿Qué pasará si no tenemos un constructor sin argumentos en el bean de entidad?
Hibernate uses [Reflection API](/community/tutorials/java-reflection-example-tutorial) to create instance of Entity beans, usually when you call get() or load() methods. The method `Class.newInstance()` is used for this and it requires no-args constructor. So if you won't have no-args constructor in entity beans, hibernate will fail to instantiate it and you will get `HibernateException`.
-
¿Cuál es la diferencia entre una colección ordenada y una colección ordenada? ¿Cuál es mejor?
When we use Collection API sorting algorithms to sort a collection, it's called sorted list. For small collections, it's not much of an overhead but for larger collections it can lead to slow performance and OutOfMemory errors. Also the entity beans should implement `Comparable` or `Comparator` interface for it to work, read more at [java object list sorting](/community/tutorials/comparable-and-comparator-in-java-example). If we are using Hibernate framework to load collection data from database, we can use it's Criteria API to use "order by" clause to get ordered list. Below code snippet shows you how to get it.```ListEmployee empList = session.createCriteria(Employee.class).addOrder(Order.desc("id")).list();```Ordered list is better than sorted list because the actual sorting is done at database level, that is fast and doesn't cause memory issues.
-
¿Cuáles son los tipos de colecciones en Hibernate?
There are five collection types in hibernate used for one-to-many relationship mappings.1. Bag2. Set3. List4. Array5. Map
-
¿Cómo implementar Joins en Hibernate?
There are various ways to implement joins in hibernate.- Using associations such as one-to-one, one-to-many etc.- Using JOIN in the HQL query. There is another form "join fetch" to load associated data simultaneously, no lazy loading.- We can fire native sql query and use join keyword.
-
¿Por qué no deberíamos hacer que la clase Entidad sea final?
Hibernate use proxy classes for lazy loading of data, only when it's needed. This is done by extending the entity bean, if the entity bean will be final then lazy loading will not be possible, hence low performance.
-
¿Qué es HQL y cuáles son sus beneficios?
Hibernate Framework comes with a powerful object-oriented query language – Hibernate Query Language (HQL). It’s very similar to SQL except that we use Objects instead of table names, that makes it more close to object oriented programming. Hibernate query language is case-insensitive except for java class and variable names. So SeLeCT is the same as sELEct is the same as SELECT, but com.journaldev.model.Employee is not same as com.journaldev.model.EMPLOYEE. The HQL queries are cached but we should avoid it as much as possible, otherwise we will have to take care of associations. However it's a better choice than native sql query because of Object-Oriented approach. Read more at [HQL Example](/community/tutorials/hibernate-query-language-hql-example-tutorial).
-
¿Qué es la caché de consultas en Hibernate?
Hibernate implements a cache region for queries resultset that integrates closely with the hibernate second-level cache. This is an optional feature and requires additional steps in code. This is only useful for queries that are run frequently with the same parameters. First of all we need to configure below property in hibernate configuration file.```property name="hibernate.cache.use_query_cache"true/property```And in code, we need to use setCacheable(true) method of Query, quick example looks like below.```Query query = session.createQuery("from Employee");query.setCacheable(true);query.setCacheRegion("ALL_EMP");```
-
¿Podemos ejecutar consultas SQL nativas en Hibernate?
Hibernate provide option to execute native SQL queries through the use of `SQLQuery` object. For normal scenarios, it is however not the recommended approach because we loose benefits related to hibernate association and hibernate first level caching. Read more at [Hibernate Native SQL Query Example](/community/tutorials/hibernate-native-sql-query-example).
-
¿Cuál es el beneficio del soporte de consultas SQL nativas en Hibernate?
Native SQL Query comes handy when we want to execute database specific queries that are not supported by Hibernate API such as query hints or the CONNECT keyword in Oracle Database.
-
¿Qué es una consulta SQL con nombre?
Hibernate provides Named Query that we can define at a central location and use them anywhere in the code. We can created named queries for both HQL and Native SQL. Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery.
-
¿Cuáles son los beneficios de una consulta SQL con nombre?
Hibernate Named Query helps us in grouping queries at a central location rather than letting them scattered all over the code. Hibernate Named Query syntax is checked when the hibernate session factory is created, thus making the application fail fast in case of any error in the named queries. Hibernate Named Query is global, means once defined it can be used throughout the application. However one of the major disadvantage of Named query is that it’s hard to debug, because we need to find out the location where it’s defined.
-
¿Cuál es el beneficio de la API de criterios de Hibernate?
Hibernate provides Criteria API that is more object oriented for querying the database and getting results. We can’t use Criteria to run update or delete queries or any DDL statements. It’s only used to fetch the results from the database using more object oriented ap