开发者

JPA multiple select query

I have a query like this, how can I get my entity type from the list? It is returning like object,but when I cast to my Entity it does not cast.

my tables: B(id_A, id_C) , A(id_A,name,location) C (id_C,......)

        String queryCompany = "select s.name,s.location from B b," +
                " A s where b.bPK.id_A=s.id_A " +
                "and b.PK.id_C= :idEvent";

        Query queryGetCompany = this.entityManager.createQuery(queryCompany);
        queryGetCompany.setParameter("idEvent"开发者_运维知识库,c.getID());

        List companyList = queryGetCompany.getResultList(); 
        //how can I get A.name A.location from this list?

Also, is this a good way to do my query ?


First: What kind of List is your result "companyList"? From your query you get a List of lists and would have to say

    companyList.get(i).get(0) // for name
    companyList.get(i).get(1) // for location

For easier use you might also put some more effort into it at the beginning. Then you can have a practical, object-orientated structure.

For this, use a kind of DTO (data transfer object) whose class might look like:

    class CompanyDTO{

      public CompanyDTO(String name, String location){
        this.name = name;
        this.location = location;
      }

      private String name;
      private String location;

      public String getName(){
        return this.name;
      }
      public String getLocation(){
        return this.location;
      }
    }

Then you can say in your query:

    select new CompanyDTO (s.name, s.location) 
    from B b, A s 
    where b.bPK.id_A = s.id_A and b.PK.id_C= :idEvent

Then you can say:

    List<CompanyDTO> companyList = queryGetCompany.getResultList();

and later get all names and locations by

    for (CompanyDTO company : companyList){
      System.out.print(company.getName() + ", ");
      System.out.println(company.getLocation());
    }

or other List-operations. You will get each DTO from the List and can call the get-Methods on these objects.


If you select multiple value you will get a List back.

See, http://en.wikibooks.org/wiki/Java_Persistence/Querying#Query_Results

If you want the object then use,

select s from B b, A s where b.bPK.id_A=s.id_A and b.PK.id_C= :idEvent

Also join are normally done through relationships,

select s from A s join s.b b where b.PK.id_C= :idEvent


It works for me.

IIRC, you can do a SELECT o1, o2, o3 FROM EntityA o1, EntityB o2, EntityC o3 WHERE ...., and the result will be a List<Object[3]>, where the array contents will contain the o1,o2,o3 values.

public List<Object[]> findXXX(final String param) {
    final TypedQuery<Object[]> query = this.em.createNamedQuery(
            "package.entity.function", Object[].class);
    query.setParameter("variable", variable);

    return query.getResultList();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜