Spring Data JPA
Spring Data JPA
What is Spring Data JPA
Connect to a real database and not in memory DB
How to map classes to tables
Hibernate Entity Life Cycle
Queries
Paging and Sorting
1 to 1 Relationships
1 to Many Relationships
Many to Many relationships
Transactions
Spring Data JPA
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
Java Object Database Table
ORM: Object-Relational Mapping
In Java: JPA through Hibernate
PostgreSQL creating a user
Open pgAdmin Login/Group Roles
PostgreSQL creating a user
Right-click on Login/Group RolesCreate Login/Group Role
PostgreSQL creating a user
Go over the following Tabs, then hit Save
PostgreSQL creating a database
Right-click on DatabasesCreateDatabase
PostgreSQL creating a database
Fill in the following information, then hit Save
Spring Data JPA
Open pgAdmin:
- Create a new user: admin
- Give it all the privileges
- Create a database: db_book
Spring Data JPA
User Class User table
- id: Long - ID: bigint
- firstName: String - firstName: text
- lastName: String - lastName: text
- username: String - username: text
- password: String - password: text
- role: String - role: text
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 [Link] file and add the following:
1. Indicates the url path to the database
2. Indicates the username that has some privileges for the database
3. Indicates the password for the database user
4. Instructs hibernate to update the database
5. Specifies Dialect used in the connection
6. beautify or pretty print the SQL on the standard ou (console)
7. Instructs hibernate to print the SQL on the standard ou (console)
--no need to specify the driver
[Link]-class-name=[Link]
DDL (Data Definition Language)
The list of DDL possible options are:
•validate: validate the schema, makes no changes to the database.
•update: update the schema.
•create: creates the schema, destroying previous data.
•create-drop: drop the schema when the SessionFactory is closed
explicitly, typically when the application is stopped.
•none: does nothing with the schema, makes no changes to the
database
User Entity
Create a model package, and a new class called User with the following annotations
Lombok
@Data // annotation from
Lombok creates the
setters and getters, equal
and hashcode methods
for the class User without
writing them explicitely
User Entity
@Entity defines the class as an Entity serializable
@Table defines the name of the table in the database
@Id: define the following attribute as an identifier
If we want to automatically generate the
primary key value, we can add the
@GeneratedValue annotation.
This can use four generation types:
• AUTO,
• IDENTITY,
• SEQUENCE
• TABLE.
Run your application
Run your application, notice the following SQL statement
Check Database in PostgreSQL
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
Edit User Entity and modify the code as below
Stop the running process and re*rerun the app
Search for the process running on port 8080, then stop it
Re-run the app
@Enumerated annotation
Note the camel case in java:
firstName converted to first_name
@Column 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
JpaRepository PagingAndSortingRepository CrudRepository
extends extends
Jpa methods, flush and Paging and sorting Crud methods
batch
UserRepository Interface
1. Create a new package called repositories
2. Create a new interface called UserRepository
Note the class name User and the type of its id
UserService Class
1. Create a new package called service
2. Create a new class called UserService
Add constructor without the id argument
Because we are using Lombok
Add constructor without the id argument
Because we are using Lombok
Add constructor without the id argument
CommandLineRunner Interface
Using CommandLineRunner Interface, allows us to execute additional code before
the app has fully started.
Add the following code after the main method of the JpaBookRentingDemoApplication
class
Run and Check
Note the following in the console
Run and Check
In PostgreSQL, click Tables right-click then refresh, then View/Edit Data
Java Persistent API JPA
You can define your own queries in the Spring Data repositories
Without writing a single SQL code.
• findByFirstName
• findByLastName
• findByUsername
• findByRole
Add the following methods in
UserRepository interface
Other JPA methods
Add the following
Methods
In UserService class
Test these methods
Add the following code in the CommanLineRunner interface
Test these methods
Before running add a customized toString() method to the User Entity
Java Persistent API JPA
You can create queries by using SQL Statements via the @Query
annotation.
Install Lombok in Eclipse
Navigate to Lombook Project folder
Install Lombok in Eclipse
Click on [Link] file , it will run and detect your IDE, then click Install
Install Lombok in Eclipse
Close Eclipse and Re-open it
Lombok annotations
Must be placed after
@Entity