我有两个实体,Employee和publication:我想在一个数据表中显示出版标题,日期,它的作者存储在数据库中:这是我使用JPQL的查询:
private static EntityManager em;
private static EntityManagerFactory factory;
public PublicationDAO() {
if(factory==null)
factory=Persistence.createEntityManagerFactory("mavenTest");
if(em==null)
em=factory.createEntityManager();
}
public List<Object[]> getAllPublication() {
em.getTransaction().begin();
List<Object[]> pubs = em.createQuery("SELECT c.titrePublication, p.login FROM Publication c JOIN c.employee p ").getResultList();
em.getTransaction().commit();
return pubs;
}
所以我想在XHTML页面的数据表中显示这些信息
当前查询将返回Array,您需要的是一个Construct返回类型。
-
创建自定义类(这将是你的返回类型,它必须有构造函数,它接受你在查询字符串中定义的结果值。)
公共类publicationModel
{
public String publicationName;public String author;
public publicationModel (String publicationName, String author) { this.publicationName= publicationName; this.author= author; } }
使用typedQuery String queryStr ="SELECT NEW example. "publicationModel (c.titrePublication, p.login)" +"FROM Publication c JOIN c.employee p ";
TypedQuery =em.createQuery(queryStr, publicationModel .class);
List
results = query.getResultList();
我无法格式化答案。
我想知道你为什么把列表的类型设置为"对象数组"。将其呈现为实体类的类型就足够了:
public List<Publication> getAllPublication() {
...
List<Publication> pubs = ...
...
}
在表示层中指定一个managedBean类来完成这项工作:
@RequestScoped
@ManagedBean
public class PublicationBean {
// Inject your PublicationDAO here
private PublicationDAO publicationDao;
private List<Publication> publications;
@PostConstruct
public retrievePublications () {
try {
publications = publicationDao.getAllPublication();
} catch (Exception e) {
}
}
public List<Publication> getPublications() {
return this.publications;
}
public void setPublications(List<Publication> publications) {
this.publications= publications;
}
// getters/setters
}
然后,像这样显示<h:dataTable>
的数据:
<h:dataTable value="#{publicationBean.publications}" var="p" rules="all">
<h:column>
<f:facet name="header">Publication title</f:facet>
#{p.titrePublication}
</h:column>
<h:column>
<f:facet name="header">Publication author</f:facet>
#{p.employee.name}
</h:column>
</h:dataTable>
嗨,我终于找到解决方案了:正确的查询应该是:
List<Publication>=em.createQuery("select p from Publication p",Publication.Class).getResultList();
在托管bean中,我应该声明author,它是带有getter和setter的Employee实体。然后创建一个名为getAllpublications的方法:
public List<Publication> getAllpublications (){
publicationDao.getAllPublication();//this method is declared and specified in the DAO class
}
之后的XHTML页面应该看起来像:
<h:dataTable value="#{publicationBean.publications}" var="p" rules="all">
<h:column>
<f:facet name="header">Publication title</f:facet>
<h:outputText value="#{p.titrePublication}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">Publication author</f:facet>
<h:outputText value="#{p.employee.name}"></h:outputText>
</h:column>
</h:dataTable>
所以解决方案非常接近你的答案,Omar,非常感谢你的帮助。