Hibernate Framework Assessment — Questions and Answers
Question 1: Which property configures the C3P0 connection pool minimum size in Hibernate?
- hibernate.connection.pool_size
- hibernate.pool.min
- hibernate.c3p0.min_size (Correct answer)
- c3p0.minPoolSize
Correct answer: hibernate.c3p0.min_size
The hibernate.c3p0.min_size property sets the minimum number of JDBC connections in the C3P0 pool.
Question 2: What does the 'hibernate.order_inserts=true' property do?
- Orders inserts by primary key
- Prevents duplicate inserts
- Groups INSERT statements by entity type to improve JDBC batch efficiency (Correct answer)
- Inserts rows in alphabetical order
Correct answer: Groups INSERT statements by entity type to improve JDBC batch efficiency
Ordering inserts by entity type allows Hibernate to batch together INSERT statements for the same table, maximizing JDBC batch efficiency.
Question 3: What is the purpose of the persistence.xml file in JPA/Hibernate?
- Lists all Java packages to scan
- Configures HTTP endpoints
- Defines a persistence unit with provider, data source, and entity classes (Correct answer)
- Stores SQL migration scripts
Correct answer: Defines a persistence unit with provider, data source, and entity classes
persistence.xml defines a JPA persistence unit, specifying the provider (Hibernate), datasource, and entity classes.
Question 4: Which method evicts all entities of a given class from the second-level cache?
- sessionFactory.getCache().evictEntityData(EntityClass.class) (Correct answer)
- cache.evict(EntityClass.class)
- session.clearCache(EntityClass.class)
- sessionFactory.evict(EntityClass.class)
Correct answer: sessionFactory.getCache().evictEntityData(EntityClass.class)
The evictEntityData() method on the Cache object obtained from SessionFactory removes all cached instances of a specific entity class.
Question 5: Which of the following statements concerning Hibernate's configuration component is correct?
- The Configuration object is the first Hibernate object you create in any Hibernate application
- All of the above (Correct answer)
- The Configuration object represents a configuration or properties files required by the Hibernate
- The Configuration object is usually created only once during application initialization
Correct answer: All of the above
Explanation: <br> The Configuration object is the first Hibernate object you create in any Hibernate application, and it's normally only used once during the initialization process. It is a configuration or properties file that Hibernate requires.
Question 6: Which of the following statements accurately defines Hibernate's Transient and Detached Objects?
- Long-lived, multi threaded objects
- None of the above
- Short-lived, single threaded objects (Correct answer)
Correct answer: Short-lived, single threaded objects
Explanation: <br> A communication between the application and the persistent store is represented by a single-threaded, short-lived object. It covers a JDBC connection and acts as a Transaction factory. When browsing the object graph or looking up items by identifier, Session must have a mandatory first-level cache of persistent objects.
Question 7: Which annotation is used to mark a class as a JPA entity in Hibernate?
- @Table
- @Entity (Correct answer)
- @Model
- @Persistent
Correct answer: @Entity
The @Entity annotation marks a Java class as a JPA-managed persistent entity.
Question 8: What does hibernate.hbm2ddl.auto=validate do?
- Drops all tables on shutdown
- Creates missing tables
- Validates the schema against mappings without making changes (Correct answer)
- Updates schema to match entities
Correct answer: Validates the schema against mappings without making changes
The validate option checks that the database schema matches the Hibernate mappings and throws an error if they differ.
Question 9: What does HQL stand for in Hibernate?
- Hibernate Query Language (Correct answer)
- High Query Language
- Hibernate Question Language
- Hybrid Query Language
Correct answer: Hibernate Query Language
HQL stands for Hibernate Query Language, an object-oriented query language similar to SQL but operating on entity classes.
Question 10: Which annotation specifies the foreign key column name in a @ManyToOne relationship?
- @JoinTable
- @ForeignKey
- @Column
- @JoinColumn (Correct answer)
Correct answer: @JoinColumn
@JoinColumn specifies the name of the foreign key column in the owning entity's table that references the primary key of the related entity.
Question 11: How do you set a named parameter in an HQL query?
- query.set("name", value)
- query.setParameter("name", value) (Correct answer)
- query.bind("name", value)
- query.addParam("name", value)
Correct answer: query.setParameter("name", value)
The setParameter() method binds a value to a named parameter (prefixed with : in HQL) in the query.
Question 12: What query hint can be used to force Hibernate to use a specific database index?
- query.useIndex("indexName")
- query.addQueryHint("indexName") (Correct answer)
- query.hint("indexName")
- query.forceIndex("indexName")
Correct answer: query.addQueryHint("indexName")
The addQueryHint() method passes a native database index hint to the generated SQL, guiding the query planner to use a specific index.
Question 13: What does the hibernate.format_sql property do?
- Compresses SQL statements
- Formats SQL output with line breaks for readability (Correct answer)
- Converts SQL to a standard dialect
- Validates SQL before execution
Correct answer: Formats SQL output with line breaks for readability
Setting hibernate.format_sql=true causes Hibernate to pretty-print SQL statements with indentation and line breaks.
Question 14: What is the first-level cache in Hibernate?
- A database-level cache
- A distributed cache shared across nodes
- A query result cache
- The Session cache that stores entities within a single session (Correct answer)
Correct answer: The Session cache that stores entities within a single session
The first-level cache is the Session's built-in identity map that caches entities for the duration of a single Session.
Question 15: What is the purpose of @BatchSize in Hibernate?
- Configures the connection pool size
- Loads lazy collections in batches to reduce the number of SQL queries (Correct answer)
- Sets the JDBC batch insert size
- Limits the number of query results
Correct answer: Loads lazy collections in batches to reduce the number of SQL queries
@BatchSize tells Hibernate to load lazy associations in batches of N items, reducing N+1 queries to ceil(N/batch_size)+1 queries.
Question 16: What does setting hibernate.show_sql=true do?
- Caches SQL queries
- Logs all generated SQL statements to the console (Correct answer)
- Validates SQL syntax before execution
- Enables SQL formatting in results
Correct answer: Logs all generated SQL statements to the console
Setting hibernate.show_sql=true causes Hibernate to print every SQL statement it executes to standard output.
Question 17: Which Hibernate statistic tells you the second-level cache hit ratio?
- Statistics.getSecondLevelCacheHitCount() / (hit + miss) (Correct answer)
- Statistics.getCacheRatio()
- Statistics.getL2HitRate()
- Statistics.getCacheHitPercent()
Correct answer: Statistics.getSecondLevelCacheHitCount() / (hit + miss)
You can calculate the hit ratio by dividing getSecondLevelCacheHitCount() by the sum of hit and miss counts from the Statistics object.
Question 18: What happens if you call session.flush() inside a transaction?
- The transaction is committed
- All cached objects are cleared
- Hibernate synchronizes in-memory state with the database without committing (Correct answer)
- The session is closed
Correct answer: Hibernate synchronizes in-memory state with the database without committing
flush() forces Hibernate to execute pending SQL statements to synchronize the persistence context with the database, but the transaction remains open.
Question 19: Which HQL keyword is used to perform an inner join between two entities?
- JOIN (Correct answer)
- LINK
- MERGE
- CONNECT
Correct answer: JOIN
HQL uses the JOIN keyword to perform joins between related entities based on their mapped associations.
Question 20: What does session.clear() do in Hibernate?
- Deletes all rows from the database
- Closes the session
- Clears the first-level cache, detaching all managed entities (Correct answer)
- Commits the current transaction
Correct answer: Clears the first-level cache, detaching all managed entities
session.clear() removes all entities from the Session's first-level cache, releasing their memory without closing the session.
Question 21: Which method opens a new Hibernate Session from a SessionFactory?
- openSession() (Correct answer)
- getSession()
- newSession()
- createSession()
Correct answer: openSession()
The openSession() method on SessionFactory opens a new database session for performing persistence operations.
Question 22: Which annotation marks a collection as a one-to-many relationship?
- @ForeignKey
- @HasMany
- @OneToMany (Correct answer)
- @CollectionOf
Correct answer: @OneToMany
The @OneToMany annotation maps a collection field where one entity owns many instances of another entity.
Question 23: Which Hibernate property maps Java types to SQL types for a specific vendor?
- hibernate.dialect (Correct answer)
- hibernate.type.mapping
- hibernate.vendor.types
- hibernate.sql.types
Correct answer: hibernate.dialect
The hibernate.dialect property selects the vendor-specific dialect class that handles Java-to-SQL type mappings.
Question 24: What does session.merge() do in Hibernate?
- Copies state from a detached entity into a new managed entity (Correct answer)
- Merges two entities into one
- Synchronizes the session with the database
- Deletes and re-inserts an entity
Correct answer: Copies state from a detached entity into a new managed entity
merge() takes a detached entity, copies its state into a managed entity with the same identifier, and returns the managed instance.
Question 25: Which annotation creates a join table for a many-to-many relationship?
- @RelationTable
- @JoinTable (Correct answer)
- @ManyToMany
- @CrossTable
Correct answer: @JoinTable
The @JoinTable annotation specifies the join table and its columns used to implement a many-to-many relationship.
Question 26: What does FetchType.EAGER do to query performance?
- Can cause excessive data loading and degrade performance with large datasets (Correct answer)
- Reduces the number of queries
- Has no performance impact
- Always improves performance
Correct answer: Can cause excessive data loading and degrade performance with large datasets
EAGER loading always fetches associations, even when not needed, which can result in loading huge datasets and degrading performance.
Question 27: What does session.refresh(entity) do in Hibernate?
- Validates the entity constraints
- Reloads the entity state from the database, overwriting in-memory changes (Correct answer)
- Clears the entire session cache
- Saves the entity to the database
Correct answer: Reloads the entity state from the database, overwriting in-memory changes
refresh() re-reads the entity's current state from the database, discarding any in-memory modifications to synchronize with the latest persisted data.
Question 28: In a @JoinTable annotation, which attribute defines the foreign key columns referencing the inverse (non-owning) entity?
- inverseJoinColumns (Correct answer)
- referencedColumns
- joinColumns
- foreignKeyColumns
Correct answer: inverseJoinColumns
'inverseJoinColumns' specifies the join table columns that reference the primary key of the non-owning (inverse) entity in the relationship.
Question 29: What does session.evict(entity) do in Hibernate?
- Commits the entity changes
- Deletes the entity from the database
- Reloads the entity from the database
- Removes the entity from the first-level cache without deleting from the database (Correct answer)
Correct answer: Removes the entity from the first-level cache without deleting from the database
evict() removes a specific entity from the Session's first-level cache, detaching it from the persistence context.
Question 30: In Hibernate, what is Query Level Cache?
- None of the above
- The query-level cache is the Session based cache
- The query-level cache is a query resultset cache that works in tandem with the second-level cache. (Correct answer)
- Both of the above
Correct answer: The query-level cache is a query resultset cache that works in tandem with the second-level cache.
Explanation: <br> Hibernate includes a query resultset cache that works in tandem with the second-level cache.
Question 31: Which Hibernate API allows building queries programmatically without writing HQL strings?
- Query Builder
- JPQL Builder
- QueryDSL
- Criteria API (Correct answer)
Correct answer: Criteria API
The Criteria API provides a type-safe, programmatic way to build Hibernate queries without writing query strings.
Question 32: When should you utilize a read-only concurrency strategy?
- None of the above
- Use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions
- Use this method if data is rarely updated and a slight chance of stale data isn't a major concern. (Correct answer)
- Use it for reference data only
Correct answer: Use this method if data is rarely updated and a slight chance of stale data isn't a major concern.
Explanation: <br> The read-only concurrency method is appropriate for data that does not change. It should only be used as a source of information.
Question 33: In a many-to-many relationship, which annotation is used to define the join table and its columns?
- @JoinColumn
- @JoinTable (Correct answer)
- @RelationTable
- @ManyToMany
Correct answer: @JoinTable
@JoinTable specifies the intermediate join table used by a many-to-many relationship, including the names of the join columns on both sides.
Question 34: Which annotation is used to define a one-to-many relationship in Hibernate?
- @ManyToMany
- @OneToMany (Correct answer)
- @OneToOne
- @ManyToOne
Correct answer: @OneToMany
@OneToMany maps a collection field in the parent entity to multiple records in the child entity.
Question 35: What is the 'N+1 select problem' in the context of Hibernate associations?
- N entities referencing 1 shared foreign key causing conflicts
- 1 initial query to load N parent entities followed by N additional queries to load each entity's associations (Correct answer)
- N+1 join conditions making queries too complex
- N queries needed to insert 1 record with associations
Correct answer: 1 initial query to load N parent entities followed by N additional queries to load each entity's associations
The N+1 problem occurs when loading N parent entities triggers N separate queries to fetch each parent's associated child collection, resulting in N+1 total queries.
Question 36: Which Hibernate property enables second-level cache?
- hibernate.second.cache
- hibernate.cache.enabled
- hibernate.cache.use_second_level_cache (Correct answer)
- hibernate.enable.l2cache
Correct answer: hibernate.cache.use_second_level_cache
Setting hibernate.cache.use_second_level_cache=true activates the second-level cache in Hibernate.
Question 37: Which method adds a WHERE condition to a CriteriaQuery?
- criteriaQuery.restrict(predicate)
- criteriaQuery.condition(predicate)
- criteriaQuery.filter(predicate)
- criteriaQuery.where(predicate) (Correct answer)
Correct answer: criteriaQuery.where(predicate)
The where() method on CriteriaQuery accepts one or more Predicate objects to define the filtering conditions.
Question 38: Which of the following statements concerning the @Id annotation is correct?
- Hibernate assumes that it should access properties on an object directly through fields at runtime
- Hibernate detects that the @ld annotation is on a field
- Both of the above (Correct answer)
- None ot these
Correct answer: Both of the above
Explanation: <br> Hibernate recognizes the @Id annotation on a field and thinks that during runtime, it should be able to access attributes on an object directly through fields.
Question 39: What is a subselect fetch strategy in Hibernate?
- Loads parent and child in separate subqueries
- Fetches from a subview in the database
- Loads all lazy collections using a single IN subselect query (Correct answer)
- Loads entities using subqueries in WHERE clauses
Correct answer: Loads all lazy collections using a single IN subselect query
The subselect fetch strategy loads all lazy collections for a result set in a single additional query using an IN clause, avoiding N+1 queries.
Question 40: Which second-level cache provider is commonly used with Hibernate?
- Hazelcast
- Memcached
- Ehcache (Correct answer)
- Redis
Correct answer: Ehcache
Ehcache is the most commonly used and well-integrated second-level cache provider for Hibernate in enterprise Java applications.
Question 41: Which annotation enables second-level caching on a Hibernate entity?
- @SecondLevelCache
- @Cacheable
- @L2Cache
- @Cache (Correct answer)
Correct answer: @Cache
The @Cache annotation (from org.hibernate.annotations) configures second-level cache settings including the CacheConcurrencyStrategy for an entity.
Question 42: Which of the following statements concerning Hibernate's Query object is correct?
- All of the above (Correct answer)
- To retrieve data from the database and construct objects, use the Hibernate Query Language (HQL) string.
- To retrieve data from the database and construct objects, use the query objects SQL string.
- A Query instance is used to bind query parameters, limit the number of results returned by a query, and then execute the query.
Correct answer: All of the above
Explanation: <br> Query objects retrieve data from the database and construct objects using SQL or Hibernate Query Language (HQL) strings. A Query instance is used to bind query parameters, limit the number of results returned by a query, and then execute the query.
Question 43: What does the 'mappedBy' attribute in @OneToMany indicate?
- The cascade type for the association
- The fetch strategy for loading child entities
- The name of the database join table
- The field in the owning entity that maps the relationship (Correct answer)
Correct answer: The field in the owning entity that maps the relationship
'mappedBy' tells Hibernate that this side is the inverse (non-owning) side and points to the field in the child entity that owns the relationship.
Question 44: What does fetch = FetchType.EAGER mean for a Hibernate association?
- The associated entity uses batch size fetching
- The associated entity is loaded only when its getter is called
- The associated entity is loaded immediately along with the parent entity (Correct answer)
- The associated entity is loaded in a background thread
Correct answer: The associated entity is loaded immediately along with the parent entity
FetchType.EAGER tells Hibernate to load the associated entity immediately in the same query (or an additional query) when the parent entity is loaded.
Question 45: Which of the following is the hbm.xml file's root node?
- Hibernate-mapping (Correct answer)
- class-mapping
- class-config
- hibernate-config
Correct answer: Hibernate-mapping
Explanation: <br> One of Hibernate's most important features is Hibernate mappings. As attributes in your model, they establish the relationship between two database tables. One to One — It denotes a one-to-one correspondence between two tables.
Question 46: Which LockMode acquires a pessimistic write lock in Hibernate?
- LockMode.EXCLUSIVE
- LockMode.PESSIMISTIC_WRITE (Correct answer)
- LockMode.LOCK
- LockMode.WRITE
Correct answer: LockMode.PESSIMISTIC_WRITE
LockMode.PESSIMISTIC_WRITE requests a SELECT FOR UPDATE lock, preventing other transactions from reading or writing the row.
Question 47: Which annotation prevents a field from being persisted in Hibernate?
- @NotMapped
- @Exclude
- @Ignore
- @Transient (Correct answer)
Correct answer: @Transient
The @Transient annotation tells Hibernate to skip a field and not map it to any database column.
Question 48: What is the role of transaction.rollback() in Hibernate?
- Undoes all changes made since the transaction began (Correct answer)
- Closes the database connection
- Triggers a second flush
- Saves changes partially
Correct answer: Undoes all changes made since the transaction began
rollback() reverses all database changes made within the current transaction, returning the database to its state before the transaction started.
Question 49: What does @Version do in a Hibernate entity?
- Enables optimistic locking by tracking a version number (Correct answer)
- Counts the number of updates
- Stores the Hibernate version used
- Records the last modified timestamp
Correct answer: Enables optimistic locking by tracking a version number
The @Version annotation marks a field for optimistic locking, where Hibernate increments the version on each update to detect concurrent modifications.
Question 50: Which annotation configures the cache region name for a Hibernate entity?
- @Cache(region = "regionName") (Correct answer)
- @CacheRegion("regionName")
- @CacheName("regionName")
- @Region("regionName")
Correct answer: @Cache(region = "regionName")
The region attribute of the @Cache annotation specifies a named cache region for storing the entity's cached data.
Question 51: What is the difference between @OneToOne and @ManyToOne?
- They are identical
- @OneToOne is for primitives, @ManyToOne for objects
- @OneToOne maps a unique relationship while @ManyToOne maps multiple entities to one (Correct answer)
- @ManyToOne creates a join table
Correct answer: @OneToOne maps a unique relationship while @ManyToOne maps multiple entities to one
@OneToOne means one entity relates to exactly one other entity, while @ManyToOne means many entities can reference the same single entity.
Question 52: Which class is used to build a SessionFactory from a Configuration object?
- Session.openFactory()
- HibernateUtil
- Configuration.buildSessionFactory() (Correct answer)
- SessionFactory
Correct answer: Configuration.buildSessionFactory()
The buildSessionFactory() method on the Configuration object creates a SessionFactory instance.
Question 53: What is pessimistic locking in Hibernate?
- Disables concurrent access entirely
- Acquires a database-level lock on rows when they are read (Correct answer)
- Checks for conflicts at commit time
- Locks the entire table
Correct answer: Acquires a database-level lock on rows when they are read
Pessimistic locking acquires a database lock on the row as soon as it is read, preventing any other transaction from modifying it.
Question 54: What is the purpose of the hibernate.dialect property?
- Defines the transaction manager
- Sets the connection pool size
- Configures the cache provider
- Specifies the SQL dialect for the target database (Correct answer)
Correct answer: Specifies the SQL dialect for the target database
hibernate.dialect tells Hibernate which SQL variant to generate for the specific database vendor being used.
Question 55: What is a SessionFactory in Hibernate?
- A thread-safe factory that creates Session objects (Correct answer)
- An interface for transaction management
- A utility class for running HQL
- A per-request database connection
Correct answer: A thread-safe factory that creates Session objects
SessionFactory is a heavyweight, thread-safe object that creates Session instances and should be created once per application.
Question 56: Which isolation level prevents dirty reads but allows non-repeatable reads?
- REPEATABLE_READ
- READ_COMMITTED (Correct answer)
- READ_UNCOMMITTED
- SERIALIZABLE
Correct answer: READ_COMMITTED
READ_COMMITTED prevents reading uncommitted data (dirty reads) but allows different reads of the same row within a transaction (non-repeatable reads).
Question 57: What does 'SELECT DISTINCT' do in HQL?
- Selects only the first result
- Selects a random result
- Removes duplicate results from the query output (Correct answer)
- Counts unique values
Correct answer: Removes duplicate results from the query output
DISTINCT in HQL eliminates duplicate entity instances from the query result set, just as in SQL.
Question 58: What does the @Id annotation signify in a Hibernate entity?
- It marks the field as nullable
- It marks the field as unique
- It marks the field as indexed
- It marks the field as the primary key (Correct answer)
Correct answer: It marks the field as the primary key
The @Id annotation designates the field as the primary key of the entity's corresponding database table.
Question 59: What is dirty checking in Hibernate?
- Validating entity constraints
- Automatically detecting changes to managed entities and generating UPDATE statements (Correct answer)
- Scanning for SQL injection in queries
- Checking for database connection errors
Correct answer: Automatically detecting changes to managed entities and generating UPDATE statements
Dirty checking is Hibernate's mechanism to compare entity state at flush time with the snapshot taken at load time, generating UPDATE SQL for changed fields.
Question 60: In a bidirectional @ManyToMany relationship, which side should contain the @JoinTable annotation?
- Both sides must declare @JoinTable
- Neither side; Hibernate generates the table automatically
- The inverse side — the side with 'mappedBy'
- The owning side — the side without 'mappedBy' (Correct answer)
Correct answer: The owning side — the side without 'mappedBy'
The owning side (the one without 'mappedBy') carries the @JoinTable annotation and is responsible for managing the join table definition.
Hibernate Framework Assessment
A technical assessment evaluating proficiency in Hibernate ORM, covering entity mapping, associations, HQL/Criteria API, transaction management, and performance optimization for enterprise Java applications.
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds