Introduction to Java Repository
Java repositories are commonly known as JPA based repositories used under JAVA spring framework. Repositories define a new elegant method of storing, updating, and extracting the data stored from JAVA applications in the backend. All of the CRUD (Create, read, update, and delete) operations can be implemented with the help of a repository interface. JPA is an abbreviation for JAVA Persistence API (Application program interface). As the name suggests JPA helps in persisting the java objects in relational databases. There are two ways of doing this and they are:
- Relational tables are mapped to subsystems using map classes.
- EntityManager API.
In this article, we will be reading about syntax and the use of JPA repositories for CRUD operations.
Syntax:
After all the related libraries are imported linked to spring, Persistence objects, and JAVA EE to the classpath of the project then an interface is created by extending “JpaRepository”. This is an extension of the repository library and contains other repositories like CrudRepository and PagingAndSortingRepository along with basic functions of repositories.
Structure:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.guides.springboot.jparepository.model.Employee;
@Repository
public interface repositoryname extends JpaRepository<Parameter 1 column name, parameter 2 data type>
{
}
//Invocation of the interface created above.
private repositoryname RepositoryName;
@Override
//Different functions from JPA library to be used for enabling transactions with databases.
public void run(String…... arguments) throws Exception {
RepositoryName.save(new TableName("Data1", "Data2", "Data3"));
RepositoryName.save(new TableName("Data1", "Data2", "Data3"));
RepositoryName.save(new TableName("Data1", "Data2", "Data3"));
RepositoryName.save(new TableName("Data1", "Data2", "Data3"));
logger.info("number of elements in table now: {}", RepositoryName.count());
How does the JPA Repository Work?
JPA repositories are created by extending the JpaRepository library consisting of implementation of different functions, methods, and other related dependent data types to enable persistence in web or desktop applications designed using JAVA. To have these interfaces working all the dependent libraries are to be loaded in the classpath.
Once the interface is created then functions like “save()”, “count()”, “info()”, “findAll()”, “sort()” and others are used to accomplish the data query or required data manipulation. We need to have a database set up to insert, update, or delete the values from tables beneath via java application. Using repositories brings easy handling of data from databases along with secure transactions. This can be understood well with an example below.
Examples of Java Repository
Implementing a JPA repository is a complex time project for beginners. All linked libraries, JARs, dependencies, server setup, database setup comes as a prerequisite to it.
File: pom.xml
Code: This can be downloaded from https://start.spring.io . Here default values as per general config is given. One can generate a file and download it after selecting the values as per their system and application requirements. This file can then be included in your project once created.
File: UserControl.java
Code:
package test.controller;
import test.model.User
import test.repository.UserJpaRespository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UsersControl {
@Autowired
private UserJpaRespository userJpaRespository;
@GetMapping(value = "/all")
public List<User> findAll() {
return userJpaRespository.findAll();
}
@PostMapping(value = "/load")
public User load(@RequestBody final User users) {
userJpaRespository.save(users);
return userJpaRespository.findByName(users.getName());
}
}
File: User.java
Code:
package test.model
import test.controller;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
@Entity
public class User {
private Long id;
private String name;
@Id
@GeneratedValue
public Long getId() {
return id;}
public void setId(Long id) {
this.id = id;}
public String getName() {
return name;}
public void setName(String name) {
this.name = name;}
}
File: UserJPARepository.java
Code:
package test.repository;
import test.controller;
import package.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
@Component
public interface UserJpaRespository extends JpaRepository<User, Long>{
}
File:Implementation.java
Code:
package test.implementation;
import static org.hamcrest.CoreMatchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import test.controller;
import org.junit.Before;
import org.junit.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import test.model.user;
import com.fasterxml.jackson.databind.ObjectMapper;
import test.repository.UserJpaRespository;
@RunWith(SpringRunner.class)
public class Implementation {
private User user;
@MockBean
private UserJpaRespository userJpaRespository;
@Before
public void setUp()
{
user = new User();
user.setId(1l);
user.setName("Virat");
}
}
Output:
The output can be obtained using localhost/users/ {–name you want to insert in database–}
Here the value is inserted in the database.
Explanation
The first file “UserControl” contains details regarding extracting or storing the values using JPA functions like “@GetMapping()” and “@PostMapping” which requires some base files to support it to work. These support files are User.java and UserJPARepository.java.
In the file “User.java” a structure of the database is maintained in the form of java objects so that database can be accessed using java persistence objects. Before getting into the project the pom.xml should be generated via the source provided in step 1 so that all dependencies linked to the database and other resources are set up correctly. Dependencies contain “spring framework” related data and persistence object-related data. UserJPARepository.java file provides the initiation of a JPA repository by extending the built-in library JpaRepository. The actions are performed using the last file named Implementation.java.
Conclusion
JPA repositories are very useful as it provides a generic platform to create queries in JAVA language but can be used with any database beneath. It reduces the number of code lines by providing elegant functions to accomplish the tasks backed up by libraries. It reduces the use of “boiler plate” code thus improving the look and speed of execution.
Recommended Articles
This is a guide to Java Repository. Here we discuss an Introduction to Java Repository and How does the JPA Repository Work with code implementation?. You may also have a look at the following articles to learn more –