【问题标题】:JPA findBy(Property) return nullJPA findBy(Property) 返回 null
【发布时间】:2017-07-03 17:22:57
【问题描述】:

我在 Spring boot 中编写了 JPA 代码,我想在其中对实体执行 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("test")recipeRepository.findOneByName("test") 时,我得到 null .当我调用 findAll() 然后对值进行迭代时,我可以找到名称为 test

的 Recipe
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 as is_injec3_0_, recipe0_.name as name4_0_, recipe0_.rule as rule5_0_ from recipe recipe0_ where recipe0_.name=?

【问题讨论】:

  • 你可以发布你的方法 findByName() 的实现吗?
  • 一些问题 - 在数据库中,测试前后是否有空格。你的数据库区分大小写吗?或不区分大小写。
  • 你能用 findByUsername 代替 findByName
  • @Prashant 感谢您指出这一点,我将错误的参数值传递给我的控制器...而不是:localhost:8080/recipe/test 我正在通过像name = test这样的值,那是在调试器中我无法拿起它的时候,因为它说name = test的值并且感到困惑。 localhost:8080/recipe/name=test
  • @here 你的Recipe类上有setter/getter方法吗,如果没有的话试试setter和getter方法

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 2017-05-08
    • 2016-09-07
    • 1970-01-01
    • 2019-03-31
    • 2015-05-08
    • 2018-02-05
    • 2020-02-25
    • 1970-01-01
    相关资源
    最近更新 更多