Defining an Entity
Learn how to create an entity and look at different JPA annotations for defining a relational mapping.
We'll cover the following
JPA dependency
To use Spring Data JPA, we will add the starter JPA dependency to the pom.xml
file as follows:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
When the pom.xml
file is saved, we can see the JPA API in the Maven Dependencies folder. This API defines a lot of different annotations like @Entity
, @Column
, @Table
, etc. Hibernate is an implementation of the JPA API which automatically gets configured in our application. The hibernate-core
jar can be seen in the Maven Dependencies folder.
We will take the tennis player database example to understand Spring Data JPA. We will make a copy of the Player
and TennisPlayerApplication
classes and save them to a new package, io.datajek.springdatajpa
. As for the PlayerDao
class, we will implement the functionality of all methods using the JPA API.
@Entity
In our example, we have a Player
class that lists attributes of a tennis player like his name, nationality, date of birth, and a number of titles won. We need to tell JPA that the objects of this class need to be mapped to a table in a database. JPA will create a table with the same name as the class and create columns for all the members of the class. Every instance of the Player
class will become a row in the Player
table. We will use the @Entity
annotation to map this class to the Player
table.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.