Unicorn
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.
- JDK 17 installed.
- IntelliJ IDEA
- A relational database (PostgreSQL).
- Maven for dependency management.

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. You can name it
unicorns.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. Give a fair try yourself before looking.
- 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
Suggested Class Diagram:
classDiagram class Unicorn { -Integer id -String name -int age -int powerstrength +Integer getId() +String getName() +int getAge() +int getPowerstrength() } class UnicornDAO { -EntityManagerFactory emf +Unicorn save(Unicorn unicorn) +Unicorn update(Unicorn unicorn) +boolean delete(int id) +Unicorn findById(int id) } class Main { -Unicorn unicorn +void main(String[] args) } class Database { } UnicornDAO --> Unicorn : manages Main --> Unicorn : uses Main --> UnicornDAO : uses UnicornDAO --> Database : connects to note for Database "Postgres DB"Run and Test:
- Run your application.
- Validate that each CRUD operation is functioning by examining the console output and checking the database.
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.
- 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.