Show Topics
Hide Topics

Spring Boot JPA Example

 

Spring Boot JPA : Spring Boot provides spring-boot-starter-data-jpa starter to connect Spring application with relational database efficiently. You can use it into project POM (Project Object Model) file.

 

 

JPA Annotations

By default, each field is mapped to a column with the name of the field. You can change the default name via @Column (name="newColumnName").

 

The following annotations can be used.

@Entity Marks java class to a Table name
@Table(name="tabname") Provides table name, when table name & class names are different .
@Id Identifies the unique ID of the database entry
@GeneratedValue Together with an ID this annotation defines that value is generated automatically.
@Transient Field will not be saved in database

The central interface in Spring Data repository abstraction is Repository (probably not that much of a surprise). It takes the domain class to manage as well as the id type of the domain class as type arguments.

 

 

 

CrudRepository

The CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed

 

 

PagingAndSortingRepository

On top of the CrudRepository there is a PagingAndSortingRepository abstraction that adds additional methods to ease paginated access to entities:

 

 

 

Example

 

Student.java – create an entity class that contains the information of a single Student entry

 

 

StudentRepository.java

We can create the repository that provides CRUD operations for Student objects by using one of the following methods:

  1. Create an interface that extends the CrudRepository
  2. Create an interface that extends the Repository interface and add the required methods to the created interface.
 

 

StudentService.java

 

 

StudentController.java

 

 

SpringBootApp.java

 

 

http://localhost:8080/ -get All Students