【问题标题】:Converter not found in Spring boot Jpa在 Spring Boot Jpa 中找不到转换器
【发布时间】:2018-07-05 18:48:57
【问题描述】:

我正在尝试接收来自 2 个不同表的信息,其中第三个表介于两者之间。比如说我们有一个这样的数据库结构 db structure

如您所见,foo_and_bar 表用于创建 foo 和 bar 之间的关系。现在我们可以说一个 foo 有许多条,其中 bar 是带有静态数据的静态表(将其视为 Player -> Items 关系和介于两者之间的 Inventory 表)。现在在 Java 中,代码如下所示: Foo实体 @实体 公共类 Foo {

@Id
private Long ID;

private String fooData;

@OneToMany(mappedBy = "foo")
private List<FooAndBar> fooAndBars;
//Getters and setters left out for convenience

}

酒吧实体 @实体 公共类酒吧 {

@Id
private Long ID;

private String BarData;

@OneToMany(mappedBy = "bar")
private List<FooAndBar> fooAndBars;

//Getters and setters left out for convenience
}

FooandBar 实体 公共类 FooAndBar {

@Id
private Long ID;

private String fooData;

@ManyToOne
@JoinColumn(name = "foo_id")
private Foo foo;

@ManyToOne
@JoinColumn(name = "bar_id")
private Bar bar;

//Getters and setters left out for convenience
}

现在假设我们要为一个 Foo 查找所有 Bars。为此,我们使用 1 个方法 findByFooId

创建一个 FooAndBarRepository
@RestController
public class FooAndBarRepo extends JpaRepository<FooAndBarRepo, Long>{
     List<Bar> findByFooId(Long id); 
}

并编写一个简单的控制器来发出这样的 GET 请求

@Autowired
FooAndBarRepo fooAndBarRepo;

@RequestMapping("/get_bars")
public String getBars(@RequestParam(value = "fooId") Long fooId){
    List<Bars> = fooAndBarRepo.findByFooId(fooId);
    return "success!";
}

现在假设我们的数据库中确实有这样的带有 fooId 的 foo,如果我们创建 /get_bars?fooId={validIdHere} 我们将得到一个像这样的 ConverterNotFoundExeption

No converter found capable of converting from type 
[FooAndBar] to type [Bar]

在我们的rest控制器的这行代码中抛出了错误

List<Bar> findByFooId(Long id); 

我做错了什么?为什么 spring 不能将 FooAndBar 转换为 Bar 实例?

编辑: 我试图手动将 Query 映射到我的 findByFooId 方法,像这样

@Query("select bar.id, bar.data from foo" +
       "left join fooandbar fb on foo.id = fb.foo_id" +
       "left join bar.id = fb.bar_id" +
       "where foo_id = :fooId")
List<Bar> findByFooId(@Param("fooId") Long id); 

查询有效,但现在我得到了

No converter found capable of converting from type 
[Integer] to type [Bar]

所以我收到了数据,如何将其转换为 Bar 类型的对象?

【问题讨论】:

  • 因为存储库是实体fooandbar,要么手动映射它,要么有两个存储库,它们之间有引用。
  • 你能说得更具体些吗?不太明白您所说的在它们之间有两个存储库是什么意思。谢谢!

标签: java spring hibernate spring-boot spring-data-jpa


【解决方案1】:

如果您想要一个返回List&lt;Bar&gt; 的方法,它应该在BarRepository 中。 FooAndBarRepository 用于返回 FooAndBars 的方法。

如果您希望 JPQL 查询返回 Bar 的实例,它应该选择 Bar,而不是 bar.idbar.data

所以,在BarRepository中使用那个方法:

@Query("select distinct bar from FooAndBar fb join fb.bar bar where fb.foo.id = :fooId")
List<Bar> findByFooId(@Param("fooId") Long fooId);

【讨论】:

    猜你喜欢
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 2017-01-21
    • 2019-03-06
    • 2019-03-25
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多