我有这样的查询,如何从列表中获取我的实体类型?它像对象一样返回,但是当我投射到我的实体时,它不会投射。
我的表: 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?
Run Code Online (Sandbox Code Playgroud)
另外,这是进行查询的好方法吗?
小智 5
第一:你的结果“companyList”是什么样的List?从您的查询中您会得到一个列表列表,并且不得不说
companyList.get(i).get(0) // for name
companyList.get(i).get(1) // for location
Run Code Online (Sandbox Code Playgroud)
为了更容易使用,您还可以在开始时付出更多努力。然后你就可以拥有一个实用的、面向对象的结构。
为此,请使用一种 DTO(数据传输对象),其类可能如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以在你的查询中说:
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
Run Code Online (Sandbox Code Playgroud)
然后你可以说:
List<CompanyDTO> companyList = queryGetCompany.getResultList();
Run Code Online (Sandbox Code Playgroud)
然后通过以下方式获取所有名称和位置
for (CompanyDTO company : companyList){
System.out.print(company.getName() + ", ");
System.out.println(company.getLocation());
}
Run Code Online (Sandbox Code Playgroud)
或其他列表操作。您将从列表中获取每个 DTO,并可以调用这些对象的 get-Methods。
如果您选择多个值,您将得到一个列表。
请参阅 http://en.wikibooks.org/wiki/Java_Persistence/Querying#Query_Results
如果你想要这个对象然后使用,
select s from B b, A s where b.bPK.id_A=s.id_A and b.PK.id_C= :idEvent
Run Code Online (Sandbox Code Playgroud)
加入通常是通过关系完成的,
select s from A s join s.b b where b.PK.id_C= :idEvent
Run Code Online (Sandbox Code Playgroud)