JPA findBy(Property)返回null

时间:2017-07-03 17:22:57

标签: spring hibernate spring-data-jpa jpql findby

我在Spring启动中编写了JPA代码,我想在Entity上执行CRUD和其他操作,我编写了扩展JpaRepository的RecipeRepository

public interface RecipeRepository extends  JpaRepository<Recipe,Long> {

  public List<Recipe> findByName(String name);

  public Recipe findOneByName(String name);
}

和实体类是;

@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;
..

} 

当我调用 recipeRepository.findByName(&#34; test&#34;) recipeRepository.findOneByName(&#34; test&#34;)时,我得到 null 。当我调用findAll()然后对值进行更新时,我可以找到名称为 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
}

在findByName或findOneByName的日志中,我在日志中得到以下内容:

  

选择recipe0_.id为id1_0_,recipe0_.is_active为is_activ2_0_,   recipe0_.is_injected为is_injec3_0_,recipe0_.name为name4_0_,   recipe0_.rule as recipe5_0_ from recipe recipe0_ where recipe0_.name =?

1 个答案:

答案 0 :(得分:0)

我将错误的参数值传递给了我的控制器。而不是: localhost:8080/recipe/test 我传递的值像 name=test (localhost:8080/recipe/name=test).

因此它将名称的值作为“name=test”传递给 recipeRepository.findByName() 方法而不是 "test"