Cannot create Typed Query for query with more than

2019-08-26 19:36发布

I'm trying to bind oracle result list to a summary list. But my summary list has 3 classes defined as entities of DB

I have three entity classes A, B, C

Summary.class
{
    @Autowired
    private A a;

    @Autowired
    private B b;

    @Autowired
    private C c;

    //getters and setters
}

@Enity
class A{
Fields 1..n ;
}  // same goes for other classes definition

I get the results with following query, but the results cannot be cast to the Summary object

List<Summary> summaryList = entityManager.createQuery("from A a, B b, C c" +
                " where a.field1 = b.field1 and a.fValue = :fValue " +
                "and b.field3= c.field3", Summary.class)
                .setParameter("fValue ", fValue )
                .getResultList();

Debugging: I made sure resultslist is not empty and below query works fine if I dont cast it to an object

List summaryList = entityManager.createQuery("from A a, B b, C c" +
                    " where a.field1 = b.field1 and a.fValue = :fValue " +
                    "and b.field3= c.field3")
                    .setParameter("fValue ", fValue )
                    .getResultList();

The alternative 1 I see is to iterate through summaryList and assign it them to individual lists like this, which I haven't tested yet but I think it might give a class cast exception since the casting dint work before

for (int i = 0; i < summaryList.size(); i++) {
   Summary s= (Summary) summaryList.get(i); // might be class cast Exception
   aList.add(s.getA());
   bList.add(s.getB());
}

The alternative 2 I'm thinking is to get only class A fields list from db cast it to A's List, do it 3 times brute force till I get all of them.

Below are some of questions I looked at before creating a new question

Uses a different class to combine multiple entity classes

gets a list back mapped to pojo

Please let me know your thoughts, I'm thinking my main approach is good way to do it if it works.

1条回答
迷人小祖宗
2楼-- · 2019-08-26 20:14

Your JPQL select statement "from A a, B b, C c" can not be mapped back to Summary entity, JPA does not have enough info to do that.

If in your logic, a summary instance can be composed from A, B, C then you can have a constructor like

public Summary(A a, B b, C c) {
       .............
}

and changed your select statment to be

"select new Summary(a, b, c) FROM A a, B b, C c"
查看更多
登录 后发表回答