Home  >  Article  >  Java  >  Java Repository

Java Repository

WBOY
WBOYOriginal
2024-08-30 15:40:28494browse

In the Java Spring framework, JPA-based repositories are commonly used. These repositories are crucial in managing database operations and are a part of the Spring Data JPA module. 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:

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  1. Relational tables are mapped to subsystems using map classes.
  2. EntityManager API.

In this article, we will be reading about syntax and the use of JPA repositories for CRUD operations.

Syntax:

Once all the necessary libraries have been imported and linked to Spring, Persistence objects, and Java EE in the classpath of the project, the next step is to create an interface by extending the “JpaRepository” interface. This is an extension of the repository library and contains other repositories like CrudRepository and PagingAndSortingRepository, along with the basic functions of repositories.

Note: POM.XML should be present in your project to use JPA applications.

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?

These implementations are crucial for enabling persistence in web or desktop applications developed using Java. To have these interfaces working, all the dependent libraries must 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 a java application. Using repositories brings easy handling of data from databases along with secure transactions.

Examples of Java Repository

Implementing a JPA repository is a complex time project for beginners. All linked libraries, JARs, dependencies, server setup, and database setup are prerequisites.

File: pom.xml

Code: This can be downloaded from https://start.spring.io. One can generate a file and download it after selecting the values as per their system and application requirements.

Note: Assuming that the database with a table named “user” is already present in the H2 database with two columns, “Id” and “Name.” “Id” is the primary key generated automatically by the system.

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:

Java Repository

Here the value is inserted into the database.

Explanation

The first file, “UserControl” contains details regarding extracting or storing the values using JPA functions like “@GetMapping()” and “@PostMapping” which require some base files to support it to work. These support files are User.java and UserJPARepository.java.

The file “User.java” maintains the structure of the database in the form of Java objects, allowing access to the database using Java persistence objects. To start working on the project, you must generate the “pom.xml” file using the provided source code in Step 1. In the provided output, the “pom.xml” file is responsible for setting up all the dependencies required for the project. 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.

Conclusion

JPA repositories are very useful as it provides a generic platform to create queries in the 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.

The above is the detailed content of Java Repository. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Range in JavaNext article:Range in Java