问题
It can be an easy problem, I have a native query with hibernate in my managedbean, my goal is to show it in a datatable of primefaces implementation.
public List<User> retrieveAllUserName() {
Transaction tx = null;
Session session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
//Native Query
Query q = session.createSQLQuery("select name from user");
List<User> ls = q.list();
System.out.println("query executed");
for (int i = 0; i < ls.size(); i++) {
System.out.println("UserName:" + ls.get(i));
}
return ls;
}
In my View:
<h:form>
<p:dataTable var="car" value="#{userMBean.retrieveAllUserName()}">
<p:column>
<f:facet name="header">
Name
</f:facet>
<h:outputText value="#{car.name}" />
</p:column>
</p:dataTable>
</h:form>
However i get the error:
"#{car.name}": Property 'name' not found on type java.lang.String
Edit: In addition, the native query can be changed to send more than one column.
Thanks all.
回答1:
Try returning list of User
objects:
Query q = session.createSQLQuery("select firstname, lastname from user");
//when it's native query, returned list is a list of arrays, and each array is a row
List<Object[]> ls = (List<Object[]>) q.list();
//you should return list of User object from this method, so need to create one
List<User> users = new ArrayList<User>();
for (Object[] row : ls) { // go throw each row
User user = new User(); // instantiate a new User
user.setFirstName((String) row[0]); // set it's first name
user.setLastName((String) row[1]); // set it's last name
users.add(user); // add the User instances to the list "users"
}
return users; //return the list we created
In the above, you need to make some modification. Like in the query change the it have the actual column names in your table. And change the User
object creation and setting of props to conform to how your User
class is defined.
And then do something like this in the view:
<h:outputText value="#{car.firstName}" />
<h:outputText value="#{car.lastName}" />
回答2:
You can use HQL like this:
public List<User> retrieveAllUserName() {
Transaction tx = null;
Session session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
//Native Query
Query q = session.createQuery("from user");
List<User> ls = q.list();
System.out.println("query executed");
for (User u:ls) {
System.out.println("UserName:" + u.getName());
}
return ls;
}
来源:https://stackoverflow.com/questions/8597382/how-to-show-hibernate-query-result-in-primefaces-datatable