Jpa Slides Lab
Jpa Slides Lab
Spring Data JPA is a method to implement JPA repositories to add the data access
layer in applications easily. CRUD stands for create, retrieve, update, delete which are
the possible operations which can be performed in a database.
Spring Data JPA
Right-click on DatabasesCreateDatabase
PostgreSQL creating a database
Annotations:
@Entity
@Table
@Id
@GeneratedValue
@Column
Spring Data JPA
Use to create a project called jpa-book-renting-demo
Dependencies
- Spring Web
- Spring Security
- Spring Data JPA
- PostgreSQL Driver
- Lombok
Spring Data JPA
Spring Data JPA
Unzip, and Import the project as an existing maven project
DB Configuration
Open application.properties file and add the following:
Lombok
@Data // annotation from
Lombok creates the
setters and getters, equal
and hashcode methods
for the class User without
writing them explicitely
User Entity
Databases SchemasTables
Enum Types
• An enum type is a special data type that enables for a variable to be a set of
predefined constants. The variable must be equal to one of the values that have
been predefined for it.
• @Enumerated Annotation : The most common option to map an enum
value to and from its database representation in JPA before 2.1. is to use
the @Enumerated annotation. This way, we can instruct a JPA provider to
convert an enum to its ordinal or String value.
Ordinal String
0 User
1 ADMIN
2 SYSTEM_MANAGER
Enum Types
Create a new Object of type enum called Role with the following constant values
@Enumerated annotation
@Column annotation allows you to add more specific things about the field,
such as the name of the column in DB, uniqueness, nullable or not, and the
length. Add the following in your code
@Column annotation and constraints
Run the app, note the following SQL statement with the new constraint
Application layers
Model
Repository
Controller
Service
Repository
User
UserRepository
extends
Lombok annotations
Must be placed after
@Entity