快速学习Spring Data JPA -- 第三章JPA自定义查询@Query

xl_echo编辑整理,交流学习请加1280023003 百战不败,依不自称常胜,百败不颓,依能奋力前行。——这才是真正的堪称强大!!


其实通过前面两章,我们不难看出,如果是仅仅按照JPA提供的关键词和定义规则,我们在操作数据库的时候,会有一定的局限性。当涉及到比较复杂的数据操作的时候,我们命名方法有可能就很难下手。所以,JPA也对此提供了解决办法,@Query

@Query是一个注解,作用在于声明在一个Repository的查询方法上,同时配置JPQL语法,编写sql语句就可以达到我们想要的效果。类似于hibernate的hql语句。

JPQL语句
这种语句有一个很明显的特征,那就是很类似SQL,但是与SQL不同的是,它的字段在编写时不是数据库字段,而是实体类中的属性。比如:表名用Entity名称来代替,字段用Entity.properties来代替。

JPQL实例演示

package com.echo.example.example.repository;

import com.echo.example.example.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

/**
 * author:XLecho
 * Date:2018/10/26 0026
 * Time:9:54
 */
public interface UserRepositoryExtendsJpaRepository extends JpaRepository<User, Long> {

    @Query("select u from User u where u.email = ?1")
    User findByEmail(String email);

}

相对来说如果使用JPQL语句比较容易和SQL混淆,那么我们的@Query支不支持sql语句呢?

@Query支持原生SQL

当你不会用JPQL的时候,基本的查询方法不能满足需求的时候,建议直接使用原生SQL语句。楼主也是喜欢使用原生SQL,不容易混淆出错。

要原生sql生效,需要在@Query中加上nativeQuery=true

示例:

package com.echo.example.example.repository;

import com.echo.example.example.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.Optional;

/**
 * author:XLecho
 * Date:2018/10/26 0026
 * Time:9:54
 */
public interface UserRepositoryExtendsJpaRepository extends JpaRepository<User, Long> {

    @Query(value = "select * from user where id = ?1", nativeQuery=true)
    Optional<User> queryByIdTest(Long id);

}

@Query分页

这里直接使用Pageable的实现类来完成分页

package com.echo.example.example.repository;

import com.echo.example.example.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.awt.print.Pageable;
import java.util.List;
import java.util.Optional;

/**
 * author:XLecho
 * Date:2018/10/26 0026
 * Time:9:54
 */
public interface UserRepositoryExtendsJpaRepository extends JpaRepository<User, Long> {

    @Query(value = "select * from user where email = ?1", nativeQuery = true)
    Page<User> queryLikeEmail(String email, PageRequest pageable);

}

项目地址:https://git.coding.net/xlecho/SpringDataJpa.git

猜你喜欢

转载自blog.csdn.net/xlecho/article/details/83411332
今日推荐