Spring Data-JPA多重嵌套对象

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

Spring Data- JPA multiple nested Object

问题

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

public class X {

@Id
private Long id;

//一对一映射
private Y y;

....更多属性

}

public class Y {

@Id
private Long id;

//多对一映射
private Z z;

....更多属性

}

public class Z {

@Id
private Long id;

....更多属性

}

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

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

}

我遇到了这个异常:

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

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

英文:

I have a class structure something like below:

public class X {

@Id
private Long id;

//One to one mapping
private Y y;

....Some more attibutes

}

public class Y {

@Id
private Long id;

//ManyToOne mapping
private Z z;

....Some more attibutes

}

public class Z {

@Id
private Long id;

....Some more attibutes

}

Now I have a Respository interface like below

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

}

I am getting this exception

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使用对象的完整路径。

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.

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; 注解。

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

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

英文:

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

 @Query(&quot;{$and : [{&#39;y.id&#39;: ?0}, {&#39;y.z.id&#39;: ?1 }]}&quot;)
 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:

确定