Create the User Entity
In our previous lessons, we set up the foundational infrastructure for our blog platform.
Now we'll create the User entity, which will represent user accounts in our system.
Understanding JPA Entities
A JPA entity is a persistent domain object that represents a table in our database.
The entity class must be annotated with @Entity and follow certain conventions to work correctly with JPA.
Hibernate (JPA implementation) will use this class to automatically create the corresponding database table and manage the mapping between Java objects and database records.
Implementing the User Entity
The User entity needs to store essential information about each user in our system.
Here's the implementation of our User class:
package com.devtiro.blog.domain.entities;
import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private LocalDateTime createdAt;
// We need to implement equals and hashCode explicitly because
// Lombok's implementation can cause issues with JPA entities
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id) &&
Objects.equals(email, user.email) &&
Objects.equals(password, user.password) &&
Objects.equals(name, user.name) &&
Objects.equals(createdAt, user.createdAt);
}
@Override
public int hashCode() {
return Objects.hash(id, email, password, name, createdAt);
}
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
}
}Entity Design Considerations
Each field in our User entity serves a specific purpose and has constraints.
The @Column annotations ensure data integrity by specifying that email must be unique and that essential fields cannot be null.
We use UUID instead of sequential IDs for better security and scalability.
Lifecycle Callbacks
The @PrePersist annotation helps us manage entity lifecycle events automatically.
When a new user is created, JPA will automatically call our onCreate() method to set the creation timestamp.
This ensures we always have an accurate record of when each user account was created.
Summary
- The User entity forms the foundation for authentication and user management
- JPA annotations map Java objects to database tables automatically
- UUID primary keys provide better security than sequential IDs
- Custom equals and hashCode methods ensure proper entity behavior
- Lifecycle callbacks automate administrative field updates