Daily photograph for 2008-07-10 - "world press photo exhibit 2008"

Today's photograph on my photoblog, "Photo-Persistence"

Hibernate: “No persister for” error

I’m pulling my hair out trying to fix this error. I’ve used the same technique, similar datatypes, similar mapping files…yet, when I try to map my Hibernate “Historical” data object class, I get a “No persister for” error. I’ve googled for solutions to this problem, but nothing has come up applicable to what I’m looking to fix. So, I’m turning to the blogosphere for help here.

In order to debug, I’ve created a servlet which attempts to write a data object (Historical) to MySQL. I do this twice, with the same code (copy & paste for this junk debug code). One method (writeDailysumsToDB) writes to a different data object, with similar types. The second method (writeHistoricalToDB) writes the Historical data object. writeDailysumsToDB works perfectly, yet writeHistoricalToDB fails with the mentioned “No persister for” error. This leads me to believe it’s a mapping error, yet I can’t detect where. So I’m dumping everything here in the hopes someone can browse and point out my obvious error.


—– Exception stacktrace —–

net.sf.hibernate.MappingException: No persister for: db.Historical
at net.sf.hibernate.impl.SessionFactoryImpl.getPersister(SessionFactoryImpl.java:420)
at net.sf.hibernate.impl.SessionImpl.getPersister(SessionImpl.java:2302)
at net.sf.hibernate.impl.SessionImpl.getPersister(SessionImpl.java:2309)
at net.sf.hibernate.impl.SessionImpl.save(SessionImpl.java:599)
at spike.WriteHistoricalServlet.writeHistoricalToDB(WriteHistoricalServlet.java:192)
at spike.WriteHistoricalServlet.handleRequest(WriteHistoricalServlet.java:126)
at org.apache.velocity.servlet.VelocityServlet.doRequest(VelocityServlet.java:372)
at org.apache.velocity.servlet.VelocityServlet.doGet(VelocityServlet.java:333)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:126)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:103)
at com.caucho.server.http.FilterChainServlet.doFilter(FilterChainServlet.java:96)
at com.caucho.server.http.Invocation.service(Invocation.java:315)
at com.caucho.server.http.CacheInvocation.service(CacheInvocation.java:135)
at com.caucho.server.http.HttpRequest.handleRequest(HttpRequest.java:246)
at com.caucho.server.http.HttpRequest.handleConnection(HttpRequest.java:164)
at com.caucho.server.TcpConnection.run(TcpConnection.java:139)
at java.lang.Thread.run(Thread.java:536)

—– hibernate mapping File —–

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 2.0//EN”
“http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd”>
<hibernate-mapping>
<class name=”db.Historical” table=”historical” >
<id name=”id” column=”id” type=”int” unsaved-value=”null”>
<generator class=”native”>
</generator>
</id>
<property name=”datelog” type=”java.util.Date” column=”datelog” not-null=”true”/>
<property name=”opened_this_day” type=”int” column=”open_this_day” not-null=”true”/>
<property name=”closed_this_day” type=”int” column=”closed_this_day” not-null=”true”/>
<property name=”open_all” type=”int” column=”open_all” not-null=”true”/>
</class>
</hibernate>

CREATE TABLE historical (
id bigint(5) unsigned NOT NULL auto_increment,
datelog date default ‘2001-01-01′,
opened_this_day bigint(5) unsigned default ‘0′,
closed_this_day bigint(5) unsigned default ‘0′,
open_all bigint(5) unsigned default ‘0′,
PRIMARY KEY (id)
) TYPE=ISAM;

——Data object——

public class Historical {

private int id;
private Date datelog;
private int opened_this_day;
private int closed_this_day;
private int open_all;

——method in servlet to write data Object——

private boolean writeHistoricalToDB ( Historical historical ) {
boolean result = true;
Transaction tx = null;
try {
SessionFactory sf = new Configuration().configure(”/config.cfg.xml”).buildSessionFactory();
Session sess = sf.openSession();
try {
tx = sess.beginTransaction();
sess.save(historical);
tx.commit();
} catch (HibernateException he) {
if (tx != null) tx.rollback();
result = false;
log.warn(”EXCEPTION: ” + he.getMessage(), he);
} finally {
sess.close();
}
} catch (HibernateException he) {
result = false;
log.warn(”EXCEPTION: ” + he.getMessage(), he);
}
return result;
}//writeHistoricalToDB

UPDATE: Matt Raible solved the problem for me (an hour after posting!). As I suspected, a stupid mistake…I forgot to add the .hbm.xml file to the cfg.xml file. Hopefully google will index and it’ll be a reference in case others have the same problem.

57 Responses to “Hibernate: “No persister for” error”

  1. Frank Merenda Says:

    oh man, believe it or not, I just had the same problem. I found your post, and realized that I also forgot to add my new .hbm.xml file to my application.

    Thanks!
    -Frank Merenda

  2. Andre Says:

    Thanks, this saved me a lot of time… haha

  3. Anonymous Says:

    google works, thx a log :-)

  4. Dave Butler Says:

    And thanks from me!

  5. B.Müller Says:

    Heya, well fortunately that fixes problem is at index #1 @ google :)

    Thx a lot…

  6. Ben Says:

    Thanks from here as well! All too much to take in…

  7. BenH Says:

    Me too…and it doesn’t appear in the Hibernate FAQ!

  8. martin marquez Says:

    I´m having the same exception, the problem is that i doesn´t have another .hbm.xml file to add because there is a class hierarchy of 4 classes with only 1 file, the idea is:
    class p;
    class t extends p;
    class c extends t;
    class l extends t;

    I can work fine with class p and class t but i cant work with classes c and l.

    Please if anybody can help me I would be very pleased.

  9. psiXaos Says:

    “Hopefully google will index and it’ll be a reference in case others have the same problem.”

    You rule! I had the same mistake, googled, found (#1st), solved! Tnx :)

  10. Robert J. Walker Says:

    Ditto above. Thanks to you and to Google.

  11. resistance to persistence » Blogging & Google - the ultimate problem solver Says:

    [...] the same problem.” Every few days I get comments added to the original post on the No persister for error saying that m [...]

  12. you r our savier Says:

    Google worked by indexing and thanks 2 u

  13. Isaac Hodnett Says:

    Google rocks!

  14. Hal Says:

    doesn’t fix my problem..I have three methods:
    public interface TransactionDAO extends DAO {
    public Transaction getTransaction(Long transId);
    public void saveTransaction(Transaction transaction);
    public void removeTransaction(Long transId);
    }

    all tests pass, except the remove method on the DAO. I don’t see the problem yet..

  15. Ruben Says:

    And thanks from me too! :)

  16. Ed Says:

    I STILL have that problem!
    I get this error:
    Exception in thread “main” net.sf.hibernate.QueryException: persister not found: test.hibernate.Product [SELECT product FROM products IN CLASS test.hibernate.Product WHERE products.name=test1]

    I have 1 table in a MySql database( table name = products) and 3 classes - a Product.class, InsertProduct.class, and FindProductByName.class.
    I can successfully insert into the database with InsertProduct.class, but CAN’T do a FindByProductName!!! grrrr..
    Is driving me nuts!!

    The code for FindByProductName.java:
    ======================================
    import java.util.List;
    import net.sf.hibernate.Hibernate;
    import net.sf.hibernate.Session;
    import net.sf.hibernate.SessionFactory;
    import net.sf.hibernate.cfg.Configuration;

    // Usage:
    // java FindProductByName <br /> public class FindProductByName {<br /> public static void main(String[] args) throws Exception {<br /> String query = “SELECT product ” +<br /> “FROM products IN CLASS test.hibernate.Product ” +<br /> “WHERE products.name=test1″;</p> <p> String name = args[0];</p> <p> Configuration cfg = new Configuration().addClass(Product.class);<br /> SessionFactory sf = cfg.buildSessionFactory();<br /> Session sess = sf.openSession();</p> <p> List list = sess.find(query, name, Hibernate.STRING);</p> <p> if (list.size() == 0) {<br /> System.out.println(”Product [" + name + "] not found!”);<br /> System.exit(0);<br /> }</p> <p> Product p = (Product) list.get(0);<br /> sess.close();<br /> System.out.println(”Found product: ” + p);<br /> }<br /> }</p> <p>==================================</p> <p>Any help/advice, and thanks!<br /> Ed

  17. Brian Says:

    God bless google and (your!) blogs!

    I’ve been racking my brains for hours on this problem and a quick search and finding your original blog has solved it for me!

    Many thanks!

    Bri…

  18. Thomas Says:

    Merry Christmas and Thanx for your blog !

    Stupid me … :o))

  19. John Says:

    Problem solved in under 2mins.

    Cheers

  20. Tiago Says:

    Goddammit, I had the same problem, and forgot to add the .hbm.xml to hibernate.cfg.xml too. Hahahaha…

  21. Jeremy Says:

    Just joining the fray of brainless developers who forgot to update their cfg files. I suppose we’re all walking around looking for our glasses when they’re right on the tops of our heads too…

    This doesn’t make us hibernate users look like a very smart bunch.

  22. Chris Mattison Says:

    I was reading this blog trying to resolve this same problem, except I am running my examples from my IDE (via a main, to test…)…the problem was essentially the same, I didn’t add all of the classes to my configuration, thanks to Ed; while reading his code –it hit like a lead pipe…

    It’s always the small stuff…

  23. Kamal Says:

    What if i didnt forget to add the hbm.xml and it still doesnt work ???

    Yep for me it still doesnt work but i am not using a hibernate.cfg.xml because i use springapp-context.xml spring framework. I have the same config somewhere else and the hbm files are still not found…

    :-(

  24. www.jorpes.com Says:

    King… Thx. I’m beginner at hibernate technology… So, your help was useful! ohh, ofcourse, it was so simple!!! Grrr

    When you come to sweden… come to se me on the track:-)

    /Jorpes

  25. nitin Says:

    I am not using the .cfg.xml. I am using hibernate.properties. So How to solve this problem in that case!!!

  26. neil Says:

    Well, I do have my hbm.xml in my cfg.xml, and I can insert data fine into that table/object. goes right into mysql fine. but, i get the “no persister” error message when i try and run a query using the class in question. anyone else have this?

  27. Wendy Says:

    Many thanks. I too was scratching my head. Google and this site saved the day.

  28. captaint Says:

    Aii! Thanks (add to the chorus). Solved my problem.

  29. billy perez Says:

    same problem, different solution.

    my mapping was added to my cfg file just fine. the problem was, the bean class name defined in the hbm file did not match the actual bean name because i forgot that i had renamed the javabean.

  30. yflag Says:

    Good! Thanks ! Solved my problem too.

  31. brice Says:

    right on man, right on!

  32. David Says:

    Sorry, gotta tough one!!!

    My “core.jar” file contains my backend database classes which includes my hibernate classes and mappings. Using this “core.jar”, I run JUnit tests that all pass with flying colors. I use this same jar within my WAR file and it is used by my servlet classes to get stuff done. When deploying the WAR into Tomcat (5.0.28) most all classes and mappings work really great.

    Ahhhh… but when attempting to persist my “User” object graph (which passed all JUnit tests above) from the servlet I get “net.sf.hibernate.MappingException: No persister for: java.lang.String”.

    The last thing in the hibernate debug logging statements is what looks like an attempt to save my mapped Set.

    Anyone have any guesses???

    Thanks in advance :-)

  33. David Says:

    Still stuck…. Arrrrrgggghhhh :-(

    I package all of my backend hibernate stuff into a “core.jar”. I have plenty of JUnit tests against all of my Hibernate DAO classes which all pass wonderfully against this core.jar file. This jar file is then deployed in a WAR file where my servlet classes use these DAOs to retrieve/persist my app stuff. This app is deployed in Tomcat (5.0.28) where most all of the mappings in my web app work wornderfully.

    Ahhhh….. This is where it all falls apart! When persisting a specific object graph, I get the following line in the stack trace:

    net.sf.hibernate.MappingException: No persister for: java.lang.String

    Any hiber-gurus out there have any ideas? (String?)

    If it helps… The last thing the Hibernate debug statements belched out were saving my Set collection that has a bi-directional mapping and is deployed using Hibernate 2.1.8.

  34. Chris Says:

    Yet another thankful soul

  35. Snehesh Says:

    Thanks,,it worked for me !!
    I did the same mistake.

  36. German Pizarro Says:

    I have a table which contains the IDs of other two tables
    (many-to-one and many-to-one relationship)

    When mapping with MyEclipse, the generated class for this table does not expose methods for setting data, instead it creates an additional class named with “Key” at the end (SeClaseorgxtiposeg.java ==> SeClaseorgxtiposegKey.java) which does expose the methods (setter and getters). However, can’t save this kind of object ’cause it has no .hbm.xml related, so it cannot be persisted.

    -Am I doing wrong when trying to save this kind of object (oSeClaseorgxtiposegKey)???

    -Should I create a .hbm.xml file for the oSeClaseorgxtiposegKey class and add it in the hibernate.cfg.xml??

  37. Creigh Says:

    I Didn’t forget to update .cfg. What i did do was put my new Object in a new package, changed all neccessary info in .hbm file to point to correct dbase table. Added new package name as a resource in .cfg file. Run a junit test, but alas …
    |——————|
    | any idea s? |
    |——————|
    /
    .
    /|\
    / \

  38. Creigh Says:

    Okay, i was shooting in the dark posting on to here ( desperation ) , but just for the sake of good form let me say that I’ve discovered that my web app runs perfectly when I jar it and deploy. It seems that when I use junit it struggles to see the .cfg file. I’m using :-
    Intellij
    tomcat 4.3
    struts & tiles
    Hibernate
    postgresql - I thought for a moment that it was a permissions problem (some tables owned by someone else) but I discounted(tested) that.
    Also I returned my new Object to the same package as all my other .java files. dont know if that made a difference. My thinking-intuition tells me I haven’t set Intellij properly somewhere to use copyed over(maybe from ant)conf files when running junit. I will check that too.
    . — Cheers
    /|\
    /\

  39. mbabauer Says:

    This didn’t help me directly, but it did put me on the right path. I am a JBoss user, and just switched to Hibernate for persistance. We deploy all this as a SAR file.

    Anyway, I forgot to add the hbm.xml to the MapResources attribute of my jboss-service.xml. Hope this helps any JBoss people out there that might run into the same problem.

  40. Brett Says:

    Thanks, solved my problem as well. Grrh!

  41. Dorival Afonso Cardozo Says:

    I solved this error putting the correct package in class name in file hbm.

    With Error: (file .hbm)

    WithOut error: (file .hbm)

    that’s all

  42. Anonymous Says:

    hi all,
    i was facing the same problem too.
    but in my case the mapping was thr in the cfg file.
    the problem as we had two vos for the same hbm files.
    it is silly mistake though.

    but still..

  43. Nary Says:

    I got the same error but the error message is a bit different. I get the message for java.lang.Boolean.

    Can someone advise what might have been the problem?

    Thanks
    Nary

  44. Nick Cotter Says:

    Hi

    I have also come across this error after changing the underlying table name in the database. I changed the hbm file and thought that would be fine. Indeed it was… except for one specific class.

    In that class it turned out there was native SQL going on all over the place, referencing the old table name - correcting this eliminated the error. Obvious really, but harder to spot!

    Cheers

    Nick

  45. guoke Says:

    well,I changed the directory of .cfg.xml,so the new .hbm is not add to it
    so stupid,hehe
    thanks a lot

  46. zaki Says:

    All you people are shit……………..are thr any real aExamples on thr

  47. caro Says:

    Thaaaaaaaaaaaaaaaaaaaaaaaaaanks!
    You save me!

  48. me Says:

    that worked, didn’t even know there was such a file, thanks for the time saver.

  49. ajay Says:

    hi, friend
    i have same problem No persister for class file at net.sf.hibernate.impl.SessionImpl.getPersister(SessionImpl.java:2302)
    i stuck at this stage so pls help me also
    ajay jain

  50. Gwizard Says:

    Thanks, It cost my firm a lot of cash until I found this solution

  51. upforever Says:

    I have a same problem No persister for: com.joyinter.avatar.emoticon.EmoticonSubject
    0.net.sf.hibernate.impl.SessionFactoryImpl.getPersister() (SessionFactoryImpl.java:line=344)
    1.net.sf.hibernate.impl.SessionImpl.getClassPersister() (SessionImpl.java:line=2656)
    2.net.sf.hibernate.impl.SessionImpl.getSQLLoadable() (SessionImpl.java:line=3775)
    3.net.sf.hibernate.impl.SessionImpl.findBySQL() (SessionImpl.java:line=3754)
    4.net.sf.hibernate.impl.SQLQueryImpl.list() (SQLQueryImpl.java:line=52)
    5.com.joyinter.avatar.emoticon.EmoticonSubjectUtil.genTreeFolder() (EmoticonSubjectUtil.java:line=278)
    6._emoticonsidebar__jsp._jspService() (_emoticonsidebar__jsp.java:line=40)
    7.com.caucho.jsp.JavaPage.service() (JavaPage.java:line=75)
    Somebody who can help me,my msn is up_zsm@hotmail.com

  52. vp Says:

    wow.. google kicks ass!! and thanks for posting it - you saved a lot of time for many people.

  53. Skybrite Says:

    Thaaaaank you so much. This idiotic programmer didn’t update the mapping file….then again that’s good, because now i’ll know the first thing to check if this happens again. Thanks again.

  54. Chaikou Says:

    Thank u guyz. 2007 next week and still having the same problem (since the first in 2004 !!!!!)

  55. jero0208 Says:

    believe it or not, I had the same problem.

    but I solve the problem after seen your post.

    Thanks!!

  56. Ignacio Says:

    A very simple mistake, yet this post saved me from wasting any more time on the debugger. Thanks! :-)

  57. aquadan Says:

    I got the same error, but it’s not the same reason. That’s why I add a comment.

    In my case, the Entity to persist (Element) contains a mapping to another entity (Specialization).

    In Element.java, I then have the methods (getter/setter):
    /**
    * Return the value associated with the column: SPEC_ID
    * not-null=true
    */
    public Specialisation getSpecialisation () {
    return this.specialisation;
    }

    /**
    * Set the value related to the column: SPEC_ID
    * @param specialisation the specialisation (Specialisation) value
    */
    public void setSpecialisation (Specialisation specialisation) {
    this.specialisation = specialisation;
    }

    The problem is that I also have a utility method:

    public boolean isSpecialisation() {
    return getSpecialisation != null;
    }

    Then when trying to fetch an Element, it seems that Hibernate uses the isSpecialisation accessor instead of the getSpecialisation one to get the field and then throws the Mapping exception!

    Hope this helps

Leave a Reply