Hibernate Quick Revision Notes
What is Hibernate?
- Hibernate is a Java framework used to connect Java code with databases.
- It is an ORM (Object-Relational Mapping) tool that maps Java classes to DB tables.
Key Concepts:
1. ORM (Object Relational Mapping):
- Converts Java objects to database tables and vice versa.
2. Hibernate Annotations:
- @Entity - Declares class as a table
- @Table - Gives table name (optional)
- @Id - Declares primary key
- @GeneratedValue - Auto-increment the ID
- @Column - Declares a column
Example:
@Entity
@Table(name="student")
public class Student {
@Id
@GeneratedValue
private int id;
@Column(name="student_name")
private String name;
3. Hibernate Configuration:
- XML based: hibernate.cfg.xml
- Java-based configuration using Configuration class
4. Important Classes:
- Configuration: Loads config and mappings
- SessionFactory: Builds sessions
- Session: Used to interact with DB
- Transaction: Handles commit and rollback
5. Hibernate Flow:
- Load Configuration
- Build SessionFactory
- Open Session
- Begin Transaction
- Save or update data
- Commit and close session
Interview Questions:
1. What is Hibernate?
- ORM tool to connect Java code with the database.
2. Difference between @Entity and @Table?
- @Entity: Declares class as entity.
- @Table: Optional, sets table name.
3. What is SessionFactory?
- Factory to create sessions.
4. What is Session?
- Used to perform database operations.
5. Advantages of Hibernate:
- No manual SQL needed.
- Works with all databases.
- Supports caching and lazy loading.