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
idwith@Idand@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
mainclass. - Inside
main, instantiateUnicornDAO. - Demonstrate CRUD operations:
- Create a
Unicornand save it usingpersist. - Update the saved
Unicornusingmerge. - Fetch the updated
Unicornby ID usingfindand display its attributes. - Delete the
Unicornby 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()inUnicornDAOthat retrieves allUnicornentities using theEntityManager.createQuery()method. - Add validation constraints to the
Unicornentity, such asnameshould not be null or empty andpowerStrengthshould be between 1 and 100.
By completing this exercise, you will gain practical experience with standard JPA CRUD operations using Hibernate as the provider.