3. Hibernate Entities
3. Hibernate Entities
□ 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
□ 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.
@Id
□ 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.
□ For example, username should be only 20 characters long. Also, it must not be null
and must be unique.
□ 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.
□ 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)
• 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.
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
• 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.
• This is managed by the currently running Session, and every change made
on it will be tracked and propagated to the database automatically.
• 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