Hiber Examples J SP
Hiber Examples J SP
Id;
public class UserDetail { @Entity public class UserDetails { @Id @GeneratedValue (strategy=GenerationType.AUTO) private int userId; private String userName;
public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } } Class Pokusaj to get the object: import java.util.List; import import import import org.hibernate.Query; org.hibernate.Session; org.hibernate.SessionFactory; org.hibernate.cfg.Configuration;
public class Pokusaj { Session session = null; public List getActorsByID(){ List<UserDetail> actorList = null; try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Query query = session.createQuery("from UserDetails"); query.setCacheable(true); actorList = query.list(); session.getTransaction().commit(); session.close();
1.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 2. <%@ page import="java.util.List"%> 3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 4. <%@ page import="net.artofz.hibernate.Pokusaj"%> 5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 6. <html> 7. <head> 8. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 9. <title>Insert title here</title> 10. </head> 11. <body> 12. 13. <% 14. Pokusaj pokusaj = new Pokusaj(); 15. List list = pokusaj.getActorsByID(); 16. request.setAttribute("database", list); 17. 18. %> 19. 20. <table border=1> 21. <c:forEach var="row" items="${database}"> 22. <tr> 23. <td><c:out value="${row.userId}"/></td> 24. <td><c:out value="${row.userName}"/></td> 25. </tr> 26. </c:forEach> 27. </table> 28. 29. </body> 30. </html>
Configuration class: <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">org.postgresql.Driver</property> <property name="connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property> <property name="connection.username">postgres</property> <property name="connection.password">9999</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <!-- Names the annotated entity class --> <mapping class="net.artofz.hibernate.UserDetail"/> </session-factory> </hibernate-configuration>
I have my entity class that I want to get data from UserDetails. I putt hibernate annotations in there. Then I made a Servlet BookListServlet with the following code in the doGet method:
view plaincopy to clipboardprint? Note: Text content in the code blocks is automatically word-wrapped
1. 2. 3. 4.
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 5. Session session = sessionFactory.openSession(); 6. session.beginTransaction(); 7. 8. try{ 9. Query query = session.createQuery("from UserDetails"); 10. List books = query.list(); 11. request.setAttribute("books", books);
In the servlet I execute the query and the result is put inside a list named books. The list was set in the request setAttribute. Close the session and redirect to booklist.jsp with the following code:
view plaincopy to clipboardprint? Note: Text content in the code blocks is automatically word-wrapped
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <table border="1"> <th>ID</th> <th>Name</th> <c:forEach var="book" items="${books}"> <tr> <td>${book.userId}</td> <td>${book.userName}</td> </tr> </c:forEach> </table> </body> </html>
List<Cars> list = query.list(); In the above line, you declare that your list is a list of Cars (which it is not) Iterator iter = list.iterator(); while (iter.hasNext()) { Object[] obj = (Object[]) iter.next();
Then you iterate on the list, and cast each element to Object[]. How could a Cars instance ever be an Object[]? The list should be declared as List<Object[]>, and you shouldn't use raw types. Your loop should be written as Iterator<Object[]> iter = list.iterator(); while (iter.hasNext()) { Object[] obj = iter.next(); Or, even simpler: for (Object[] obj : list) { Now, in the JSP, I suspect you're just using ${list} to display the list. This simply calls the toString() method on the list, which itself calls the toString() method of each element. Since each element is an Object[], the result string is [Ljava.lang.Object;@1f3b536, which means "array of Object with hashCode 1f3b536". To display the elements of the list, you should iterate over the list, as you must do it in the Java code: <c:forEach var="array" items="${list}"> Count: ${array[0]} - Color: <c:out value="${array[1]}"/> <br/> </c:forEach>
2down
vote
You need to determine the object type of every list item. It should be an existing model object (a Javabean like class with private properties and public getters). The ${item} in JSP would only display its Object#toString() outcome, something like com.packagename.ClassName@hashcode. Or if the toString() method is overridden, then you would see a "human friendly" string. Other way to reveal the type would then be debugging the getClass() of the list item: System.out.println(opdts.get(0).getClass().getName()); Once the type is known and the property names are known, then you can just access its properties in EL like ${item.someProperty}, ${item.otherProperty}, etcetera. Update: since the list seems to contain Object[] as every item (thus the list signature is actually List<Object[]>), here's how you could display it in JSP/JSTL: <table> <c:forEach items="${list}" var="objects"> <tr>
<c:forEach items="${objects}" var="object"> <td>${object}</td> </c:forEach> </tr> </c:forEach> </table> This does basically the same as following in "raw" Java: System.out.println("<table>"); for (Object[] objects : list) { System.out.println("<tr>"); for (Object object : objects) { System.out.println("<td>" + object + "</td>"); } System.out.println("</tr>"); } System.out.println("</table>");