- Published on
Mapping Entities in Hibernate
- Authors
- Name
- Gary Huynh
- @huynhthienthach
Alrighty then, let's map some entities to database tables
, or as I like to call it, teaching your code to speak 'Database-ese'!
First, we need to define what a Entity
is. In the world of JPA
(Java Persistence API
) and Hibernate
, an Entity
is just a fancy name for a plain old Java object
(also known as a POJO
) that we're going to store in a database
.
Here is an example of a Book
entity:
@Entity
@Table(name = "books")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "title")
private String title;
@Column(name = "author")
private String author;
// getters and setters
}
Let's break down the hieroglyphics above:
@Entity
: This tellsHibernate
that this class is an entity and needs to be managed by the entity manager. It's like the flashing neon sign that says "Hey, I'm important and I need to be in the database!"@Table(name = "books")
: Here, we're specifying which table in the database this entity corresponds to. If you don't use this annotation, Hibernate will just use the class name as the table name. But we're control freaks and we like to be specific!@Id
: Thisannotation
is tellingHibernate
which field we're using as the primary key in the database. It's the equivalent of wearing a giant hat with "I'm Number 1!" in a crowd.@GeneratedValue(strategy = GenerationType.IDENTITY)
: We're tellingHibernate
to let the database decide how to generate values for the id field. That way, we don't have to keep count ourselves (we've got better things to do!).@Column(name = "title")
: With this, we're mapping thetitle
field in our class to thetitle
column in ourbooks
table. It's like introducing your code to the databasecolumn
: "Title, meet Title".
And voila! We've mapped a Java
class to a database table
, like a pro! Now, whenever you use this entity, Hibernate
will automatically know which table
it corresponds to and what the column
names are. Isn't that swell? We've done more mapping than a cartographer with a caffeine addiction!