Spring Data-JPA多重嵌套对象

huangapple go评论91阅读模式
英文:

Spring Data- JPA multiple nested Object

问题

我有一个类结构,类似于以下内容:

  1. public class X {
  2. @Id
  3. private Long id;
  4. //一对一映射
  5. private Y y;
  6. ....更多属性
  7. }
  8. public class Y {
  9. @Id
  10. private Long id;
  11. //多对一映射
  12. private Z z;
  13. ....更多属性
  14. }
  15. public class Z {
  16. @Id
  17. private Long id;
  18. ....更多属性
  19. }

现在我有一个如下所示的Repository接口:

  1. public interface XRepository extends JPARepository<X, Long> {
  2. // 这个不起作用
  3. public X findByIdAndYIdAndZId(Long xId, Long yId, Long zId);
  4. // 这个也因为上面的原因而无法工作
  5. public X findYIdAndZId(Long yId, Long zId);
  6. }

我遇到了这个异常:

  1. org.springframework.data.mapping.PropertyReferenceException: No property zId found for type X!

请帮我构建适用于这种情况的方法。

英文:

I have a class structure something like below:

  1. public class X {
  2. @Id
  3. private Long id;
  4. //One to one mapping
  5. private Y y;
  6. ....Some more attibutes
  7. }
  8. public class Y {
  9. @Id
  10. private Long id;
  11. //ManyToOne mapping
  12. private Z z;
  13. ....Some more attibutes
  14. }
  15. public class Z {
  16. @Id
  17. private Long id;
  18. ....Some more attibutes
  19. }

Now I have a Respository interface like below

  1. public interface XRepository extends JPARepository&lt;X, Long&gt; {
  2. // This is not working,
  3. public X findByIdAndYIdAndZId(Long xId, Long yId, Long zId);
  4. //This also doesn&#39;t work obviously for same reason as above one
  5. public X findYIdAndZId(Long yId, Long zId);
  6. }

I am getting this exception

  1. org.springframework.data.mapping.PropertyReferenceException: No property zId found for type X!

Please help me on how to construct the method for such scenario

答案1

得分: 4

Z字段在X中不存在,它在Y类中。因此,您应该为Zid使用对象的完整路径。

  1. public X findByIdAndYIdAndYZId(Long xId, Long yId, Long zId);

注: 请考虑为类使用可理解的名称。我猜它们仅为示例。

英文:

The field Z does not exist in X, it is in Y class. So, you should use the full path of the object for Z's id.

  1. public X findByIdAndYIdAndYZId(Long xId, Long yId, Long zId);

Note: Please consider to use the understandable name for the class. I guess they are for example only.

答案2

得分: 0

你可以使用 import org.springframework.data.mongodb.repository.Query; 注解。

  1. @Query("{$and : [{'y.id': ?0}, {'y.z.id': ?1 }]}")
  2. public X findByIdAndYIdAndZId(Long yId, Long zId);

你可以在 Query 中获得更多的信息。

英文:

You can use import org.springframework.data.mongodb.repository.Query; annotation.

  1. @Query(&quot;{$and : [{&#39;y.id&#39;: ?0}, {&#39;y.z.id&#39;: ?1 }]}&quot;)
  2. public X findByIdAndYIdAndZId(Long yId, Long zId);

You will get more idea about Query

huangapple
  • 本文由 发表于 2020年9月1日 13:33:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63681905.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定