java - How to get all values from a table in spring boot with where condition?
问题描述
I am learning Spring Boot
and basically want to make a query like this that returns all rows whose age is 5.
SELECT * FROM pets WHERE age = 5;
With Spring Boot, getting all pets or a pet with a unique id is easy using the JPA
and Hibernate
and I can simply do this.
PetsController.java
//for all pets
@GetMapping
public List<Pet> getAllPets() {
return petService.getAllPets();
}
//for getting one pet with unique id
@GetMapping("{id}")
public ResponseEntity<Pet> getPetById(@PathVariable("id") int petId) {
ResponseEntity<Pet> matchingPet = new ResponseEntity<Pet>(petService.getPetById(petId), HttpStatus.OK);
return matchingPet;
}
PetService.java
public interface PetService {
List<Pet> getAllPets();
Pet getPetById(int petId);
}
PetServiceImpl.java
@Service
public class PetServiceImpl implements PetService {
private PetRepository petrepository;
public PetServiceImpl(PetRepository petrepository) {
this.petrepository = petrepository;
}
@Override
public List<Pet> getAllPets() {
return petrepository.findAll();
}
@Override
public Pet getPetById(int petId) {
Optional<Pet> pet = petrepository.findById(petId);
if (pet.isPresent()) {
return pet.get();
}
else {
return null;
}
}
}
PetRepository.java
public interface PetRepository extends JpaRepository<Pet, Integer> {
}
Since getting list of pets and getting pets by id was easy enough by using the JpaRepository
, I was wondering if there are any methods available that does something similar that returns all pets whose age is 5. Or would I need to make a custom query for this? And if so, how?
解决方案
If you're just going to do a search by age, you can use Query creation from method names method.
public interface PetRepository extends JpaRepository<Pet, Integer> {
List<Pet> findAllByAge(Integer age);
}
OR
Alternatively, you can also use the @Query
annotation to apply your query.
public interface PetRepository extends JpaRepository<Pet, Integer> {
@Query("select p from Pet p where p.age = ?1")
List<Pet> findAllByAge(Integer age);
}
Note: If you have too many criteria or if you want to search according to certain conditions, you should use Specification
.
推荐阅读
- javascript - React 组件渲染两次,不使用状态钩子的函数组件只渲染一次
- java - JavaFx 中的 TranslateX、LayoutX 和 ScaleX 之间的区别?
- javascript - javascript数组由两个键混合
- python - 我正在从我的函数返回一个列表,但是当我打印返回的列表时,它会打印 NONE
- javascript - 用 useEffect 反应去抖动
- javascript - jquery-除非输入必填字段,否则如何防止下一页执行?
- javascript - 使用兄弟之间的数据隐藏子组件
- django - 使字段唯一时Django数据库错误
- mysql - 更新 MyISAM sdi 版本
- nginx - nginx 可以自己生成原始响应吗?