Home > OS >  JPA Repos- Is there a way to return all data without using ID?
JPA Repos- Is there a way to return all data without using ID?

Time:03-09

I am trying to return a search bar of results based on a food's name on my front end. Therefore on the backend, I need to have a GetMapping that returns all data based on name. Basically, I want to find all food products by name. Is it possible to do this without using the Serial Key ID?

Here is my model:


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="food")
public class Food {

    @Id
    @Column
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id; 
    
    @Column(name="category")
    private String category;
    
    @Column
    private String name;
    
    @Column
    private String price;
    
    @Column
    private String image;
    
    @Column
    private String description;

    public int getId() {
        return id;
    }
//  public void setId(int id) {
//      this.id = id;
//  }

    public String getCategory() {
        return category;
    }
    public void setCategory(String category) {
        this.category = category;
    }

    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }

    
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }

    
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}

Here is my Repo


import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.winecoff.backend.models.Food;

@Repository
public interface FoodRepository extends JpaRepository<Food, Integer> {
    
    List<Food> findByName(String name); 
    List<Food> findByCategory(String category);
    
}

Here is my Controller

package com.winecoff.backend.controllers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.winecoff.backend.exceptions.ResourceNotFoundException;
import com.winecoff.backend.models.Food;
import com.winecoff.backend.repositories.FoodRepository;

@RestController
@CrossOrigin
@RequestMapping("/api/v1/")
public class FoodController {

    @Autowired
    private FoodRepository foodRepo; 
    
    
    // Read and return all food items
    @GetMapping("allfood")
    public List<Food> getAllFood(){
        return foodRepo.findAll(); 
    }
    
//  This is where I am having trouble
    @GetMapping("food/name")
    public List<Food> findAllByFoodName(String name) {
        return (List<Food>) foodRepo.findByName(name);
    }
    
    //Read and return all by category
    @GetMapping("food/category/{category}")
    public List<Food> findByCategory(@PathVariable String category){
        return (List<Food>) foodRepo.findByCategory(category); 
    }

    
//  Get food item by id
    @GetMapping("food/{id}")
    public ResponseEntity<Food> getFoodById(@PathVariable int id){
        Food food = foodRepo.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Food not found.")); 
        return ResponseEntity.ok(food); 
    }
    
    
//   Delete by id 
//  Question: Wont this change the whole menu and not whats just in the cart? 
    @DeleteMapping("food/{id}")
    public ResponseEntity<String> deleteFood(@PathVariable int id) {
            foodRepo.findById(id);
//              .orElseThrow(() -> new ResourceNotFoundException("Student not found."));
            
//          Delete method from jpa
            foodRepo.deleteById(id); 
            return new ResponseEntity<>("Food has been deleted", HttpStatus.OK); 
        }
    
//  add food to api
    @PostMapping("addfood")
    public Food newFood(@RequestBody Food food) {
        return foodRepo.save(food); 
    }
    
    
//  update food obj keys, such as name to the api
    @PutMapping("food/{id}")
    public ResponseEntity<Food> updateFood(@PathVariable int id, @RequestBody Food newFoodInfo){
        Food foundFood = foodRepo.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Food not found."));
        
        foundFood.setCategory(newFoodInfo.getCategory()); 
        foundFood.setName(newFoodInfo.getName()); 
        foundFood.setPrice(newFoodInfo.getPrice()); 
//      foundFood.setId(newFoodInfo.getId()); 
        
        Food updatedFood = foodRepo.save(foundFood);
        
        return ResponseEntity.ok(updatedFood);  
    }
    
}

CodePudding user response:

yes you can do custom query in your repo:

try

@Query(value="your query")
List<Food> getFoodByFilter(@Param("filter") String filter);

this page can help you: https://www.baeldung.com/spring-data-jpa-query

CodePudding user response:

You can use @Query annotation and write your own custom query.

 @Query("SELECT e FROM food e WHERE e.name = :name")
 List<Food> findByName(@Param("name") String name); 

or create a custom repository class implements from FoodRepository interface and create custom queries.

@PersistenceContext
private EntityManager entityManager;

@Override
public List<Food> findAllByFoodName(String name) {
        String query = String.format("SELECT * FROM food WHERE name = '%s' ", name);
        Query q = entityManager.createNativeQuery(query);
        List<Food> result = q.getResultList();
        return result;
    }
  • Related