spring data rest 入门(三)自定义查询

通过简单的增删改查知道了spring data rest 的基本语法,那么带入一些真实环境来实现一些用例。

一、密码一栏的信息不想让用户看到。

在user实体类中增加

    @JsonIgnore
    private String password;

http://localhost:8081/api/user/2

返回结果:

{
    "name": "李四",
    "age": 25,
    "sex": "男",
    "datatime": "2020-02-20 01:52:26",
    "_links": {
        "self": {
            "href": "http://localhost:8081/api/user/2"
        },
        "user": {
            "href": "http://localhost:8081/api/user/2"
        }
    }
}

二、组合输出用户姓名、性别、年龄。

新增一个接口:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.rest.core.config.Projection;

import test.entity.User;

@Projection(name="list",types=User.class)
public interface userList {

	@Value("#{target.name},年龄:#{target.age},性别:#{target.sex}")
	public String getFullInfo();
}

输入 http://localhost:8081/api/user?projection=list

将该接口配置在UserRepository上。

package test.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import test.entity.User;

/**
 * path="user": 映射路由
 * excerptProjection 映射接口
 * User:实体类
 * Long:主键
 * @author white
 *
 */
@RepositoryRestResource(path="user",excerptProjection=userList.class)
public interface UserRepository extends JpaRepository<User, Integer>{

}

输入http://localhost:8081/api/user

返回内容:(如果输入http://localhost:8081/api/user/2,显示不出这个组合字段)

{
    "_embedded": {
        "users": [
            {
                "fullInfo": "张三,年龄:16,性别:男",
                "_links": {
                    "self": {
                        "href": "http://localhost:8081/api/user/1"
                    },
                    "user": {
                        "href": "http://localhost:8081/api/user/1{?projection}",
                        "templated": true
                    }
                }
            },
            {
                "fullInfo": "李四,年龄:25,性别:男",
                "_links": {
                    "self": {
                        "href": "http://localhost:8081/api/user/2"
                    },
                    "user": {
                        "href": "http://localhost:8081/api/user/2{?projection}",
                        "templated": true
                    }
                }
            },
            {
                "fullInfo": "王五,年龄:32,性别:女",
                "_links": {
                    "self": {
                        "href": "http://localhost:8081/api/user/3"
                    },
                    "user": {
                        "href": "http://localhost:8081/api/user/3{?projection}",
                        "templated": true
                    }
                }
            }
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8081/api/user{?page,size,sort,projection}",
            "templated": true
        },
        "profile": {
            "href": "http://localhost:8081/api/profile/user"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 3,
        "totalPages": 1,
        "number": 0
    }
}

三、查找姓名为张三的信息

在UserRepository配置如下内容:


	@RestResource(path="name",rel="name")
	public String findByName(@Param("name") int name);

输入http://localhost:8081/api/user/search/name?name=张三

返回结果:

{
    "name": "张三",
    "age": 16,
    "sex": "男",
    "datatime": "2020-02-03 01:52:14",
    "_links": {
        "self": {
            "href": "http://localhost:8081/api/user/1"
        },
        "user": {
            "href": "http://localhost:8081/api/user/1{?projection}",
            "templated": true
        }
    }
}

这里有两个问题:1.为什么请求的url要加上search?2.为什么方法名必须是findByName?

按照Spring Data的规范的规定,查询方法以find | read | get开头(比如 find、findBy、read、readBy、get、getBy),涉及查询条件时,条件的属性用条件关键字连接,要注意的是:条件属性以首字母大写。框架在进行方法名解析时,会先把方法名多余的前缀截取掉,然后对剩下部分进行解析。

jpa命名规范请参考:点击这里

四、查询一个姓张的信息。

在UserRepository配置如下内容:

@RestResource(path="like",rel="nameStartsWith")
	public List<User> findByNameStartsWith(@Param("name") String name);

输入:http://localhost:8081/api/user/search/like?name=张

返回结果:

{
  "_embedded": {
    "users": [
      {
        "fullInfo": "张三,年龄:16,性别:男",
        "_links": {
          "self": {
            "href": "http://localhost:8081/api/user/1"
          },
          "user": {
            "href": "http://localhost:8081/api/user/1{?projection}",
            "templated": true
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8081/api/user/search/like?name=%E5%BC%A0"
    }
  }
}

五、查询一个姓名为张三,性别为男的信息。

在UserRepository配置如下内容:

@RestResource(path="more",rel="nameAndSex")
	public List<User> findByNameAndSex(@Param("name") String name,@Param("sex") String sex);

输入:http://localhost:8081/api/user/search/more?name=张三&sex=男

返回结果:

{
  "_embedded": {
    "users": [
      {
        "fullInfo": "张三,年龄:16,性别:男",
        "_links": {
          "self": {
            "href": "http://localhost:8081/api/user/1"
          },
          "user": {
            "href": "http://localhost:8081/api/user/1{?projection}",
            "templated": true
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8081/api/user/search/more?sex=%E7%94%B7&name=%E5%BC%A0%E4%B8%89"
    }
  }
}

六、将性别为男的信息按年龄排序输出。

在UserRepository配置如下内容:

@RestResource(path="ageDesc",rel="ageDesc")
	public List<User> findBySexOrderByAgeDesc(@Param("sex") String sex);

输入:http://localhost:8081/api/user/search/ageDesc?sex=男

返回结果:

{
  "_embedded": {
    "users": [
      {
        "fullInfo": "李四,年龄:25,性别:男",
        "_links": {
          "self": {
            "href": "http://localhost:8081/api/user/2"
          },
          "user": {
            "href": "http://localhost:8081/api/user/2{?projection}",
            "templated": true
          }
        }
      },
      {
        "fullInfo": "张三,年龄:16,性别:男",
        "_links": {
          "self": {
            "href": "http://localhost:8081/api/user/1"
          },
          "user": {
            "href": "http://localhost:8081/api/user/1{?projection}",
            "templated": true
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8081/api/user/search/ageDesc?sex=%E7%94%B7&%E5%BC%A0%E4%B8%89"
    }
  }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Data JPA 中,我们可以通过定义 Repository 接口中的方法,使用方法名来自动生成查询语句。但是有时候,我们需要自定义查询结果,比如说只需要查询结果中的部分字段,或者对查询结果进行聚合操作等。这时,我们可以使用 Spring Data JPA 提供的投影(Projection)功能来自定义查询结果。 投影是指将实体类中的一部分属性或关联属性映射成一个接口或类,从而返回一个自定义的结果集。Spring Data JPA 支持三种投影方式: 1. 接口投影:定义一个接口,接口中声明需要的属性,Spring Data JPA 将根据接口定义的属性生成查询结果。 2. 类投影:定义一个类,类中声明需要的属性,Spring Data JPA 将根据类定义的属性生成查询结果。 3. 动态投影:可以根据查询条件动态地返回不同的投影结果,比如说根据用户的角色返回不同的查询结果。 下面是一个简单的例子,演示如何使用接口投影来自定义查询结果: 定义一个接口投影: ```java public interface UserProjection { String getUsername(); String getEmail(); } ``` 在 UserRepository 中使用接口投影: ```java public interface UserRepository extends JpaRepository<User, Long> { List<UserProjection> findByUsername(String username); } ``` 通过上面的代码,我们可以在 UserRepository 中定义一个方法 findByUsername,该方法会返回一个 List<UserProjection> 类型的结果集,该结果集中只包含 username 和 email 两个字段。 当我们调用 findByUsername 方法时,Spring Data JPA 将根据方法名自动生成查询语句,并根据 UserProjection 接口中定义的属性生成查询结果。 当然,除了接口投影,还有其他的投影方式,你可以根据自己的需求选择适合的方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值