Hibernate MCQs With Answers Explained Hibernate java Java MCQ JPA MCQ Spring Data JPA by devs5003 - July 24, 2024July 27, 20240 Last Updated on July 27th, 2024 As a Java developer, we should have a good handle on one of the frameworks used in the data layer. We are expected to have a good understanding of its basic concepts and implementation. Undoubtedly, Hibernate is one of the most popular ORM frameworks in this category. It is developed on top of JPA. In this article, we will refresh the Hibernate concepts in the form of Hibernate MCQs that are frequently asked in the interviews as well. Furthermore, you must also get benefitted in both either a written test or the interviews from these Hibernate MCQs. Here are the most important and foundation based multiple-choice questions (MCQs) on the topic “Hibernate MCQs With Answers Explained” including some code-based questions, with answers and detailed explanations. We also have various categories of questions, such as concept-based, code-based, scenario-based, high complexity level questions. You may also check other set of MCQs on Java and related technology by visiting our JAVA MCQs section. Table of Contents Toggle Hibernate MCQs With Answers ExplainedConcept-Based QuestionsCode-Based QuestionsScenario-Based QuestionsMiscellaneous Questions Hibernate MCQs With Answers Explained Concept-Based Questions Q#1. Below are the three statements in the context of Hibernate Framework. 1) Hibernate is a database management system 2) The main configuration file for Hibernate is hibernate-config.xml 3) Hibernate is an ORM tool Which of the following is the correct option? A) Statements 2 & 3 are correct B) All statements are correct C) Statements 1 & 2 are incorrect D) All statements are incorrect A#1: C) Statements 1 & 2 are incorrect Explanation: Hibernate is not a database management system. The main configuration file for Hibernate is hibernate.cfg.xml (not the hibernate-config.xml), which contains database connection settings and other configurations. Also, Hibernate is an ORM tool for Java. Therefore, statements 1 & 2 are incorrect, while 3 is correct. Q#2. Which statement is incorrect about the @Entity annotation in Hibernate? A) It is a foundation for mapping Java objects to relational database tables. B) It marks a class as an entity bean. C) An entity annotated class instance corresponds to a single row in the mapped database table. D) It creates a new database. A#2: D) It creates a new database Explanation: The @Entity annotation creates a new table in the database, but not a new database. Hence, option D is incorrect. Q#3. What is the purpose of the SessionFactory in Hibernate? A) To manage database connections B) To create session objects C) To generate SQL queries D) To create entity beans A#3: B) To create session objects Explanation: The SessionFactory is used to create Session objects, which in turn manage the lifecycle and persistence of entities. Q#4. Below are the three statements in the context of Hibernate Framework. Hibernate can generate database schema based on mappings. Hibernate does not support lazy fetching of associations. Hibernate supports caching to improve performance. Which of the following is the correct option? A) Statements 1 & 3 are correct B) All statements are correct C) Statements 2 & 3 are incorrect D) All statements are incorrect A#4: A) Statements 1 & 3 are correct Explanation: Hibernate can generate database schema based on entity mappings. Hibernate supports lazy fetching of associations to improve performance. Hibernate also supports caching mechanisms to reduce database hits. Therefore, statements 1 & 3 are correct, while 2 is incorrect. Q#5. Which Hibernate interface is responsible for managing the persistent state of an object? A) SessionFactory B) Session C) Coniguration D) Query A#5: B) Session Explanation: The Session interface is responsible for managing the persistent state of an object, including CRUD operations. Q#6. Below are the three statements in the context of Hibernate Framework. Hibernate Query Language (HQL) is case-sensitive. HQL allows for SQL-like queries. Hibernate does not support native SQL queries. Which of the following is the correct option? A) Statements 2 & 3 are correct B) All statements are correct C) Statements 1 & 3 are incorrect D) All statements are incorrect A#6: C) Statements 1 & 3 are incorrect Explanation: Hibernate Query Language (HQL) is not case-sensitive except for Java class and variable names. HQL allows for SQL-like queries to be written. Hibernate supports native SQL queries through the createSQLQuery() method. Therefore, statements 1 & 3 are incorrect, while 2 is correct. Q#7. Which of the following is used to specify the primary key of an entity? A) @Id B) @PrimaryKey C) @Primary D) @Key A#7: A) @Id Explanation: The @Id annotation is used to specify the primary key of an entity in Hibernate. Q#8.What is the use of the @GeneratedValue annotation in Hibernate? A) To generate SQL queries B) To generate unique values for primary keys C) To generate entity beans D) To generate database tables A#8: B) To generate unique values for primary keys Explanation: The @GeneratedValue annotation is used to specify how the primary key should be automatically generated. Q#9. Below are the three statements in the context of Hibernate Framework. The @Entity annotation is used to declare a class as a Hibernate entity. The @GeneratedValue annotation specifies the primary key generation strategy. The @JoinColumn annotation is used to specify a mapped column for joining an entity association. Which of the following is the correct option? A) Statements 1 & 2 are correct B) All statements are incorrect C) Statements 2 & 3 are incorrect D) All statements are correct A#9: D) All statements are correct Explanation: The @Entity annotation is used to declare a class as a Hibernate entity. The @GeneratedValue annotation specifies the strategy for primary key generation. The @JoinColumn annotation is used to specify a column for joining an entity association. Therefore, all statements are correct. Q#10. What does the @OneToMany annotation signify in Hibernate? A) One entity is associated with multiple entities B) One entity is associated with one entity C) Many entities are associated with many entities D) Many entities are associated with one entity A#10: A) One entity is associated with multiple entities Explanation: The @OneToMany annotation signifies that one entity is associated with multiple entities. Q#11. Below are the three statements in the context of Hibernate Framework. Hibernate supports second-level caching. Hibernate does not support automatic dirty checking. Hibernate uses proxies for lazy loading of entities. Which of the following is the correct option? A) Statements 1 & 3 are correct B) All statements are correct C) Statements 2 & 3 are incorrect D) All statements are incorrect A#11: A) Statements 1 & 3 are correct Explanation: Hibernate supports second-level caching to improve performance by reducing database access. Hibernate supports automatic dirty checking to detect changes in entities and update the database accordingly. Hibernate uses proxies for lazy loading of entities. Therefore, statements 1 & 3 are correct, while 2 is incorrect. Q#12. Below are the three statements in the context of Hibernate Framework. The Session interface provides methods to create, read, and delete operations. Hibernate annotations are part of the javax.persistence package. The @Table annotation specifies the table name for an entity. Which of the following is the correct option? A) Statements 1 & 3 are correct B) All statements are correct C) Statements 2 & 3 are incorrect D) All statements are incorrect A#12: A) Statements 1 & 3 are correct Explanation: The Session interface in Hibernate provides methods for create, read, and delete operations. During Recent Migration, the Java Persistence API (JPA) is undergoing a specification move from Java EE to Jakarta EE, with the package name changing to jakarta.persistence from javax.persistence, which is the standard JPA (Java Persistence API) package. The @Table annotation specifies the table name for an entity in the database. Therefore, statements 1 & 3 are correct, while 2 is incorrect. Code-Based Questions Q#13. Which method is used to save an entity in Hibernate? A) session.save(entity) B) session.insert(entity) C) session.store(entity) D) session.persist(entity) A#13: A) session.save(entity) Explanation: The session.save(entity) method is used to save an entity in Hibernate. Q#14. What is the purpose of the session.delete(entity) method? A) To delete an entity from the session B) To delete an entity from the database C) To delete a table from the database D) To delete a column from the table A#14: B) To delete an entity from the database Explanation: The session.delete(entity) method is used to delete an entity from the database. Q#15. Which method is used to fetch an entity by its primary key? A) session.fetch(Class, id) B) session.load(Class, id) C) session.retrieve(Class, id) D) session.get(Class, id) A#15: D) session.get(Class, id) Explanation: The session.get(Class, id) method is used to fetch an entity by its primary key. Q#16. In which method do you write HQL queries in Hibernate? A) session.createQuery() B) session.createSQLQuery() C) session.createHQLQuery() D) session.createNativeQuery() A#16: A) session.createQuery( ) Explanation: The session.createQuery() method is used to write HQL (Hibernate Query Language) queries in Hibernate. Q#17. Consider the following entity class. Which annotation is missing to create the custom user_email as a database column? @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // Missing annotation private String email; // Getters and setters } A) @Attribute B) @MappedColumn C) @Column D) @Field A#17: C) @Column Explanation: The @Column annotation is required to map a custom column user_email field to the database. Q#18.What is the use of the Criteria API in Hibernate? A) To create SQL queries B) To create HQL queries C) To create object-oriented queries D) To create native queries A#18: C) To create object-oriented queries Explanation: The Criteria API is used to create object-oriented queries in Hibernate. Q#19. Which method is used to add a restriction in the Criteria API? A) criteria.add(Restriction) B) criteria.add(Criterion) C) criteria.add(Constraint) D) criteria.add(Condition) A#19: B) criteria.add(Criterion) Explanation: The criteria.add(Criterion) method is used to add a restriction in the Criteria API. Q#20. What is the purpose of the @Immutable annotation in Hibernate? A) To prevent the entity from being cached B) To mark an entity as read-only and prevent updates C) To make the entity serializable D) To define a composite primary key A#20: B) To mark an entity as read-only and prevent updates Explanation: The @Immutable annotation is used to mark an entity as read-only and prevent any updates to its state. It means additions and deletions to and from the collection are not allowed. Q#21. How can you configure a Hibernate entity to be automatically timestamped on creation and update? A) Using @CreatedDate and @LastModifiedDate B) Using @Timestamped annotation C) Using @Temporal(TimestampType) D) Using @CreationTimestamp and @UpdateTimestamp A#21: D) Using @CreationTimestamp and @UpdateTimestamp Explanation: The @CreationTimestamp and @UpdateTimestamp annotations are used to automatically timestamp an entity on creation and update. Q#22. Which of the following methods would you use to retrieve an entity by its primary key using the Criteria API? A) criteria.createCriteria() B) criteria.add(Restrictions.eq("id", id)) C) criteria.createAlias("id", "primaryKey") D) criteria.addOrder(Order.asc("id")) A#22: B) criteria.add(Restrictions.eq(“id”, id)) Explanation: criteria.add(Restrictions.eq(“id”, id)) is used to add a restriction for fetching an entity by its primary key in the Criteria API. Scenario-Based Questions Q#23. Jacob is working on a web application where Hibernate is being used in the data layer. He wrote a POJO class and wants this class to work as an entity to implement the ORM concept. What are the minimum required annotations he must use at the class to create a table in the database? A) @Table, @Entity, @Id B) @Id, @GeneratedValue C) @Id, @Entity D) @Column, @Entity, @Table A#23: C) @Id, @Entity Explanation: In order to create a table in the database, @Entity & @Id annotations are mandatory, otherwise Hibernate will throw an exception. Q#24. Alice is worling in a Hibernate project. She needs to map a List of values in her entity. Which annotation should she use? A) @OneToMany B) @ElementCollection C) @ManyToMany D) @Embedded A#24: B) @ElementCollection Explanation: The @ElementCollection annotation is used to map a collection of basic or embeddable types. We can use the @ElementCollection annotation to store a list of values as an entity attribute without creating an additional entity. Q#25. Mark wants to use a custom generator for primary keys in his Hibernate application. Which annotation will help him achieve this? A) @Id B) @GeneratedValue C) @GenericGenerator D) @SequenceGenerator A#25: C) @GenericGenerator Explanation: The @GenericGenerator annotation is used to define a custom/user-defined sequence generator in Hibernate. Q#26. Jane is trying to optimize the performance of her Hibernate application by using a second-level cache. Which of the following steps is NOT necessary for configuring the second-level cache in Hibernate? A) Enabling second-level cache in the configuration file B) Specifying cache provider in the configuration file C) Annotating entities with @Cacheable D) Using session.clear() method to clear the cache manually A#26: D) Using session.clear() method to clear the cache manually Explanation: Steps A, B, and C are necessary to configure the second-level cache, but using session.clear() to clear the cache manually is not a necessary step for configuring it. Q#27. Mike wants to create a composite primary key for his entity class. Which of the following annotations should he use? A) @Id B) @EmbeddedId C) @GeneratedValue D) @ElementCollection A#27: B) @EmbeddedId Explanation: The @EmbeddedId annotation is used to define a composite primary key that is an embeddable class. Q#28. Emma needs to perform a bulk update operation using HQL. Which of the following methods should she use? A) session.update() B) session.bulkUpdate() C) query.executeUpdate() D) session.saveOrUpdate() A#28: C) query.executeUpdate() Explanation: The query.executeUpdate() method is used to perform bulk update or delete operations in HQL. Q#29. Lucas is working on a many-to-one relationship betweenStudent and Course entities. Which annotations should he use to map this relationship correctly? A) @ManyToMany with mappedBy attribute B) @OneToMany with mappedBy attribute C) @ManyToOne with mappedBy attribute D) @OneToOne with mappedBy attribute A#29: C) @ManyToOne with mappedBy attribute Explanation: To map a many-to-one relationship, Lucas should use @ManyToOne along with mappedBy attribute to specify the join table. Q#30. David needs to fetch the associatedAuthor for each Book entity using a join in HQL. Which of the following HQL queries should he use? A) SELECT b FROM Book b JOIN FETCH b.author B) SELECT b FROM Book b LEFT JOIN b.author C) SELECT b FROM Book b RIGHT JOIN b.author D) SELECT b FROM Book b OUTER JOIN b.author A#30: A) SELECT b FROM Book b JOIN FETCH b.author Q#31. Mary wants to enable lazy loading for a collection in her entity. Which annotation should she use? A) @Lazy B) @LazyCollection C) @OneToMany(fetch = FetchType.LAZY) D) @OneToMany(fetchType = LAZY) A#31: C) @OneToMany(fetch = FetchType.LAZY) Explanation: To enable lazy loading for a collection, Maria should use @OneToMany(fetch = FetchType.LAZY) Q#32. James has an entityProduct with a fieldprice of type double. How would he write an HQL query to find products with a price greater than 100? A) FROM Product p WHERE p.price > 100 B) FROM Product p WHERE p.price gt 100 C) FROM Product p WHERE p.price = 100 D) FROM Product p WHERE p.price >= 100 A#32: A) FROM Product p WHERE p.price > 100 Explanation: The correct HQL query to find products with a price greater than 100 is FROM Product p WHERE p.price > 100. Miscellaneous Questions Q#33. What is the role of the @BatchSize annotation in Hibernate? A) It specifies the number of entities to be loaded in a single batch, reducing the number of database queries. B) It defines the maximum size of a batch insert operation. C) It sets the size of the first-level cache. D) It configures the size of the JDBC batch. A#33: A) It specifies the number of entities to be loaded in a single batch, reducing the number of database queries. Explanation: The @BatchSize annotation specifies the number of entities to be loaded in a single batch, which can reduce the number of database queries and improve performance. Q#34. Which of the following Hibernate annotations can be used to define a custom SQL query for insert operations on an entity? A) @SQLQuery B) @NativeInsert C) @SQLInsert D) @InsertQuery A#34: C) @SQLInsert Explanation: The @SQLInsert annotation is used to define a custom SQL query for insert operations on an entity. Q#35. How can you configure a Hibernate entity to use a different database schema for read and write operations? A) Using @ReadOnlySchema and @WriteSchema B) Using @SQLRead and @SQLWrite C) Using @ReadSchema and @WriteSchema D) Using @SecondaryTable with different schemas A#35: D) Using @SecondaryTable with different schemas Explanation: The @SecondaryTable annotation can be used to map an entity to different schemas for read and write operations by defining multiple table mappings. Related