Spring data JPA — default method

Time:2020-2-13

Preliminary exploration of SDJ

Let’s consolidate the basics of Java. Java is an object-oriented language, which aims to solve the problems in real life. We can use classes to package things in real life into objects, use attributes to describe the characteristics of objects, and use methods to control the behavior of objects. All our operations in Java are aimed at the object itself, which is why we need ORM to operate the “object” stored in the database. In addition, for NoSQL (non relational database) based on key value storage like redis, we can’t obviously observe the “object” stored in it, because this “object” is different from the object in relational database, such as mysql. In mysql, the table corresponds to the class in Java, each column corresponds to the object, and each field corresponds to the property. Of course, MySQL has its own method, but it is not covered in this article. We can intuitively observe “objects” through SQL query statements, but in NoSQL, we can only write and read objects through serialization and deserialization. Trust me, you’d rather see assembly than serialized objects

In order to save time, we won’t go into details about what and how to build the basic environment. Here is one of the official guidelines of sdj for your reference, as long as you can refer to sdj’s package (org. Springframework. Data: Spring data JPA: 1.11.6. Releas).

Sdj should pay more attention to the following core interfaces for application (in the order of inheritance from subclass to parent class):

  • JPA repository — the interface of JPA protocol.

    package org.springframework.data.jpa.repository;

    public interface JpaRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {}
  • Pagingandsortingrepository — interface for paging and sorting. Querybyexampleexecutor — interface for instance query.

    package org.springframework.data.repository;

    public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {}
    
    package org.springframework.data.repository.query;

    public interface QueryByExampleExecutor<T> {}
  • Crudrepository — interface for general CRUD operations.

    package org.springframework.data.repository;
    
    public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {}

Just like the name shows, we can inherit specific interfaces according to the situation. Different interfaces provide different functions. If we need to page and sort, we can inheritPagingAndSortingRepositoryInterface. However, in order to fully understand sdj, this paper usesJpaRepositoryInterface, because it is located at the bottom of the inheritance tree, which can be understood as the leaves in the binary tree, can use all the unwritten methods including its parent class. Of course, there are some contradictions that do not affect the function realization. We will see them later.

Prepare for using the default interface method

As mentioned before, we need to build an object through classes. Create a user class here (Lombok is recommended to simplify the code).

//Sdj uses @ entity, NoSQL uses @ document. (not verified yet)
@Entity
public class User {
    //Declare the primary key.
    @Id
    //Declare that the primary key generation policy is controlled by the program.
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    //Constraint, cannot be empty, length 16.
    @Column(unique = true, nullable = false, length = 16)
    private String username;
    @Column(unique = true, nullable = false)
    private String email;
    //Set the default value.
    private Double balance = 0.0;
    //Updates are not allowed.
    @Column(updatable = false)
    private Date createTime = new Date();

    //Provides a default construction method for sdj.
    public User() {
    }

    //Provides a constructor for a non nullable property to prevent errors.
    public User(String username, String email) {
        this.username = username;
        this.email = email;
    }

    //Omit a bunch of getter, setter, and toString methods. You can also use Lombok plug-in to greatly simplify the way of annotation, which is provided by all major ides!
}

And then create an interface that’s simple enough to be suspicious of your life, inherited fromJpaRepository

import org.springframework.data.jpa.repository.JpaRepository;
import top.cciradih.spring.data.jpa.entity.User;

//The < user, long > generic specifies the acceptable object type and its primary key type, which is useful in some methods.
public interface UserRepository extends JpaRepository<User, Long> {
}

Surprise or not? Did it happen? We can use it already! Don’t write anything!

Try the interface default method

Preservation

Save individual objects and return to

//Saves a single object and returns.
        User savedUser = userRepository.save(new User("Cciradih", "[email protected]"));

This is called.CrudRepository<T, ID extends Serializable>Interface<S extends T> S save(S entity)Method to save and return the stored object.

Save multiple objects and return

//Save multiple objects and return.
        List<User> userList = new ArrayList<>();
        User newUser;
        for (int i = 0; i < 10; i++) {
            newUser = new User("Cciradih" + i, "[email protected]" + i);
            userList.add(newUser);
        }
        List<User> savedUserList = userRepository.save(userList);

This is called.JpaRepository<T, ID extends Serializable>Interface<S extends T> List<S> save(Iterable<S> entities)Method to save multiple objects.

query

Query single object based on primary key

//Query a single object based on the primary key.
        User foundUser = userRepository.findOne(1L);

This is called.CrudRepository<T, ID extends Serializable>InterfaceT findOne(ID id)Method to query a single object.

Query all objects

//Query all objects.
        List<User> foundUserList = userRepository.findAll();

This is called.JpaRepository<T, ID extends Serializable>InterfaceList<T> findAll()Method to check all objects.

Query and sort by ID field

import org.springframework.data.domain.Sort;

        //Query and sort according to the ID field, and the default is order (ASC).
        List<User> foundASCSortedUserList = userRepository.findAll(new Sort("id"));
        //Query in reverse order according to the ID field (DESC).
        List<User> foundDESCSortedUserList = userRepository.findAll(new Sort(Sort.Direction.DESC, "id"));

New objects are involved here——new Sort("id")。 It can be seen from the name that it is for sorting, and its internal specific logic will not be described in detail in this article. adoptJpaRepository<T, ID extends Serializable>InterfaceList<T> findAll(Sort sort)Method to query and sort.

Example query

import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;

        User user = new User("Cciradih", "[email protected]");
        //1. Use example.
        //Create an example.
        Example<User> userExample = Example.of(user);
        User foundExampleUser = userRepository.findOne(userExample);
        //2. Use the examplematcher.
        //Create an examplematcher.
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                //Ignore the ID and createtime fields.
                .withIgnorePaths("id", "createTime")
                //Ignore case.
                .withIgnoreCase()
                //Ignore empty fields.
                .withIgnoreNullValues();
        //Take the examplematcher.
        userExample = Example.of(user, exampleMatcher);
        User foundExampleWithExampleMatcherUser = userRepository.findOne(userExample);

This involves the use of example and examplematcher.

Example through its static method<T> Example<T> of(T probe)To introduce aExample<T>Object. And then throughQueryByExampleExecutor<T>Interface<S extends T> S findOne(Example<S> example)Method to query objects that match the instance. Of course, in general, no object can be queried here, because users have different IDs and, in a sense, will not be the same createtime.

Examplematcher uses static methods<T> Example<T> of(T probe, ExampleMatcher matcher)Carry a generic object andExampleMatcherObject, the ID and createtime fields are ignored here, so qualified objects can be found.

Examplematcher is an extension of example, which is why I say that the control of sdj is still very delicate.

For more filtering methods of examplematcher, you can refer to the source code.

Paging query

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

        //Page by page query, starting from page 0 to query 5.
        Page<User> foundUserPage = userRepository.findAll(new PageRequest(0, 5));
        //Paging table.
        List<User> content = foundUserPage.getContent();
        //Total quantity.
        long totalElements = foundUserPage.getTotalElements();
        //Total pages.
        long totalPages = foundUserPage.getTotalPages();
        //Paging table size.
        int size = foundUserPage.getSize();

New objects are involved here——new PageRequest(0, 5)。 It can be seen from the name that it is for pagination, and its internal specific logic will not be described in detail in this article. adoptPagingAndSortingRepository<T, ID extends Serializable>InterfacePage<T> findAll(Pageable pageable)Method to queryPage<T>Object. Page contains all the properties required for paging, which can be obtained through its methods.

delete

Delete individual objects based on primary key

//Delete individual objects based on primary key
        userRepository.delete(1L);

This is called.CrudRepository<T, ID extends Serializable>Interfacevoid delete(ID id)Method to delete a single object based on the primary key.

Delete individual objects based on objects

//Delete individual objects based on objects
        User user = new User("Cciradih", "[email protected]");
        userRepository.delete(user);

This is called.CrudRepository<T, ID extends Serializable>Interfacevoid delete(T entity)Method to delete an individual object based on the object. Like the example, no objects will be deleted. Please think about it.

Delete all

//Delete all
        userRepository.deleteAll();

This is called.CrudRepository<T, ID extends Serializable>Interfacevoid deleteAll()Method to delete an individual object based on the object.

Some of the contradictions mentioned before that do not affect the function realization are reflected here. BecauseJpaRepository<T, ID extends Serializable>Indirectly inherited fromCrudRepository<T, ID extends Serializable>So we can use it at the same timevoid deleteAllInBatch()andvoid deleteAll()Method, the functions of the two are the same, and one of them can be used. To avoid this, you can only inherit the interface up without affecting the actual business logic.

Delete multiple objects

//Delete multiple objects
        List<User> userList = new ArrayList<>();
        User user;
        for (int i = 0; i < 10; i++) {
            user = new User("Cciradih" + i, "[email protected]" + i);
            userList.add(user);
        }
        userRepository.delete(userList);

This is called.CrudRepository<T, ID extends Serializable>Interfacevoid delete(Iterable<? extends T> entities)Method to delete multiple objects. Like the example, no objects will be deleted. Please think about it.

Number of statistical objects

//Number of statistical objects
        long count = userRepository.count();

This is called.CrudRepository<T, ID extends Serializable>Interfacelong count()Method to count the number of objects.

Judge whether an object exists according to the primary key

//Judge whether the object exists
        boolean exists = userRepository.exists(1L);

This is called.CrudRepository<T, ID extends Serializable>Interfaceboolean exists(ID id)Method to determine whether an object exists based on the primary key.

epilogue

I listed the default methods as much as possible, but for the convenience of writing, some of them can be used together, such asJpaRepository<T, ID extends Serializable>Interface<S extends T> List<S> findAll(Example<S> example, Sort sort), you can pass in the example and sort objects to query at the same time. Please refer to the source code.

I hope you can achieve the degree of “knowing what it is” through the default method of sdj in this article. In software development, I think it is necessary to go from “knowing what it is” to “knowing why it is” and then “creating why it is”, but the road needs to be step by step.

  • Source repository

Learn/Spring Data JPA at master · cciradih/Learn

  • Series catalogue

Spring data JPA detailed guide

  • Reference resources

Spring Data JPA – Reference Documentation

  • My Cafe

If you have any suggestions or questions about this article, please come to my cafe and take a seat at 338147322.

Recommended Today

Microsoft: typescript 3.9 can reduce compilation time by 40%

Technical editor: Xu Jiuyi’s infatuation from midnightSegmentFault has he reported the official account number: SegmentFault Recently, Microsoft’s typescript team released version 3.9 of this young programming language, which is a superset of JavaScript, which can be compiled into JavaScript code, in or out of the browser Node.js Run on. Microsoft released typescript for large JavaScript […]