0% found this document useful (0 votes)
28 views

Hibernate

Uploaded by

Pawan Kumar
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)
28 views

Hibernate

Uploaded by

Pawan Kumar
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/ 9

Hibernate

1. What is hibernate framework?


a. Hibernate is a java framework that simplifies the development of java application to
interact with the database.
b. Works on the database layer.
c. Is a ORM tool (object relational mapping). -> object ko table se map krenge ORM se.
d. Open source and lightweight.
e. Non-invasive framework means it will not force the programmer to extend any class.
f. Invented by Gevin king in 2001.
g. Any type of application can build with Hibernate Framework.
2. What is ORM?

@Entity Use to mark class as an entity


@Id Use to mark column as id
@GeneratedValu Auto generate values for that using internal sequence
e
@Column Can be used to specify column mappings
@Transient This tells hibernate not to save this field
@Temporal
@Table Use to change table details
@Lob

Configuration cfg = new Configuration();

Cfg.configure(“hibernate sml file”);

SessionFactory factory = cfg.buildSessionFactory();

Session session = factory.getCurrentSession();

session.beginTransaction();

Session.save(st);

Session.getTransaction().commit();

Reading image and storing in DB

FileInputStream fis = new FileInputStream(“Path”);

Byte[] data = new byte[fis.available()};

Fis.read();

Ad.setImage(data);
FETCHING DATA

Two method get() and load()

Get returns null when object is not found in cache as well as db while load method throws
ObjectNotFoundException if object is not found on cache as well as db but never returns null.

Use get when you are not sure object is avialabe or not

@Embeddable annotation in hibernate

@Embeddable

Class certificate{

String course;

String duration;}

@Entity

Class student{

Int id;

String name;

Private Certificate certi;}

@onetone mapping One field is mapped with one field only


@onetomany mapping
@manytomany mapping
@manytoone mapping

# Hibernate Interview Questions and Answers

## **Basics of Hibernate**

### 1. What is Hibernate, and how is it different from JDBC?

**Answer:** Hibernate is an Object-Relational Mapping (ORM) tool for Java that simplifies database
interactions by mapping Java objects to database tables. Unlike JDBC, Hibernate provides high-level
APIs for database access, reduces boilerplate code, and includes features like caching, lazy loading,
and transaction management.
### 2. Explain the advantages and disadvantages of Hibernate.

**Advantages:**

- Eliminates the need for complex SQL queries.

- Supports caching for performance improvement.

- Offers database independence.

- Provides automatic table creation.

**Disadvantages:**

- Slower for complex queries compared to native SQL.

- Learning curve for beginners.

- Overhead due to additional abstraction.

### 3. What is ORM (Object-Relational Mapping), and how does Hibernate implement it?

**Answer:** ORM is a programming technique that maps Java objects to database tables. Hibernate
implements ORM by using mapping files or annotations to establish the relationship between Java
classes and database tables.

### 4. What are the key components of Hibernate architecture?

**Answer:**

- **SessionFactory**: Provides a factory for `Session` objects.

- **Session**: Represents a single unit of work.

- **Transaction**: Manages database transactions.

- **Query**: Executes database queries.

- **Configuration**: Configures Hibernate using XML or annotations.

### 5. What is the difference between `Session` and `SessionFactory` in Hibernate?


**Answer:**

- **SessionFactory** is a heavyweight object that creates `Session` instances and is thread-safe.

- **Session** is a lightweight, non-thread-safe object used to interact with the database.

---

## **Configuration**

### 6. How do you configure Hibernate in a Java application?

**Answer:**

- Use `hibernate.cfg.xml` for XML-based configuration.

- Set properties like database URL, username, and dialect.

- Example:

```xml

<hibernate-configuration>

<session-factory>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<property name="hibernate.hbm2ddl.auto">update</property>

</session-factory>

</hibernate-configuration>

```

### 7. What is `hibernate.cfg.xml`, and what does it contain?

**Answer:** This file contains database configurations and mappings required by Hibernate. It
typically includes properties like dialect, connection URL, username, password, and mapping files.
### 8. Can you use Hibernate without an XML configuration file?

**Answer:** Yes, Hibernate can be configured programmatically using the `Configuration` class:

```java

Configuration configuration = new Configuration();

configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");

SessionFactory sessionFactory = configuration.buildSessionFactory();

```

### 9. How do you configure Hibernate using annotations?

**Answer:** Annotate entity classes using annotations like `@Entity`, `@Table`, and `@Id`. Example:

```java

@Entity

@Table(name = "users")

public class User {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private int id;

@Column(name = "name")

private String name;

```

### 10. What is the purpose of the `hibernate.properties` file?

**Answer:** It is an alternative to `hibernate.cfg.xml` for defining Hibernate properties.


---

## **Mappings**

### 11. What are the different types of Hibernate mappings?

**Answer:**

- One-to-One

- One-to-Many

- Many-to-One

- Many-to-Many

### 12. How do you map a class to a database table in Hibernate?

**Answer:** Using annotations or XML. Example with annotations:

```java

@Entity

@Table(name = "employee")

public class Employee {

@Id

@GeneratedValue

private int id;

private String name;

```

### 13. What is the difference between `@OneToMany` and `@ManyToOne` annotations?
**Answer:**

- `@OneToMany`: Defines a one-to-many relationship, typically used on the parent side.

- `@ManyToOne`: Defines a many-to-one relationship, used on the child side.

### 14. What is the role of the `@JoinTable` and `@JoinColumn` annotations?

**Answer:**

- `@JoinTable`: Specifies the join table for many-to-many relationships.

- `@JoinColumn`: Specifies the foreign key column for one-to-one or many-to-one relationships.

### 15. Explain how inheritance is mapped in Hibernate.

**Answer:** Hibernate supports three strategies:

- **Single Table Strategy:** All classes in a hierarchy are mapped to a single table.

- **Table per Class Strategy:** Each class has its own table.

- **Joined Strategy:** Each class has its table, and relationships are joined.

---

## **Session and Transactions**

### 20. What is a Hibernate `Session`, and what are its main methods?

**Answer:** A `Session` is used to interact with the database. Common methods:

- `save()`: Saves an object.

- `get()`: Fetches an object by ID.

- `delete()`: Deletes an object.


- `update()`: Updates an object.

### 21. Explain the lifecycle states of a Hibernate object.

**Answer:**

- **Transient:** Object not associated with a session.

- **Persistent:** Object is associated with a session and mapped to the database.

- **Detached:** Object was persistent but is no longer associated with a session.

### 22. How is transaction management handled in Hibernate?

**Answer:** Transactions are managed using the `Transaction` interface:

```java

Transaction tx = session.beginTransaction();

try {

// Perform operations

tx.commit();

} catch (Exception e) {

tx.rollback();

```

### 23. What is the difference between `save()` and `persist()` methods?

**Answer:**

- `save()`: Returns the generated ID and works outside transactions.

- `persist()`: Does not return the ID and must be used inside a transaction.
### 24. Explain the difference between `update()` and `merge()`.

**Answer:**

- `update()`: Updates a persistent object, fails if the object is detached.

- `merge()`: Copies the state of a detached object to a persistent object.

---

## **Querying**

### 25. What are the different ways to query a database using Hibernate?

**Answer:**

- HQL

- Criteria API

- Native SQL

### 26. What is HQL (Hibernate Query Language), and how is it different from SQL?

**Answer:** HQL is an object-oriented query language similar to SQL but works with entity objects
instead of database tables.

---

Would you like detailed solutions for specific queries or more sections added here?

You might also like