Home »
MCQs
NHibernate MCQs (Multiple-Choice Questions)
NHibernate is an object-relational mapping (ORM) framework for the .NET platform. It maps .NET objects to relational database tables and provides features for persistence, querying, transactions, caching, lazy loading, associations, inheritance mapping, and database interaction. These NHibernate MCQs cover important concepts such as ISession, ISessionFactory, mappings, HQL, transactions, caching, associations, collections, and persistent object states.
NHibernate MCQs
Practice these NHibernate multiple-choice questions to test your knowledge of ORM concepts, NHibernate configuration, mappings, sessions, queries, transactions, caching, and persistence.
List of NHibernate MCQs
The following NHibernate MCQs include answers and explanations covering fundamental as well as practical NHibernate concepts.
1. What is NHibernate?
- An object-relational mapping framework for .NET
- A JavaScript framework
- A web server
- A source-control system
Answer: A) An object-relational mapping framework for .NET
Explanation:
NHibernate is an ORM framework for .NET that maps object-oriented domain models to relational database structures and manages persistent objects.
2. What does ORM stand for?
- Object-Relational Mapping
- Object-Resource Management
- Operational Record Model
- Object Runtime Management
Answer: A) Object-Relational Mapping
Explanation:
ORM stands for Object-Relational Mapping. It provides a mechanism for representing relational database data as objects and mapping object properties to database structures.
3. NHibernate is primarily modeled after which ORM framework?
- Hibernate
- Entity Framework
- JDBC
- ADO.NET
Answer: A) Hibernate
Explanation:
NHibernate is the .NET port of the Java Hibernate ORM concept and provides similar object-relational persistence features for .NET applications.
4. Which NHibernate object is an expensive-to-create, thread-safe factory for creating sessions?
- ISession
- ISessionFactory
- ITransaction
- IQuery
Answer: B) ISessionFactory
Explanation:
ISessionFactory is an expensive-to-create, thread-safe object intended to be shared by application threads. It creates ISession instances used for individual units of work.
5. Which NHibernate object represents a unit of work for interacting with persistent objects?
- ISession
- ISessionFactory
- IDialect
- IConfiguration
Answer: A) ISession
Explanation:
ISession provides the main interface for loading, saving, updating, deleting, and querying persistent objects. It is relatively lightweight and is normally used for a business unit of work.
6. Which statement about ISessionFactory is correct?
- It should normally be created for every database query
- It is inexpensive and normally discarded after every operation
- It is expensive to create and is intended to be shared
- It represents one database row
Answer: C) It is expensive to create and is intended to be shared
Explanation:
NHibernate documentation describes ISessionFactory as expensive to create and thread-safe, making it suitable for sharing across application threads.
7. Which object is not thread-safe and should generally be used by one unit of work at a time?
- ISessionFactory
- ISession
- Configuration
- Dialect
Answer: B) ISession
Explanation:
An ISession is not thread-safe and is normally associated with a single unit of work rather than being shared concurrently among application threads.
8. Which method is commonly used to create a new NHibernate session from an ISessionFactory?
- OpenSession()
- CreateSessionFactory()
- NewSessionFactory()
- StartSessionFactory()
Answer: A) OpenSession()
Explanation:
ISessionFactory provides OpenSession() to create an ISession that can be used for database operations.
9. What is the primary purpose of an NHibernate mapping?
- To describe how classes and properties correspond to database structures
- To configure the operating system
- To compile C# code
- To create HTTP requests
Answer: A) To describe how classes and properties correspond to database structures
Explanation:
NHibernate mappings describe relationships between .NET classes and relational database tables, columns, identifiers, associations, and other persistence information.
10. Which file format is traditionally used for NHibernate XML mappings?
- .hbm.xml
- .nh.xml
- .orm.xml
- .mapping.cs
Answer: A) .hbm.xml
Explanation:
NHibernate traditionally uses Hibernate Mapping XML files with the .hbm.xml naming convention to describe object-relational mappings.
11. Which mapping element defines the identifier of a persistent class?
- <id>
- <identifier>
- <key-property>
- <primary>
Answer: A) <id>
Explanation:
The <id> mapping element defines the identifier property and its mapping information for a persistent class.
12. What is the purpose of an identifier generator in NHibernate?
- To generate unique identifiers for persistent objects
- To generate SQL queries
- To create database connections
- To define transaction isolation
Answer: A) To generate unique identifiers for persistent objects
Explanation:
NHibernate provides identifier generators that determine how identifiers are generated for persistent instances.
13. Which identifier generator can delegate identifier generation to a database-native strategy appropriate for the configured dialect?
- native
- random
- automatic-only
- database-auto-row
Answer: A) native
Explanation:
The native generator selects an appropriate identifier generation strategy based on the configured database dialect and available native mechanisms.
14. Which mapping element normally maps a simple persistent property?
- <property>
- <field>
- <column-property>
- <value>
Answer: A) <property>
Explanation:
The <property> element maps a persistent class property to a database column and can specify attributes such as type, length, and nullability.
15. Which NHibernate mapping element represents an association to another persistent class using a foreign-key relationship?
- <many-to-one>
- <foreign-key>
- <reference>
- <association>
Answer: A) <many-to-one>
Explanation:
A <many-to-one> mapping represents an object reference to another persistent class and commonly corresponds to a relational foreign-key relationship.
16. Which mapping is commonly used for a collection containing multiple associated entities?
- <one-to-many>
- <single-reference>
- <foreign-list>
- <entity-group>
Answer: A) <one-to-many>
Explanation:
A <one-to-many> mapping represents a collection of associated entities where multiple child entities are associated with one parent.
17. Which NHibernate collection mapping represents a set?
- <set>
- <collection-set>
- <hashset-map>
- <unique-list>
Answer: A) <set>
Explanation:
The <set> mapping represents a collection with set semantics, where duplicate elements are not allowed according to the set's equality semantics.
18. Which NHibernate collection mapping supports indexed list semantics?
- <list>
- <indexed-set>
- <ordered-map>
- <sequence>
Answer: A) <list>
Explanation:
The <list> collection mapping supports indexed collection semantics and uses an index column to represent element positions.
19. What does the inverse attribute generally indicate in a bidirectional association?
- The association is not persistent
- The mapped side is not responsible for managing the association's foreign-key changes
- The association must always be eagerly loaded
- The association is read-only in every context
Answer: B) The mapped side is not responsible for managing the association's foreign-key changes
Explanation:
In a bidirectional association, inverse="true" identifies the non-owning side for persistence of the association. The other side manages the relationship's foreign-key state.
20. Which mapping attribute controls cascading operations between associated objects?
- cascade
- propagate
- flow
- inherit
Answer: A) cascade
Explanation:
The cascade mapping controls which operations, such as save-update or delete, are propagated from one entity to associated entities.
21. What is lazy loading in NHibernate?
- Deferring the loading of associated data until it is needed
- Loading every related object immediately
- Preventing all database queries
- Deleting unused objects automatically
Answer: A) Deferring the loading of associated data until it is needed
Explanation:
Lazy loading delays retrieval of associated data until the application actually accesses it. NHibernate commonly uses lazy fetching for collections and proxy-based lazy loading for single-valued associations.
22. What can happen when a lazy association is accessed after its NHibernate session has been closed?
- NHibernate may be unable to initialize the association and throw an exception
- The association is always loaded automatically from memory
- The database is automatically recreated
- The association becomes an eager association permanently
Answer: A) NHibernate may be unable to initialize the association and throw an exception
Explanation:
Lazy initialization requires an active session. Accessing an uninitialized lazy association after the session has been closed can result in an exception.
23. What is eager or join fetching used for?
- Retrieving associated data as part of the query or fetch operation rather than waiting for lazy access
- Preventing all associations from being mapped
- Deleting related entities automatically
- Creating a second database
Answer: A) Retrieving associated data as part of the query or fetch operation rather than waiting for lazy access
Explanation:
Join fetching can retrieve associated data as part of a query and is one way to customize fetching behavior for a particular operation.
24. Which query language is designed around NHibernate's mapped objects and properties?
- HQL
- HTML
- XPath
- CSS
Answer: A) HQL
Explanation:
HQL, or Hibernate Query Language, is an object-oriented query language used by NHibernate to query mapped entities and their properties.
25. In HQL, which statement is generally used to retrieve all instances of a mapped entity named Product?
- SELECT * FROM Product
- FROM Product
- GET Product ALL
- LOAD TABLE Product
Answer: B) FROM Product
Explanation:
HQL operates on mapped entity names rather than directly using table names. A query such as from Product retrieves mapped Product entities.
26. Which method is commonly used to create an HQL query from an ISession?
- CreateQuery()
- CreateHqlQueryOnly()
- OpenQuery()
- BuildQuery()
Answer: A) CreateQuery()
Explanation:
ISession provides CreateQuery() for creating an IQuery from an HQL string.
27. Which method is commonly used to limit the maximum number of results returned by an NHibernate query?
- SetMaxResults()
- LimitRows()
- MaxRowsOnly()
- SetResultCountOnly()
Answer: A) SetMaxResults()
Explanation:
SetMaxResults() specifies the maximum number of results that a query should return.
28. Which method can be used to provide a named parameter value to an NHibernate query?
- SetParameter()
- AssignQueryValue()
- SetQueryVariableOnly()
- BindSQLText()
Answer: A) SetParameter()
Explanation:
SetParameter() binds a value to a named query parameter and is useful for creating parameterized NHibernate queries.
29. Why should parameters generally be used instead of constructing HQL by concatenating user input?
- Parameters help avoid unsafe query construction and provide proper value binding
- Parameters force every query to become a stored procedure
- Parameters disable transactions
- Parameters prevent NHibernate from mapping objects
Answer: A) Parameters help avoid unsafe query construction and provide proper value binding
Explanation:
Parameterized queries separate query structure from values and avoid unsafe string concatenation of external input.
30. Which NHibernate API can be used to create queries programmatically using restrictions and projections?
- ICriteria
- ITransaction
- ISessionFactory
- IDialect
Answer: A) ICriteria
Explanation:
NHibernate's Criteria API provides a programmatic approach for constructing queries using restrictions, projections, ordering, and related query features.
31. What is the first-level cache in NHibernate?
- The cache associated with an individual ISession
- A cache shared by every ISessionFactory in an application
- A cache stored only in the database server
- A cache containing only SQL strings
Answer: A) The cache associated with an individual ISession
Explanation:
NHibernate's ISession maintains an internal first-level cache of persistent objects. It is scoped to that session.
32. Which method can remove a persistent object from the current session's first-level cache?
- Evict()
- RemoveCacheOnly()
- Unload()
- ClearObject()
Answer: A) Evict()
Explanation:
Evict() removes a specified object from the session cache. NHibernate also provides Clear() to clear the session cache more broadly.
33. Which method clears all objects from the current ISession cache?
- Clear()
- Flush()
- ResetSessionFactory()
- EmptyDatabase()
Answer: A) Clear()
Explanation:
ISession.Clear() removes all objects from the session's first-level cache.
34. What is the second-level cache in NHibernate?
- A cache associated with the ISessionFactory and potentially shared across sessions
- A cache available only inside one method call
- A cache that stores only transaction objects
- A cache that replaces the database
Answer: A) A cache associated with the ISessionFactory and potentially shared across sessions
Explanation:
The second-level cache operates at the ISessionFactory/process level and can cache persistent entity or collection data across multiple sessions when configured.
35. What does NHibernate's query cache primarily cache?
- Query result information such as identifiers and scalar values
- The complete state of every entity automatically
- Database transaction logs
- Mapping XML files only
Answer: A) Query result information such as identifiers and scalar values
Explanation:
The query cache stores query result information. It does not by itself cache the complete entity state; entity data is normally obtained through the second-level cache when appropriate.
36. Which method enables query caching for an individual NHibernate query?
- SetCacheable(true)
- EnableQueryCache()
- UseCacheOnly()
- CacheQueryResult()
Answer: A) SetCacheable(true)
Explanation:
An IQuery can be marked cacheable with SetCacheable(true), provided query caching and an appropriate cache configuration are enabled.
37. Which NHibernate object is used to manage database transactions?
- ITransaction
- IQuery
- ICriteria
- ISessionFactory
Answer: A) ITransaction
Explanation:
ITransaction provides NHibernate's transaction API for beginning, committing, and rolling back transactions.
38. Which method commonly begins a transaction on an ISession?
- BeginTransaction()
- StartTransactionOnly()
- OpenTransaction()
- CreateTransactionScopeOnly()
Answer: A) BeginTransaction()
Explanation:
ISession provides BeginTransaction() to begin an NHibernate ITransaction.
39. What does Flush() do in NHibernate?
- Synchronizes in-memory persistent state with the database
- Closes the ISessionFactory
- Clears every database table
- Deletes the first-level cache without synchronizing changes
Answer: A) Synchronizes in-memory persistent state with the database
Explanation:
Flush synchronizes changes held by the session with the persistent store. It is different from committing the database transaction.
40. What normally happens when an NHibernate ITransaction is committed?
- The session state is flushed and the underlying transaction is committed
- The session is always converted to a detached state before commit
- All mappings are deleted
- The ISessionFactory is destroyed
Answer: A) The session state is flushed and the underlying transaction is committed
Explanation:
When using the NHibernate ITransaction API, Commit() flushes the session and commits the underlying database transaction.
41. Which method reverses the changes made by the current database transaction?
- Rollback()
- UndoSession()
- ReverseFlush()
- CancelDatabase()
Answer: A) Rollback()
Explanation:
Rollback() rolls back the current transaction. After a rollback, NHibernate recommends closing and discarding the affected session to maintain consistent internal state.
42. Which method can be used to save a new persistent object?
- Save()
- PersistObjectOnly()
- InsertEntityOnly()
- CreatePersistent()
Answer: A) Save()
Explanation:
ISession.Save() makes a transient object persistent and returns its generated identifier when applicable.
43. What is a detached object in NHibernate?
- An object that was persistent but is no longer associated with an active ISession
- An object that has never been created
- An object that cannot be mapped
- An object that exists only inside the database
Answer: A) An object that was persistent but is no longer associated with an active ISession
Explanation:
A detached object has previously been associated with a session but is no longer associated with that session. It can later be re-associated or merged according to the application's needs.
44. Which method can copy the state of a detached object onto the persistent instance associated with the current session?
- Merge()
- CopyToSession()
- AttachState()
- SynchronizeObject()
Answer: A) Merge()
Explanation:
Merge() copies the state of a given object onto the persistent object with the same identifier when appropriate and returns the persistent instance. The supplied detached instance itself does not become associated with the session.
45. Which method is commonly used to delete a persistent object?
- Delete()
- RemovePersistentOnly()
- EraseObject()
- DropEntity()
Answer: A) Delete()
Explanation:
ISession.Delete() marks a persistent object for deletion. The corresponding SQL operation is synchronized with the database during flushing.
46. Which NHibernate method loads an entity by its identifier and can return null when no matching entity exists?
- Get()
- LoadAlways()
- FetchRequired()
- RetrieveOnly()
Answer: A) Get()
Explanation:
Get() retrieves an entity by identifier and returns null when the requested entity does not exist. Load() has different semantics and can use a proxy.
47. Which NHibernate method can return a proxy without immediately accessing the database when the entity is not already available?
- Load()
- GetImmediate()
- FindDatabaseOnly()
- FetchNow()
Answer: A) Load()
Explanation:
Load() can return a proxy for an entity when appropriate. Database access may be deferred until the proxy needs initialization.
48. Which NHibernate inheritance strategy stores the entire class hierarchy in a single table and typically uses a discriminator?
- Table per class hierarchy
- Table per concrete class only
- Table per database
- Table per property
Answer: A) Table per class hierarchy
Explanation:
In the table-per-class-hierarchy strategy, the inheritance hierarchy is represented in one table, generally using a discriminator column to distinguish subclass types.
49. Consider the following NHibernate mapping:
<class name="Customer" table="Customers">
<id name="Id" column="CustomerId">
<generator class="native"/>
</id>
<property name="Name" column="CustomerName"/>
</class>
What does this mapping indicate?
- The Customer class is mapped to the Customers table and its Id property is mapped to CustomerId
- The Customer table is mapped to a class named CustomerId
- The Name property becomes the primary key automatically
- NHibernate will not persist the Customer class
Answer: A) The Customer class is mapped to the Customers table and its Id property is mapped to CustomerId
Explanation:
The class mapping specifies Customers as the table. The <id> element maps the Id property to CustomerId and uses the native identifier generator, while the <property> element maps Name to CustomerName.
50. Consider the following NHibernate code:
using (var session = factory.OpenSession())
using (var transaction = session.BeginTransaction())
{
var customer = session.Get<Customer>(10);
customer.Name = "Rahul";
transaction.Commit();
}
Assuming Customer with ID 10 exists and the property is mapped as persistent, what allows NHibernate to detect and persist the changed Name without an explicit Update() call?
- The persistent object is associated with the current ISession and NHibernate performs dirty checking
- The database automatically modifies the object before Commit()
- Get() converts every object into a detached object
- NHibernate requires Update() for every property change inside the same session
Answer: A) The persistent object is associated with the current ISession and NHibernate performs dirty checking
Explanation:
An object loaded through the current ISession is persistent. When its mapped state is changed, NHibernate can detect the change and synchronize it with the database during flushing. With the NHibernate transaction API, the session is flushed as part of Commit().
Advertisement
Advertisement