简体   繁体   English

JPA命名查询:如何获取列列表

[英]Jpa named query: how to get a list of column

I have an entity orderdetails, where a user can have many ordernames I want to get all the ordername by userid using jpa named query. 我有一个实体orderdetails,其中用户可以有许多订单名称,我想使用jpa命名查询按用户ID获取所有订单名称。 I tried this 我试过了

SELECT o.orderName FROM OrderDetails o WHERE o.userId=:userId; 

Since the return type will be List in the resultset, I executed the query like this 由于返回类型将在结果集中为List,因此我像这样执行查询

getEntityManager().createNamedQuery("getOrderNamesByUserId", 
orderDetail.class).setParameter("userId", userId);

This obviously is not working. 这显然是行不通的。 How can I get that query working? 如何使该查询正常工作? One way is to iterate the List but I wonder whether there is another way around? 一种方法是迭代List,但我想知道是否还有另一种方法?

Well this is non-compiled code snippet, you could try the following approach. 好吧,这是未编译的代码片段,您可以尝试以下方法。

@Override
public List<OrderDetails> findOrders(Long userId) {
        TypedQuery<OrderDetails> query = entityManager.createNamedQuery(
                "OrderDetails.getOrderNamesByUserId", OrderDetails.class);
        query.setParameter("userId", userId);
        List<OrderDetails> list = query.getResultList();
        return list;
    }

If you just need to select one column(ordername), use getResultList() method. 如果只需要选择一列(订单名),请使用getResultList()方法。

    Query query = getEntityManager().createNamedQuery("getOrderNamesByUserId", OrderDetail.class);
    query.setParameter("userId", userId);
    List<String> orderNameList = query.getResultList();

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

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