Spring Boot – Create JPA Repository

In this chapter, we would add a Spring Data JPA repository to our application.

 

  1. What is a JPA repository
  2. Configure the Entity
  3. Create the Repository

 

1. What is JPA Repository

Recall that in the previous chapters, we wrote codes to perform CRUD operations. For example, we wrote the method to getAllUsers, getUser, deleteUser and addUser. Now with the JPA repository, all of this have been implemented for us.The implementations are defined in the JpaRepository interface.

Therefore, you simply need to extend the JpaRepository. In this way, you will have the basic operations. It’s this easy! However, you can also write some custom methods if you want.

 

2. Configure the Entify

The first thing we need to do is to tell JPA that the student class is an entity.Therefore each instance of this class corresponds to a record in the database table. To achieve this, we add the @Entity annotation to the Student class.

Next, we also tell JPA which of the member variables is the primary key. You do this using the @Id annotation.

After this configuration, then our Student class would be as shown below:

 

package com.kindsonthegenius.social.student;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Student {
	
	@Id
	private String id;
	private String name;
	private String department;
	
	
	public Student(String id, String name, String department) {
		super();
		this.id = id;
		this.name = name;
		this.department = department;
	}


	public String getId() {
		return id;
	}


	public void setId(String id) {
		this.id = id;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}


	public String getDepartment() {
		return department;
	}


	public void setDepartment(String department) {
		this.department = department;
	}
	
}

 

3. Create the StudentRepository

Now we need to create the StudentRepository. This would be created as an Interface. It would extend the CrudeRepository. Then you need to specify the Entity type we are working with. In this case, it is Student. Finally, we specify the data type of the primary key. In this case, it is string.

Putting all this together, our StudentRepository would be as shown below;

 

package com.kindsonthegenius.social.student;

import org.springframework.data.repository.CrudRepository;

public interface StudentRepository extends CrudRepository<Student, String> {

      //With this the crud methods are now available
	
}

 

In the  next lesson, we would actually hook up the service with the repository.