Sunday, June 10, 2012

Pull Most Recent Entry in a Table Using Hibernate

I have a table called 'codesnipets' which has fields that make up a sort of pastebin thing. After posting a new code snipet, I want to show that snipet post immediately. So I simply want to pull the latest record from the table. I can to this two ways: selecting the highest ID in the table (where ID is primary key, integer, auto-inc...) or I could select by the most recent date. My ID name is "idcodesnipets", which is, again, the name of the variable in my bean, NOT the actual name of my table field.

So by ID, one way is with criteria:


 <%
        // Begin transaction as normal
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        s.beginTransaction();

        CodeSnipet snipet = new CodeSnipet(); // new object holder

        Criteria c = s.createCriteria(CodeSnipet.class);
        c.addOrder(Order.asc("idcodesnipets")).setMaxResults(1); //only want one.
        List l = c.list();
        snipet = (CodeSnipet)l.get(0); // just want the first one in the list
      
        %>
        <p>Here is a snipet:</p>
        <p>Title:
            <% out.println(snipet.getCodetitle()); %>
            </p>
        <p>File Name:
            <% out.println(snipet.getCodefilename()); %>
            </p>
        <p>Code:
            <% out.println(snipet.getCodetext()); %>
            </p>


Imports:

<%@page import="java.util.List"%>
<%@page import="org.hibernate.criterion.Order"%>
<%@page import="org.hibernate.Criteria"%>



By the way, I had the wrong dialect set from some stupid copy pasta, so if you get a 'SQL Grammar Error', check that if you are using MySQL you have this:

hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect


Set as your dialect in your hibernate config file. So it will look like:


<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

No comments:

Post a Comment