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

3. Hibernate Entities

The document explains Hibernate entities in JPA, which are POJO classes mapped to database tables. It details the creation approaches (Database-first and Entity-first), annotations like @Entity, @Id, @Table, and @Column for defining entities and their properties, as well as primary key generation strategies. Additionally, it covers the entity lifecycle states (Transient, Managed, Detached, Removed) and the differences between EntityManager and Session in Hibernate.

Uploaded by

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

3. Hibernate Entities

The document explains Hibernate entities in JPA, which are POJO classes mapped to database tables. It details the creation approaches (Database-first and Entity-first), annotations like @Entity, @Id, @Table, and @Column for defining entities and their properties, as well as primary key generation strategies. Additionally, it covers the entity lifecycle states (Transient, Managed, Detached, Removed) and the differences between EntityManager and Session in Hibernate.

Uploaded by

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

Hibernate Entities

What are Entities?

□ In RDBMS, entities are objects that are stored as rows in the


tables.

□ Similarly, in JPA, entities are POJO (Plain Old Java Object)


classes whose objects you want to save in the rows of the
tables.

□ For example, we want to save customer data into the


database. Then, there would be a POJO class named
‘Customer’ in our application
Entities Cont…
□ Entities in an application can be created using the following two different
approaches:
● Database-first
● Entity-first

□ In the Database-first approach, we first create the schema in the database.


Then, we create the entire classes in the application. So, the table name
would be the class name, and the columns would be the attributes of the
class.

□ In the Entity-first approach, we first create the entities in the application.


Then, we use ORM tools, such as Hibernate, to create the schema for the
application. So, the class name would be the table name, and the attributes
of the class would be the columns in the table.
Using @Entity
□ The @Entity annotation is used to mark POJO classes whose objects are to be saved in
the rows of the database tables.

□ On starting the application, Hibernate scans all the classes that are marked with the
@Entity annotation and maps them to the tables present in the database.
• @Entity

public class Customer {


private int customerId;
private String firstName;
private String lastName;
private String username;
private String password;
private LocalDateTime dateOfBirth;
// getters, setters and toString
}
Using @Id
□ If you run the application now, then you will see that Hibernate is not creating
any tables.

□ Every JPA entity must have a primary key, in the same way as every table in
the database has a primary key.

□ To make any attribute of the entity class its primary key, mark that attribute
with the @Id
annotation.

□ Thus, to create an entity class that can be mapped to a database table by


Hibernate, there are two requirements as given below.
● That class should be marked with the @Entity annotation.
● One of its fields should be marked with the @Id annotation.
Using @Id - Example
@Entity

public class Customer {

@Id

private int customerId;

private String firstName;

private String lastName;

private String username;

private String password;


private LocalDateTime dateOfBirth;
// getters, setters and toString
}
Using @Table
□ Now, if this code is run, Hibernate will create a table corresponding to the Customer
Entity in which:
● The name of the table will be the same as the entity class name ‘customer’;
● All the attributes of the Customer class will be treated as columns in the customer
table;
● The attribute names, which contain more than one word and were written using the
lower camel case are not written using the underscore; and
● int will be mapped to number, String will be mapped to varchar2 and
LocalDateTime will be mapped to date by Hibernate.

□ Hibernate maps the entities to the same table name in the database.

□ To make the table name different from the name of the entity class, mark the entity
class with the @Table annotation.

□ Provide the table name using the name attribute of the @Table annotation.
Using @Table - Example
@Entity
@Table(name = "Cust")
public class Customer {
@Id
private int customerId; private String firstName;
private String lastName; private String username;
private String password;
private LocalDateTime dateOfBirth;
// getters, setters and toString
}
Using @Column
□ Observe the ‘create table’ query - all the columns are created using the default
values.

□ How to apply certain constraints to our columns?

□ For example, username should be only 20 characters long. Also, it must not be null
and must be unique.

□ Apply such constraints to the columns using the @Column annotation.

□ Some of the most useful attributes of the @Column annotation are as follows:
● name: To provide custom name to the column inside the database table
● length: To specify the length of the column datatype
● nullable: To specify whether or not the column value can be null
● unique: To specify whether or not the column value is unique
Using @Column - Example
@Entity
@Table(name = "Customer") public class
Customer {
@Id
private int customerId;
@Column(name = "first_name", length = 20, nullable = false)
private String firstName;
@Column(length = 20)
private String lastName;
@Column(length = 20, nullable = false, unique = true)
private String username;
@Column(length = 20, nullable = false)
private String password;
@Column(nullable = false)
private LocalDateTime dateOfBirth;
// getters, setters and toString
}
Key Generation Strategies
Primary Key Generation Strategies
□ ‘customerId’ is the primary key for the customer table.

□ How would the primary key be generated?

□ In MySQL Database, a sequence is used to generate primary keys.

□ Specify the strategy to be used to generate primary keys using the


@GeneratedValue
annotation.

□ Specify the primary key generation strategy using the strategy attribute
of the @GeneratedValue annotation.
@GeneratedValue
• The JPA specification supports 4 different primary key generation strategies which generate the
primary key values programmatically or use database features, like auto-incremented columns or
sequences.

□ The value of the strategy attribute can be one of the following four types:
● IDENTITY: It uses a database identity column (auto-increment). It is mainly used
with MS SQL or MySQL.
● SEQUENCE: It uses a database sequence. It is mainly used with Oracle or
PostgreSQL.
● TABLE: It uses an underlying database table to ensure uniqueness. It works
with all databases.
● AUTO: It uses an appropriate strategy for the underlying database. This is default
in case no strategy is specified. It is also the preferred type, as the ORM tool will
choose the best strategy for the underlying database.
@GenerateValue - Example
@Entity
@Table(name = "Customer") public
class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO) private int
customerId;
@Column(name = "first_name", length = 20, nullable = false)

private String firstName;


@Column(length = 20)
private String lastName;
@Column(length = 20, nullable = false, unique = true)
private String username;
@Column(length = 20, nullable = false)
private String password;
@Column(nullable = false)
private LocalDateTime dateOfBirth;
// getters, setters and toString
}
Auto Generation
• If we're using the default generation type, the persistence provider
will determine values based on the type of the primary key attribute

• In case of MySQL, hibernate will use SEQUENCE generation type for AUTO

@Entity
public class Student {
@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private long studentId;
//
...
}
Identity Generation
• This type of generation relies on the IdentityGenerator, which expects
values generated by an identity column in the database.

• E.g., In case of MySql, it uses the Auto-Increment


@Entity
public class Student {
@Id
@GeneratedValue (strategy =
GenerationType.IDENTITY)
private long studentId;
// ...
}

• Note: IDENTITY generation disables batch updates.


Sequence Generation
• To use a sequence-based id, Hibernate provides
the SequenceStyleGenerator class.

• This generator uses sequences if our database supports them. It switches to


table generation if they aren't supported.
@Entity
public class User {
@Id
@GeneratedValue(generator = "sequence-generator")
@GenericGenerator( name = "sequence-generator",
strategy =
"org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = { @Parameter(name = "sequence_name", value
= "user_sequence"), @Parameter(name = "initial_value",
value = "4"), @Parameter(name = "increment_size", value
= "1") } )
private long userId;
// ...
}
Table Generation
• The TableGenerator uses an underlying database table that holds segments of
identifier generation values.

• Let's customize the table name using the @TableGenerator annotation:


@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.TABLE,
generator = "table-generator")
@TableGenerator(name = "table-generator", table =
"dep_ids", pkColumnName = "seq_id",
valueColumnName = "seq_value") private long
depId;
// ...
}
Hibernate Entity Lifecycle
Entity Lifecycle
• Every Hibernate entity naturally has a lifecycle within the framework –
it's either in a transient, managed, detached or deleted state.
Session Methods

session.sav session.persis session.loa


e() t() d()

session.get session.delet
() e()
EntityManager and Session
EntityManag Sessio
er n
Part of JPA Specification that makes Part of Hibernate that makes
the code the code tightly coupled with
loosely coupled with ORM tool Hibernate.

Uses Session to store and retrieve Uses JDBC API to store and retrieve
entities. entities

Provides less control over CRUD Provide more control over CRUD
operations operations

Provides CRUD methods such as


Provides CRUD methods
persist(), save(),
such as persist(), find(), merge(),
saveOrUpdate(), get(),
remove(), etc
load(), merge(), update(), delete(),
Transient State
• When an entity object is initially created, it’s state is New or Transient. In this state, the
object is not yet associated with an EntityManager and has no representation in the
database.

• Objects instantiated using the new operator are not immediately persistent (Managed).
Their state is “Transient”. Which means they are not associated with any database table
row, and so their state is lost as soon as their reference is removed.

• Transient state instances state is lost and garbage-collected as soon as they are no longer
referenced.

• To make a transient entity persistent, we need to call Session.save(entity) or


Session.saveOrUpdate(entity):
Persistent/Managed State
• An entity object becomes Managed or Persistent when it is persisted to
the database via an EntityManager’s persist() method, which must be
invoked within an active transaction.

• This is managed by the currently running Session, and every change made
on it will be tracked and propagated to the database automatically.

• If we are changing persistent State object values those are synchronized


automatically with the database while committing the transaction.
Detached State
• The detached state, represents entity objects that have been disconnected
from the EntityManager.

• An entity can become detached when the Session used to load it was closed,
or when we call Session.evict(entity) or Session.clear().

• The difference from a managed entity is that it's not tracked anymore by any
persistence context.

• Note that in order to make a persistent entity from a detached entity, the
application must re-attach it to a valid Hibernate Session.
Removed/Deleted State
• A persistent state entity object can also be marked for deletion, by
using the EntityManger’s remove() with in an active transaction. Then
entity object changes its state from Managed to Removed, and
physically deleted from the database during commit.

• As the entity object is in the removed state, if any change will be done
in the data will not affect the database table.
References
• Hibernate Mapping Entities – Community Documentation
https://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.ht
ml

• Beginners guide to entity state transition


https://vladmihalcea.com/a-beginners-guide-to-jpa-hibernate-entity-state-tran
sitions/

• JPA Entity Lifecycle


https://javabydeveloper.com/jpa-entity-lifecycle-jpa-developer-should-know/

• Hibernate Entity Lifecycle https://www.baeldung.com/hibernate-entity-lifecycle

You might also like