【问题标题】:Can you use RequestFactory's .with() method with named queries?您可以将 RequestFactory 的 .with() 方法与命名查询一起使用吗?
【发布时间】:2013-07-14 17:31:36
【问题描述】:

我正在尝试使用带有 Hibernate/JPA 的 RequestFactory 来调用数据库,并且我想检索包含返回的嵌入式实体的实体列表。我知道 .with() 方法适用于 .find() 等方法,但它似乎不适用于自定义查询。

我目前的做法如下:

我在实体类中使用了一个命名查询来进行查询。 (Primary Entity是Name,Embedded entity是一个Suffix entity,叫做nameSuffix)

@NamedQueries({ @NamedQuery(name = "Query.name", query = "select * from NameTable") })

然后在服务类中,我想用RequestFactory调用的.list()方法如下。

public List<Name> list() {
    return emp.get().createNamedQuery("Query.name").getResultList();
}

最后,这就是我在客户端代码中进行调用的方式:

NameRequest context = requestFactory.createNameRequest();
context.list().with("nameSuffix").fire(new Receiver<List<NameProxy>>(){
    public void onSuccess(List<NameProxy> response) {
       String suff = response.get(0).getNameSuffix().getText();

    }
});

在上面的代码中,它表示 getNameSuffix() 返回 null,这意味着 .with("nameSuffix") 不适用于 .list() 调用,就像它在标准 .find() 方法中一样。

有没有一种方法可以使用.with() 构建一个返回实体列表及其嵌入实体的调用,或者我需要以其他方式吗?如果我需要用另一种方式来做,有没有人想出一个好的方法?

【问题讨论】:

    标签: sql gwt requestfactory


    【解决方案1】:

    我认为你误解了 with() 方法的用途,除非你有一个方法 getNameSuffix 返回 NameSuffixentity。这就是documentation 所说的:

    When querying the server, RequestFactory does not automatically populate relations in the object graph. To do this, use the with() method on a request and specify the related property name as a String

    因此,您必须传递给该方法的是您要检索的子实体的名称列表。我希望这个例子能有所帮助:

    class A {
       String getS(){return "s-a"}
       B getB(){return new B();}
    }
    class B {
       String getS(){return "s-b";}
       C getC(){return new C();}
    }
    class C {
       String getS(){return "s-c";}
    }
    
    context.getA().fire(new Receiver<A>(){
      public void onSuccess(A response) {
        // return 's-a'
        response.getS();
        // trhows a NPE
        response.getB().getS(); 
      }
    });
    context.getA().with("b").fire(new Receiver<A>(){
      public void onSuccess(A response) {
        // return 's-a'
        response.getS();
        // return 's-b'
        response.getB().getS(); 
        // trhows a NPE
        response.getB().getC().getS(); 
      }
    });
    context.getA().with("b.c").fire(new Receiver<A>(){
      public void onSuccess(A response) {
        // return 's-a'
        response.getS();
        // return 's-b'
        response.getB().getS(); 
        // return 's-c'
        response.getB().getC().getS(); 
      }
    });
    

    【讨论】:

    • 感谢您的回复,但不,我明白我正在向它发送名称。我对 .with() 的理解相对较好,并且可以很好地与 .find() 方法一起使用。我希望获得帮助的地方是能够在使用 NamedQueries 的调用上使用 .with(),这可能是不可能的。
    • 明白了。为什么不将命名查询作为远程方法的参数发送? rq.list("namedQuery")
    • 我不确定这有什么帮助。命名查询被调用得很好,但我没有在返回的实体中得到嵌入的实体。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2015-09-21
    • 2020-11-23
    • 1970-01-01
    • 2014-01-22
    相关资源
    最近更新 更多