Search code examples
springhibernatespring-data-jpajpqlfindby

JPA findBy(Property) return null


I have written JPA code in Spring boot where I want to perform CRUD and other operations on an Entity, I have written RecipeRepository that extends JpaRepository

public interface RecipeRepository extends  JpaRepository<Recipe,Long> {

  public List<Recipe> findByName(String name);

  public Recipe findOneByName(String name);
}

and Entity class is;

@Entity
@Table(name = "Recipe")
public class Recipe {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;

@Column(name = "name")
private String name;
..

} 

When I call the the recipeRepository.findByName("test") or recipeRepository.findOneByName("test"), I get null. When I call findAll() and then itreate over the values, I can find Recipe where name is test

String name = "test";

Recipe recipe = recipeRepository.findOneByName(name);

List<Recipe> recipeList = recipeRepository.findByName(name);

Iterable<Recipe> recipies = recipeRepository.findAll();
for(Recipe recipe : recipies){
    System.out.println(recipe.getName());
    // gets value of recipe where name is test
}

in the logs for the findByName or findOneByName, I get the following in logs:

select recipe0_.id as id1_0_, recipe0_.is_active as is_activ2_0_, recipe0_.is_injected as is_injec3_0_, recipe0_.name as name4_0_, recipe0_.rule as rule5_0_ from recipe recipe0_ where recipe0_.name=?


Solution

  • I was passing the wrong value of the param to my controller. Instead of: localhost:8080/recipe/test I was passing the value like name=test (localhost:8080/recipe/name=test).

    So it was passing the value of the name as "name=test" to recipeRepository.findByName() method instead of "test"