一、jpa中查询方法
查询方法 | jpa方法名 | 返回 | |
---|---|---|---|
1 | 全查询 | findAll() | list集合 |
2 | 主键查询 | findById() | Optional< UserEntity>实体对象 |
3 | 自定义条件查询 | findByNameAndPassword(String name, Long password) | UserEntity实体 |
自定义模糊查询 | findByNameLike("%"+name+"%") | list集合 | |
注意: | 自定义查询 | 需要在jpa中声明自定义的方法,确保命名规范! |
二、具体实现
controller中:
模糊查询:
这里给出四种方法部分代码,全部代码见github:UserController.java
@Autowired
private UserJPA userJPA;
@RequestMapping(value ="/queryUser",method = RequestMethod.GET)
public UserEntity login(String name,Long password) {
UserEntity userEntity= userJPA.findByNameAndPassword(name,password);
return userEntity;
}
@RequestMapping(value ="/findUser",method = RequestMethod.GET)
public List<UserEntity> find(String name) {
return userJPA.findByNameLike("%"+name+"%");
}
@RequestMapping(value ="/info",method = RequestMethod.GET)
public Optional<UserEntity> userInfo(Long id) {
return userJPA.findById(id);
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<UserEntity> list() {
return userJPA.findAll();//SpringDataJPA为我们提供的内置方法,它可以查询表内所有的数据
}
声明:UserJPA.java
UserEntity findByNameAndPassword(String name, Long password);
List<UserEntity> findByNameLike(String name);
三、查询效果
3.1 关键字查询,及模糊查询
自定义关键词查询请求:
http://localhost:8080/api/user/queryUser?name=test&password=123456
数据库查询无结果返回nul,有相应内容返回json:(这种适合登录判断)
模糊查询请求:http://localhost:8080/api/user/findUser?name=n
返回结果:(这适合输入关键词、下拉框等模糊查询)
3.2 主键查询
请求:http://localhost:8080/api/user/info?id=3
结果:
3.3 全查询
请求:http://localhost:8080/api/user/info?id=3
结果:
总结
今天学习了jpa全查询+主键查询+全查询
的三种方法,
用途 | |
---|---|
自定义属性查询 | 登录(name,password) |
主键(id)查询 | 登录后显示个人信息 |
全查询 | 表格,图表显示 (list) |
关键字模糊查询` | 输入框、下拉框模糊查询 |