简体   繁体   English

spring-data-jdbc:包含具有 1-n 关系的实体的查询

[英]spring-data-jdbc: query containing entity with a 1-n relation

How can I write Queries for entities containing a 1-n reference?如何为包含 1-n 引用的实体编写查询?

Based on the spring-data-jdbc examples I will explain it with the following unit-test:基于spring-data-jdbc示例,我将使用以下单元测试对其进行解释:

@Test
public void customQuery_ReferenceMultipleInstances() {
  // prepare
  LegoSet smallCar = createLegoSet("Small Car 01", 5, 12);
  smallCar.setManual(new Manual("Just put all the pieces together in the right order", "Jens Schauder"));
  smallCar.addModel("suv", "SUV with sliding doors.");
  smallCar.addModel("roadster", "Slick red roadster.");
  repository.save(smallCar);

  // execute
  List<LegoSet> actual = repository.findByName("Small Car 01");
  Iterable<LegoSet> compare = repository.findAll();

  // verify
  assertThat(actual).as("same number of lego sets").hasSize(Lists.newArrayList(compare).size());
  assertThat(actual.get(0).getModels()).as("same number of models").hasSize(Lists.newArrayList(compare).get(0).getModels().size());
  assertThat(actual.get(0).getModels().get(0)).as("model must not be null").isNotNull();
  assertThat(actual.get(0).getModels().get(0).getName()).as("model must have a name").isNotEmpty();
}

This models a LegoSet referencing 2 Model s.这模拟了一个引用 2 个ModelLegoSet The repository.findByName() is annotated with a custom query; repository.findByName()用自定义查询注释; the repository.findAll() is the standard spring-boot-data method of the CrudRepository (just as reference). repository.findAll()CrudRepository的标准 spring-boot-data 方法(仅供参考)。

The custom query in version 1:版本 1 中的自定义查询:

@Query("SELECT ls.id, ls.name, ls.min_age, ls.max_age, " +
      "h.handbuch_id AS manual_handbuch_id, h.author AS manual_author, h.text AS manual_text " +
      "FROM lego_set ls JOIN handbuch h ON ls.id = h.handbuch_id " +
      "WHERE name = :name")
List<LegoSet> findByName(@Param("name") String name);

In this version the test fails w/在此版本中,测试失败 w/

java.lang.AssertionError: [model must not be null] 
Expecting actual not to be null

Okay, after that I add another JOIN to model :好的,之后我将另一个JOIN添加到model中:

@Query("SELECT ls.id, ls.name, ls.min_age, ls.max_age, " +
      "h.handbuch_id AS manual_handbuch_id, h.author AS manual_author, h.text AS manual_text, " +
      "m.* " +
      "FROM lego_set ls JOIN handbuch h ON ls.id = h.handbuch_id " +
      "JOIN model m ON ls.id = m.lego_set " +
      "WHERE name = :name")
List<LegoSet> findByName(@Param("name") String name);

Now the test fails w/现在测试失败了/

java.lang.AssertionError: [same number of lego sets] 
Expected size:<1> but was:<2> in:
<[LegoSet(id=1, name=Small Car 01, minimumAge=P5Y, maximumAge=P12Y, manual=Manual(id=1, author=Jens Schauder                                                                                       , text=Just put all the pieces together in the right order), models={suv=Model(name=suv, description=SUV with sliding doors.), roadster=Model(name=roadster, description=Slick red roadster.)}),
    LegoSet(id=1, name=Small Car 01, minimumAge=P5Y, maximumAge=P12Y, manual=Manual(id=1, author=Jens Schauder  

So how do I have to write that query correctly?那么我该如何正确编写该查询呢?

The first query is actually the correct one and it is working fine.第一个查询实际上是正确的,并且工作正常。

The problem is in your test.问题出在你的测试中。 models is a Map , but you treat it like a List which compiles because a list index is also a valid map key. models是一个Map ,但是你把它当作一个List来编译,因为列表索引也是一个有效的映射键。

If you change the last two assertions in your test like this they will succeed:如果您像这样更改测试中的最后两个断言,它们将会成功:

assertThat(actual.get(0).getModels().get("suv")).as("model must not be null").isNotNull();
assertThat(actual.get(0).getModels().get("suv").getName()).as("model must have a name").isNotEmpty();
// ----------------------------------------^

An alternative is to use the second query but with a custom ResultSetExtractor to collect multiple rows for the multiple models into a single LegoSet .另一种方法是使用第二个查询,但使用自定义ResultSetExtractor将多个模型的多行收集到单个LegoSet中。

I'm in a similar situation, but i don't see what is different in my situation.我处于类似情况,但我看不出我的情况有什么不同。

I have three models: Client: id, name.. Project: id, name, clientId, List ProjectMember我有三个模型: Client: id, name.. Project: id, name, clientId, List ProjectMember

Here is my had coded query这是我的编码查询

  @Query("""
       select
          project.id,
          project.legacy_id,
          project.code,
          project.client_id,
          project.is_archived,
          project.name,
          project.budget_type,
          project.hours_budget_max,
          project.money_budget_max
       from project
       join client on client.id = project.client_id
       where client.name ilike '%:name%'
      """)
  List<Project> findByClientNameContainingIgnoreCase(final String name);

As you can see i'm looking for project where client name (using a join) match a pattern.如您所见,我正在寻找客户名称(使用连接)匹配模式的项目。

Executing the request by hand give me the expected results.手动执行请求会给我预期的结果。 But going through spring data jdbc give me no results但是通过 spring data jdbc 没有给我任何结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM