JPA Rapid Development Query Interface Repository

What is JPA

SpringData is a data manipulation framework provided by Spring, and SpringData JPA is a module for data manipulation based on the JPA standard under this framework.

SpringData JPA simplifies the operation of the persistence layer code, and it can be realized only by writing the interface.

JPA, the full name of Java Persistence API, is one of the sub-projects of Spring Data. It is a tool for JDK 5.0 annotations or XML to describe the mapping relationship between objects and relational tables, and it can persist entity objects at runtime to the database.

Both JPA and Mybatis are persistence layer frameworks with the same functions. However, due to the widespread use of Mybatis, fewer people understand and use JPA now.

JPQL evolved from Hibernate's HQL, and its syntax is very similar to HQL. HQL is Hibernate Query Language (Hibernate Query Language), and SQL is Structure Query Language (Structured Query Language).

Their main difference is: SQL directly manipulates the tables and fields in the database, while HQL manipulates entity objects and attributes.

It should be noted that the JPQL we write will eventually be converted into SQL statements for execution.

Interface inheritance relationship

Repository<T, ID> interface The top-level interface is used to customize JPQL statements

/**
 * 使用@Query注解,自定义JPQL语句
 * JPQL语句中,使用的不是表名,而是实体类名,不是列名,而是属性名,
 * 例如SQL语句:select * from user  JPQL语句是:select User from User
 * 如果是条件查询,之前语句中的占位符?可以使用(:xxx)进行表示
 * 此时xxx会根据方法中同名的形参自动绑定值
 */
public interface UsersRepositoryByQuery extends Repository<User, Integer> {
    
    
    //如果是查询所有列,可以省略select ....,从from开始写
    @Query("from User where name=:name")
    List<User> selectByName(String name); //select * from user where name=?

    @Query("select u from User u where name=:name and age=:age")
    List<User> selectByNameAndAge(String name, Integer age); //select * from user where name=? and age=?

    @Query("from User where name=:name and age=:age")
    List<User> selectByNameLike(String name);//select * from user  where name like ?

    //除了使用JPQL语句,也是可以使用sql原生语句,在注解中设置参数nativeQuery = true,不推荐!
    @Query(value = "select * from user where name=:name",nativeQuery = true)
    List<User> selectByNameSQl(String name);//select * from user where name=?
}

The CrudRepository interface inherits the Repository interface , and the methods for adding, deleting, modifying and checking built-in classes

The PagingAndSortingRepository interface inherits the CrudRepository interface
and adds paging and sorting methods

 @Autowired
    private UserRepositoryPage userRepositoryPage;
    /**
     * 分页
     */
    @Test
    void testPage(){
    
    
        //第一个参数是页码数,0表示第一页;第二参数是分页单位;
        Pageable Pageable = PageRequest.of(0, 2);
        Page<User> page = userRepositoryPage.findAll(Pageable);
        System.out.println("总数据量"+page.getTotalElements());
        System.out.println("总页数"+page.getTotalPages());
        List<User> content = page.getContent();
        for (User user : content) {
    
    
            System.out.println(user);
        }
    }
    /**
     * 排序
     */
    @Test
    void testSort(){
    
    
        //根据id排序
        Sort sort = Sort.by(Sort.Order.desc("id"));
        Iterable<User> all = userRepositoryPage.findAll(sort);
        for (User user : all) {
    
    
            System.out.println(user);
        }
    }

JpaRepository<T, ID> interface

Inherited from PagingAndSortingRepository<T, ID>

and query interface QueryByExampleExecutor

The feature is that it can help us adapt the return values ​​of methods of other interfaces. It can make it easier for us to use these methods when developing

The JpaSpecificationExecutor interface mainly provides support for multi-condition query, and can add paging and sorting to the query

The JpaSpecificationExecutor interface has nothing to do with the above interfaces and is completely independent.
It cannot be used alone, but needs to be used together with other interfaces in JPA.

//接口  
public interface UserRepositoryExJPA extends JpaRepository<User,Integer>,JpaSpecificationExecutor<User> {
    
    
}

  
//使用  
@Autowired
    private UserRepositoryExJPA userRepositoryExJPA;

    /**
     * 自定义规则,可以多条件查询
     */
    @Test
    void testExJPA2() {
    
    
        Specification<User> specification = new Specification<User>() {
    
    
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
    
    
                //模糊查询
                Predicate predicate = criteriaBuilder.like(root.get("name"), "张%");
                //模糊查询+性别筛选+年龄筛选
                Predicate predicate2 = criteriaBuilder.and(criteriaBuilder.like(root.get("name"), "张%"),
                        criteriaBuilder.equal(root.get("sex"), "男"), criteriaBuilder.gt(root.get("age"), 24));
                return predicate2;
            }
        };
        //进行排序年龄进行倒序排列
        Sort sort = Sort.by(Sort.Order.desc("age"));
        //分页+追加排序
        Pageable pageable = PageRequest.of(0, 2, sort);
        Page<User> page = userRepositoryExJPA.findAll(specification, pageable);
        System.out.println("根据条件查询到" + page.getTotalElements() + "条数据");
        System.out.println("根据条件查询到" + page.getTotalPages() + "页数据");
        System.out.println("当页数据");
        for (User user : page) {
    
    
            System.out.println(user);
        }
    }  

JpaRepositoryImplementation<T, ID> interface

Inherited JpaRepository<T, ID>, JpaSpecificationExecutor interface

The implementation class is the SimpleJpaRepository<T, ID> interface with the most powerful functions

key naming query

According to Spring Data's specification, query methods should start with find, read, or get (eg find, findBy, read, readBy, get, getBy). When it comes to query conditions, you should use the condition keyword to connect attributes, and make sure the first letter of the condition attribute is capitalized. When parsing the method name, the framework will first remove the redundant prefix, and then parse the rest.

You can define the query method directly in the interface, as long as it conforms to the specification, you don't need to write the implementation or SQL. The currently supported keywords are as follows:


Pay attention to the official account, the programmer will continue to output high-quality content at three o'clock , hoping to bring you some inspiration and help

Guess you like

Origin blog.csdn.net/u011738045/article/details/131931404