Hibernate in Java
Hibernate in Java
Overview
interactions by mapping Java objects to database tables and vice versa. Key features include ORM
framework, transparent persistence, HQL (Hibernate Query Language), and automatic table
generation. It boosts productivity, maintainability, and portability by reducing boilerplate code and
Core Components
- SessionFactory: Configures Hibernate for the application and provides Session instances.
Example Usage
```
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
Hibernate in Java
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<mapping class="com.example.MyEntity"/>
</session-factory>
</hibernate-configuration>
```
Entity Class:
```
@Entity
@Table(name = "my_table")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "name")
```
Hibernate in Java
Using Hibernate:
```
static {
try {
sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
try {
transaction = session.beginTransaction();
entity.setName("Hibernate Example");
session.save(entity);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
```
Hibernate entities can exist in three primary states during their lifecycle: Transient, Persistent, and
Detached.
1. Transient State:
- An object is in a transient state when it is instantiated but not associated with a Hibernate Session.
Hibernate in Java
2. Persistent State:
- Example: session.save(entity);
3. Detached State:
- An object is in a detached state when it was once associated with a Hibernate Session, but the
- Example: session.close();
1. get Method:
- Returns the actual object or null if the entity does not exist.
2. load Method:
- Throws ObjectNotFoundException if the entity does not exist when a method is invoked on the
proxy.
Java Persistence API (JPA) is a specification for object-relational mapping (ORM) in Java. It
provides a standard way to map Java objects to relational database tables and manage persistent
data. JPA requires a concrete implementation such as Hibernate, EclipseLink, Apache OpenJPA, or
DataNucleus.
1. Dependencies:
2. Entity Class:
3. Persistence Configuration:
4. Using EntityManager: