[go: up one dir, main page]

0% found this document useful (0 votes)
10 views8 pages

MongoDB PostgreSQL Hibernate Complete Interview Questions

Uploaded by

Shubham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views8 pages

MongoDB PostgreSQL Hibernate Complete Interview Questions

Uploaded by

Shubham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Interview Questions for MongoDB,

PostgreSQL, and Hibernate


This document contains a comprehensive set of interview questions covering MongoDB,
PostgreSQL, and Hibernate. Each question is explained with clear, concise, and detailed
concepts.

MongoDB Interview Questions

Basics

What is MongoDB and how is it different from traditional relational databases?


MongoDB is a NoSQL database that stores data in a flexible JSON-like format called BSON
(Binary JSON). Unlike relational databases that use structured tables and rows, MongoDB
allows for a more dynamic schema, meaning you can have different fields in different
documents within the same collection.

What are BSON and its advantages?


BSON (Binary JSON) is a format used to represent data in MongoDB. It supports more data
types than JSON, such as dates and binary data. Its advantages include efficient data storage
and faster data retrieval due to its binary nature.

What is a collection in MongoDB?


A collection in MongoDB is similar to a table in relational databases. It is a group of related
documents stored in the database. Each document in a collection can have different fields
and structures.

How do you define a schema in MongoDB?


In MongoDB, schemas are not strictly enforced, but you can define one using Mongoose (a
library for MongoDB) or by following conventions. You can set rules about the data types
and required fields to help maintain data consistency.

What is a document in MongoDB?


A document is a basic unit of data in MongoDB represented in BSON format. It is similar to a
row in a relational database and can contain various fields and values.

CRUD Operations

How do you insert a document into a MongoDB collection?


You can insert a document using the insertOne() or insertMany() methods. Example:
db.collectionName.insertOne({ name: "John", age: 30 });
What is the difference between insertOne() and insertMany()?
insertOne() is used to insert a single document, while insertMany() is used to insert
multiple documents at once. Example:
db.collectionName.insertMany([{ name: "Jane" }, { name: "Doe" }]);

How do you update a document in MongoDB?


You can update documents using the updateOne() or updateMany() methods. Example:
db.collectionName.updateOne({ name: "John" }, { $set: { age: 31 } });

What is the difference between update() and save()?


update() modifies existing documents based on a query, while save() is used to either insert
a new document or update an existing one. If the document already exists, save() updates it;
if not, it creates a new one.

How do you delete a document in MongoDB?


You can delete a document using deleteOne() or deleteMany() methods. Example:
db.collectionName.deleteOne({ name: "John" });

Querying Data

How do you retrieve a single document from a collection?


You can use the findOne() method to retrieve a single document. Example:
db.collectionName.findOne({ name: "Jane" });

What are query operators in MongoDB?


Query operators are special keywords used to specify conditions in your queries. Examples
include $eq (equal), $gt (greater than), $lt (less than), and $in (matches any value in an
array).

How do you perform a case-insensitive search?


You can perform a case-insensitive search using a regular expression. Example:
db.collectionName.find({ name: { $regex: /^john$/i } });

What is the purpose of the $exists operator?


The $exists operator checks if a specific field exists in a document. Example:
db.collectionName.find({ age: { $exists: true } });

Explain how to use the $or and $and operators in queries.


The $or operator allows you to specify multiple conditions where at least one must be true,
while $and requires all conditions to be true. Example:
db.collectionName.find({ $or: [{ age: { $lt: 25 } }, { name: "John" }] });
PostgreSQL Interview Questions

Basics

What is PostgreSQL and what are its key features?


PostgreSQL is an open-source relational database management system known for its
advanced features like support for complex queries, full-text search, and extensibility
through custom data types and functions. It emphasizes standards compliance and data
integrity.

What is a database schema?


A database schema is the structure that defines how data is organized in the database,
including tables, fields, relationships, and constraints. It acts like a blueprint for the
database.

What is a table in PostgreSQL?


A table is a collection of rows and columns that stores data in a relational database. Each
column has a specific data type and each row represents a record.

How does PostgreSQL handle data types?


PostgreSQL supports a wide range of data types including integers, strings, dates, and
custom types. You can choose the appropriate type based on the data you are storing,
ensuring data integrity.

What are the advantages of using PostgreSQL over other databases?


Advantages include strong data integrity through ACID compliance, support for advanced
data types (e.g., JSON, arrays), powerful indexing capabilities, and support for complex
queries and stored procedures.

CRUD Operations

How do you create a table in PostgreSQL?


You can create a table using the CREATE TABLE statement. Example:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
age INT
);

What is the SERIAL data type and how is it used?


The SERIAL data type is a special type in PostgreSQL that automatically generates a unique
integer for each new record. It is often used for primary key fields.

How do you perform an INSERT operation in PostgreSQL?


You can insert data into a table using the INSERT INTO statement. Example:
INSERT INTO users (name, age) VALUES ('Alice', 30);
What is the difference between UPDATE and UPSERT?
UPDATE modifies existing records in a table, while UPSERT (a combination of insert and
update) inserts a new record if it doesn't exist or updates it if it does. In PostgreSQL, you can
perform an UPSERT using the INSERT ... ON CONFLICT statement.

How do you delete records from a table in PostgreSQL?


You can delete records using the DELETE statement. Example:
DELETE FROM users WHERE name = 'Alice';

Querying Data

How do you retrieve data from a PostgreSQL table?


You can retrieve data using the SELECT statement. Example:
SELECT * FROM users;

What are the different types of joins available in PostgreSQL?


PostgreSQL supports several types of joins including:
- INNER JOIN: Returns records that have matching values in both tables.
- LEFT JOIN: Returns all records from the left table and matched records from the right
table.
- RIGHT JOIN: Returns all records from the right table and matched records from the left
table.
- FULL JOIN: Returns records when there is a match in either table.

Explain the use of subqueries in PostgreSQL.


A subquery is a query nested inside another query. It can be used in various clauses like
SELECT, WHERE, or FROM. Example:
SELECT name FROM users WHERE age IN (SELECT age FROM users WHERE name = 'Bob');

What is a Common Table Expression (CTE) and how is it used?


A CTE is a temporary result set that you can reference within a SELECT, INSERT, UPDATE,
or DELETE statement. It is defined using the WITH clause. Example:
WITH user_age AS (SELECT name, age FROM users)
SELECT * FROM user_age WHERE age > 25;

How do you perform a full-text search in PostgreSQL?


PostgreSQL provides full-text search capabilities using the tsvector and tsquery data types.
You can create a tsvector from text and then search it. Example:
SELECT * FROM articles WHERE to_tsvector('english', content) @@ to_tsquery('database');
Hibernate Interview Questions

Basics

What is Hibernate and what are its key features?


Hibernate is an Object-Relational Mapping (ORM) framework for Java that simplifies
database interactions. Key features include automatic SQL generation, support for caching,
and transaction management.

What is ORM (Object-Relational Mapping)?


ORM is a programming technique that allows developers to interact with a database using
high-level object-oriented programming languages instead of SQL. It maps database tables
to classes and rows to objects.

What are the advantages of using Hibernate over JDBC?


Advantages include reduced boilerplate code, automatic management of SQL queries, built-
in caching, and simplified transaction handling. Hibernate allows developers to focus on the
object-oriented model instead of SQL queries.

What is a session in Hibernate?


A session is a single-threaded, short-lived object that represents a conversation between the
application and the database. It is used to create, read, and delete objects in the database.

What is the Hibernate configuration file?


The Hibernate configuration file (usually hibernate.cfg.xml) contains settings for connecting
to the database, mapping classes to tables, and other Hibernate properties.

Mapping

What is the difference between @Entity and @Table annotations?


@Entity indicates that a class is an entity (a persistent object), while @Table specifies the
name of the database table to which the entity is mapped. You can use @Table to define
additional properties like the table's schema.

Explain the different types of associations in Hibernate.


Hibernate supports several types of associations:
- One-to-One: One entity is associated with one instance of another entity.
- One-to-Many: One entity is associated with multiple instances of another entity.
- Many-to-One: Multiple entities are associated with one instance of another entity.
- Many-to-Many: Multiple entities are associated with multiple instances of another entity.

What is lazy loading in Hibernate?


Lazy loading is a performance optimization technique where related entities are not loaded
from the database until they are accessed for the first time. This helps reduce memory
usage and improve performance.
What is the difference between save() and persist() methods in Hibernate?
Both methods are used to save an entity, but save() returns the generated identifier of the
entity, while persist() does not return anything. persist() is also used for managed entities,
whereas save() can be used for transient entities.

What is a primary key generator in Hibernate?


A primary key generator is a strategy to generate unique identifiers for entities. Hibernate
supports different strategies such as IDENTITY, SEQUENCE, and TABLE to generate primary
keys.

Querying Data

What is HQL (Hibernate Query Language)?


HQL is an object-oriented query language similar to SQL but operates on Hibernate objects
rather than database tables. It allows querying entities based on their properties. Example:
List<User> users = session.createQuery('FROM User WHERE age > :age')
.setParameter('age', 25)
.list();

How do you use criteria queries in Hibernate?


Criteria queries provide a programmatic way to create queries using Java objects. Example:
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> root = cq.from(User.class);
cq.select(root).where(cb.gt(root.get('age'), 25));
List<User> users = session.createQuery(cq).getResultList();

What is the difference between get() and load() methods in Hibernate?


get() retrieves an entity by its primary key and returns null if not found, while load()
returns a proxy of the entity that is not immediately fetched from the database. If the entity
is not found, load() throws an exception when accessed.

What are the advantages of using JPQL (Java Persistence Query Language)?
Advantages include database independence, the ability to work with entities instead of
tables, support for object-oriented features like polymorphism, and integration with the
Java Persistence API (JPA).

How do you perform pagination in Hibernate?


You can perform pagination by setting the maximum number of results and the offset in a
query. Example:
List<User> users = session.createQuery('FROM User')
.setFirstResult(0) // Starting index
.setMaxResults(10) // Maximum results to return
.list();
Caching

What is the first-level cache in Hibernate?


The first-level cache is a session-scoped cache that stores entities fetched within the same
session. It ensures that multiple requests for the same entity within a session return the
same instance.

What is the second-level cache in Hibernate?


The second-level cache is a session factory-scoped cache that stores entities and collections
across multiple sessions. It improves performance by reducing database access for
frequently used data.

How do you configure second-level caching in Hibernate?


You can configure second-level caching in the Hibernate configuration file by specifying the
cache provider and enabling caching for specific entities or collections using annotations
like @Cache.

What are cache providers in Hibernate?


Cache providers are libraries or frameworks that Hibernate can use for second-level
caching. Common providers include Ehcache, Infinispan, and Hazelcast.

What are the strategies for caching in Hibernate?


Hibernate supports various caching strategies including:
- Read-only: The cached data is not modified after being read.
- Read-write: The cached data can be modified and is synchronized with the database.
- Nonstrict-read-write: The cached data may be stale but is still valid for reads.
- Transactional: Ensures data consistency within transactions.

Transactions

What is the difference between container-managed and application-managed transactions in


Hibernate?
Container-managed transactions: The container (e.g., an application server) manages the
transaction boundaries automatically.
Application-managed transactions: The application code explicitly controls the transaction
boundaries using Hibernate APIs.

How do you handle transaction management in Hibernate?


You handle transaction management using Transaction objects. Example:
Transaction tx = session.beginTransaction();
// Perform database operations
tx.commit(); // or tx.rollback(); in case of an error
What is optimistic locking in Hibernate?
Optimistic locking is a concurrency control mechanism that allows multiple transactions to
access the same data. It checks for conflicts before committing changes, typically using a
version column in the entity.

What is pessimistic locking in Hibernate?


Pessimistic locking prevents other transactions from accessing the data until the current
transaction is complete. It is achieved by locking the entity when it is read or updated.

How do you implement locking in Hibernate?


You can implement locking using the LockMode enumeration. Example:
User user = session.get(User.class, userId, LockMode.PESSIMISTIC_WRITE);

You might also like