Exercise: Java JPA with Hibernate - Standard CRUD Operations on Unicorn Entity
Check pantopto videos with solutions
Objective
Create a Java application that uses Java Persistence API (JPA) with Hibernate to perform standard CRUD (Create, Read, Update, Delete) operations on a Unicorn
entity. Use standard JPA methods: persist
, merge
, remove
, and find
.
Prerequisites
- JDK installed.
- An IDE (IntelliJ IDEA)
- A relational database (PostgreSQL).
- Maven for dependency management.
Steps
- Set Up a New Project:
- Create a new Maven project in your IDE using this tutorial
-
Create a new database in Postgres for the project.
- Create the Entity Class:
- Create a new Java class named
Unicorn
. - Add attributes:
id
,name
,age
, andpowerStrength
. - Annotate
id
with@Id
and@GeneratedValue
. - Annotate the class with
@Entity
.
- Create a new Java class named
- Create UnicornDAO Class:
- Create a new class named
UnicornDAO
. - Implement methods for CRUD operations using standard JPA methods:
save(Unicorn unicorn)
usingEntityManager.persist()
update(Unicorn unicorn)
usingEntityManager.merge()
delete(int id)
usingEntityManager.remove()
findById(int id)
usingEntityManager.find()
- Peek at these snippets for inspiration.
- Create a new class named
- Main Application:
- Create a
main
class. - Inside
main
, instantiateUnicornDAO
. - Demonstrate CRUD operations:
- Create a
Unicorn
and save it usingpersist
. - Update the saved
Unicorn
usingmerge
. - Fetch the updated
Unicorn
by ID usingfind
and display its attributes. - Delete the
Unicorn
by ID usingremove
.
- Create a
- Create a
- Run and Test:
- Run your application.
- Validate that each CRUD operation is functioning by examining the console output and checking the database.
Expected Outcome
After running the application, you should be able to see the Unicorn
entity being created, updated, fetched, and deleted in both your database and console output, utilizing standard JPA methods.
Bonus Challenge
- Implement a method
findAll()
inUnicornDAO
that retrieves allUnicorn
entities using theEntityManager.createQuery()
method. - Add validation constraints to the
Unicorn
entity, such asname
should not be null or empty andpowerStrength
should be between 1 and 100.
By completing this exercise, you will gain practical experience with standard JPA CRUD operations using Hibernate as the provider.