Announcement Announcement Module
Collapse
No announcement yet.
Hibernate 3, Unknown entity Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Hibernate 3, Unknown entity

    Hi all,
    after trying a lot of hours without any result I hope that someone here is able to help.
    I would just like to make a really small Hibernate/Spring Example running in a TestCase but it allways stops with a hibernate.MappingException (Unknown entity) and I've got not only one idea left, where the problem is.

    My Spring Config file looks like this:

    Code:
    <!-- XML Schema-style -->
    <beans xmlns="http://www.springframework.org/schema/beans" 
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName">
       
        <bean id="dbTestService" 
              class="DbTestDao" 
              parent="hibernateDaoSupport"/>
       
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/test"/>
            <property name="username" value="root"/>
            <property name="password" value=""/>
        </bean>
        
     
     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
          <property name="dataSource">
             <ref bean="dataSource"/>
          </property>
          <property name="annotatedClasses">
             <list>
                <value>DbTest</value>
             </list>
          </property>
          <property name="hibernateProperties">
             <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
             </props>
          </property>
       </bean> 
        
          <!-- This is the base definition for all Hibernate based DAOs -->
        <bean id="hibernateDaoSupport" 
              class="org.springframework.orm.hibernate3.support.HibernateDaoSupport"
              abstract="true">
            <property name="sessionFactory">
                <ref bean="sessionFactory"/>
            </property>
        </bean>
    
    </beans>
    My Entity looks looks like this:
    Code:
    @Entity
    @Table(name="dbtest")
    public class DbTest {
    
        @Id
        @Column(name="id")
        private int id;
        
        @Column(name = "name")
        private String name;
    
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    Everything compiles, everything starts without complaints but allways I see this:

    Code:
    org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: DbTest; nested exception is org.hibernate.MappingException: Unknown entity: DbTest
    Caused by: org.hibernate.MappingException: Unknown entity: DbTest
    at ...
    No Nested Exception, and nothing else. But when I change the Spring config file to a class which not exists. Spring doesn't start because the annotated class was not found by Spring so that it seems that the Annotated Class has been registered by the AnnotationSessionFactoryBean. But why it doesn't work?

    This is my Test:

    Code:
    public class TestApp extends AbstractDependencyInjectionSpringContextTests {
        
        private DbTestService dbTestService;
        
        public void setDbTestService(DbTestService dbTestService) {
            this.dbTestService = dbTestService;
        }
    
        
        @Override
        protected String[] getConfigLocations() {
            return new String[]{"classpath:applicationContext.xml"};
        }
    
        public void testMyFirst() throws Exception {
            DbTest db = new DbTest();
            db.setName("huhu");
            dbTestService.save(db);
        }
    
    }
    TIA
    items

  • #2
    I've not yet used Hibernate annotations, but the error isn't annotations specific. Basically, Hibernate doesn't know how to map your class. When you use Hbm files, this could be that a file has been missed.

    In this example, it must be that Hibernate doesn't know how to map your class via annotations. I would suggest that there must be something wrong with the configuration. I would have a look at the annotations examples on the Hibernate website. Get that working then the integration with Spring should be simple.

    This talks about the same error, might be worth a look!
    http://www.hibernate.org/329.html
    Last edited by karldmoore; Dec 18th, 2006, 04:25 PM.

    Comment


    • #3
      This is an example from the javadoc. You haven't specified a package structure, is that correct?

      Code:
       <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
         <property name="dataSource">
           <ref bean="dataSource"/>
         </property>
         <property name="annotatedClasses">
           <list>
             <value>test.package.Foo</value>
             <value>test.package.Bar</value>
           </list>
         </property>
         <property name="annotatedPackages">
           <list>
             <value>test.package</value>
           </list>
         </property>
       </bean>
      http://www.springframework.org/docs/...ctoryBean.html

      Comment


      • #4
        Hi,
        thanks a lot. Finally I made it work, but I'm not quite sure why. It wasn't a problem not to mention the packages because in the working project I also don't describe them in the spring configuration file.

        After finishing my tests I will compare both projects to each other and I hope to find out why the problem in one project occurs.

        I like Spring and its conecept but sometimes, sorry that I have to say that, it is pain in the butt.

        bye
        items

        Comment


        • #5
          Glad its working. I would be interested to know what change actually fixed it!

          Comment


          • #6
            Hi again,
            solving this costs me about 10 years of my life :o|.

            In my Entity class I've written this:
            Code:
            @Entity
            @Table(name="dbtest")
            public class DbTest {
            ....
            And the import I made was this:
            Code:
            org.hibernate.annotations.Entity;
            After copying line after line of my applicationContext.xml from one project to another, I've also copied the Eclipse classpath files and anything else. The Object was still an "Unknown entity". But after changing the import to:
            import javax.persistence.Entity;
            it works immedeately and out of the box no matter what I've changed afterwards in my Spring configuration or classpath.

            Horrible and in my opinion far away from "easy to use". In my opinion it is still an interesting way to use Spring and Hibernate but small and working examples as well as a documentation reduced to the really necessary requirements would be really great.

            I was sure that it doesn't make any difference whether javax.pesistence Annotations or hibernate annotations are used but now it seems you're really in trouble if your decision is not the right one.

            A really exhausted bye
            from
            items

            Comment


            • #7
              First, glad its working!
              Second this is nothing to do with Spring, its Hibernate, and I agree this is very confusing.
              Third, the FAQ I posted yesterday had that error in it, thats why I posted it.

              I use @org.hibernate.annotations.Entity and get an Unknown entity exception
              Always import @javax.persistence.Entity

              @org.hibernate.annotations.Entity completes @javax.persistence.Entity but is not a replacement
              Anyway, its working .

              Comment


              • #8
                Hi karldmore,
                thanks a lot! Your hint was the right one and yes: It was my fault.

                bye
                items

                Comment


                • #9
                  Its not a question of fault, I think this problem is a really horrible one! You happen to have been bitten by it, atleast you solved it.

                  Good luck!

                  Comment


                  • #10
                    Hi again :o),
                    in my opinion it is really difficult to connect such complex technologies like Spring and Hibernate even if you are in the business for a long time.

                    In Germany we say "A lot of different roads are leading to Rome" and therefore it is a hard job to locate why an error occurs because often there is neither an Exception thrown nor a clear message in the logs. But for sure you are right that solving a problem also helps to learn a lot about a technology. But after spending hours and hours for a problem you sometimes would rather bang your head to the wall instead of thinking about a problem in a stoic or buddhistical way.

                    Using Spring and Hibernate (and all those other frameworks) doesn't solve all our technical problems though their marketing tries to make us believe that and encapsulating stuff like that also makes it more and more unknowable what reallly happens in the background if a curious problem comes up.

                    bye and best regards
                    items
                    (laid-back again after also solving Transactionproblems -> :o)

                    Comment


                    • #11
                      Originally posted by items View Post
                      in my opinion it is really difficult to connect such complex technologies like Spring and Hibernate even if you are in the business for a long time.
                      Personally, I don't think its that difficult, I do think however you just come across problems. Hopefully, gone are days of writing a new shiny framework for every project. That was much worse then learning Spring and Hibernate. Seen lots of companies go to the wall because of solving the wrong problems.

                      Originally posted by items View Post
                      Using Spring and Hibernate (and all those other frameworks) doesn't solve all our technical problems though their marketing tries to make us believe that and encapsulating stuff like that also makes it more and more unknowable what reallly happens in the background if a curious problem comes up.
                      They won't solve all your problems and they won't be suitable everytime, agreed! The issue here is though they are more suitable for lots of things, then a framework you haven't yet written.

                      I've participated in projects that re-invented the wheel, its no fun, its frustrating. You might think you would understand the code better, you might think you can do it better. I tend to think the frameworks out there e.g. Spring are more stable, better tested and better supported then my MooreUltimateFramework could ever be.

                      Given the choice I would sooner find a *good* framework off the shelf then build my own! Thats obviously until I write Struts3 or SpringReloaded "this time its autumn" .

                      Comment


                      • #12
                        Unknown Entity: exception for annotated entity

                        Hi
                        It does not work for me with LocalContainerEntityManagerFactoryBean!
                        But I use
                        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean">
                        <property name="dataSource" ref="dataSource"/>
                        <property name="jpaVendorAdapter">
                        <bean class="org.springframework.orm.jpa.vendor.Hibernat eJpaVendorAdapter">
                        <property name="databasePlatform"
                        value="org.hibernate.dialect.MySQL5Dialect"/>
                        <property name="generateDdl" value="true"/>
                        <property name="showSql" value="true" />
                        </bean>
                        </property>
                        </bean>

                        The annotation looks like this:

                        @Entity
                        public class Blah {

                        My persistence.xml looks like this:

                        <jar-file>file:C:/projects/hibernatejpa/webapp/WEB-INF/classes</jar-file>
                        <exclude-unlisted-classes>false</exclude-unlisted-classes>

                        The annotated class is correctly detected in the logs:
                        INFO: found EJB3 Entity bean: org.springframework.samples.petclinic.Manvita

                        The class looks like this (import javax.persistence.Entity:
                        @Entity
                        public class Manvita {


                        But the table is not created. What do I configure wrong? Spring? Persistence.xml?
                        Thanks.

                        Comment


                        • #13
                          Unknown entity:

                          hi All,

                          when i run the application given below, it says Unknow Entity.
                          PHP Code:
                          package com.spring.hibernate.basic;


                          import org.hibernate.Transaction;
                          import org.hibernate.cfg.*;
                          import org.hibernate.Session;
                          import org.hibernate.SessionFactory;
                          import org.hibernate.FlushMode;

                          public class 
                          HelloWorldTest {

                              public static 
                          void main(String args[])
                              {
                                  
                          Session session null;

                              try{
                                  
                          // This step will read hibernate.cfg.xml and prepare hibernate for use
                                  
                          SessionFactory sessions = new Configuration().configure().buildSessionFactory();
                                  
                                  
                          /* for hibernate.properties file use the below
                                  SessionFactory sessions = new Configuration()
                                                            .addClass(Message.class)
                                                            .setProperties(System.getProperties())
                                                            .buildSessionFactory(); 
                                  */
                                  
                                  
                                   
                          session =sessions.openSession();
                                  
                          // Transaction tx = session.beginTransaction();
                                      //Create new instance of Contact and set values in it by reading them from form object
                                       
                          System.out.println("Inserting Record");
                                      
                          Message message = new Message();
                                      
                          message.setText("abc");
                                      
                          session.save(message);
                                      
                          System.out.println(message.getId());
                                      
                          session.connection().setAutoCommit(true);
                                      
                          // session.setFlushMode(FlushMode.AUTO/ FlushMode.COMMIT/FlushMode.NEVER/FlushMode.ALWAYS);
                                  
                                      
                          session.flush();
                                      
                          session.close();
                                    
                          //  tx.commit();
                                       
                          System.out.println("Done");
                              }catch(
                          Exception e){
                                  
                          System.out.println(e.getMessage());
                              }
                              
                                  
                              }




                          message class:

                          PHP Code:
                          package com.spring.hibernate.basic;
                          /**
                           * 
                           * @hibernate.class
                           * table="MESSAGES"
                           *
                           */
                          public class Message {
                          private 
                          Long id;
                          private 
                          String text;

                          public 
                          Message()
                          {
                              }

                          /**
                           * 
                           * @hibernate.id
                           * generator-class="increment"
                           * column="MESSAGE_ID"
                           */

                          public Long getId() {
                              return 
                          id;
                          }
                          public 
                          void setId(Long id) {
                              
                          this.id id;
                          }


                          /**
                           * 
                           * @hibernate.property
                           */
                          public String getText() {
                              return 
                          text;
                          }
                          public 
                          void setText(String text) {
                              
                          this.text text;
                          }



                          Message.hbm.xml file:

                          PHP Code:


                          <?xml version="1.0" encoding="UTF-8"?>

                          <!DOCTYPE hibernate-mapping PUBLIC
                              "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
                              "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

                          <hibernate-mapping
                          >
                              <class
                                  name="com.spring.hibernate.basic.Message"
                                  table="MESSAGES"
                              >

                                  <id
                                      name="id"
                                      column="MESSAGE_ID"
                                      type="java.lang.Long"
                                  >
                                      <generator class="increment">
                                        <!--  
                                            To add non XDoclet generator parameters, create a file named 
                                            hibernate-generator-params-Message.xml 
                                            containing the additional parameters and place it in your merge dir. 
                                        --> 
                                      </generator>
                                  </id>

                                  <property
                                      name="text"
                                      type="java.lang.String"
                                      update="true"
                                      insert="true"
                                      column="text"
                                  />

                                  <!--
                                      To add non XDoclet property mappings, create a file named
                                          hibernate-properties-Message.xml
                                      containing the additional properties and place it in your merge dir.
                                  -->

                              </class>

                          </hibernate-mapping>
                          and spring.cfg.xml file:
                          PHP Code:
                          <?xml version="1.0" encoding="UTF-8"?>
                          <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

                          <!-- Generated file - Do not edit! -->

                          <hibernate-configuration>

                              <!-- a SessionFactory instance listed as /jndi/name -->
                              <session-factory>

                                  <!-- properties -->
                                  <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
                                  <property name="show_sql">false</property>
                                  <property name="use_outer_join">false</property>
                                      <property name="connection.username">CDO</property>
                                      <property name="connection.password">CDO</property>
                                      <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
                                      <property name="connection.url">jdbc:oracle:thin:@10.237.204.86:1521:CDOI1</property>
                                      <property name="hibernate.hbm2ddl.auto">update</property>
                                  <!-- mapping files -->
                                  <property name="cache.provider_class">
                                  org.hibernate.cache.OSCacheProvider
                                  </property>
                                  
                                  <mapping resource="com/spring/hibernate/basic/Message.hbm.xml"/>
                              </session-factory>

                          </hibernate-configuration>
                          i have created a table called:
                          PHP Code:
                          create table MESSAGES(MESSAGE_ID Longtext varchar2(20)) 
                          but when i run it says Unknown entity: com.spring.hibernate.basic.Message, why what is the reason?

                          Comment


                          • #14
                            I would presume that maybe the mapping file couldn't be found. I would have a look at the simple example in the Hibernate manual.
                            http://www.hibernate.org/hib_docs/v3...orial-firstapp

                            Comment


                            • #15
                              Hey thanks alot , replacing hibernate's entity with javax.persistence.entity really solved the problem

                              Comment

                              Working...
                              X