1

I met exception when using annotated joined subclass, i don't know how to correct it, please help.
Exception is: org.hibernate.MappingException: Unknown entity: B
Code:
Class A

@Entity
@Table(name="table_a")
@Inheritance(strategy=InheritanceType.JOINED)   
public class A {
    // uses composite key
    @Id
    @Column(name="sid")
    private String sid;

    @Id
    @Column(name="uid")
    private String uid;

    .....
}


Class B

@Entity
@Table(name="table_b")
public class B extends A {
    // inherited sid and uid from A
    @Id
    @Column(name="xid")
    private String xid;

    @Column(name="name")
    private String name;
    ......
}


Tables

create table_a(sid varchar, uid varchar);
create table_b(sid varchar, uid varchar, xid varchar, name varchar);


Hibernate.cfg.xml

<hibernate-configuration>
    <session-factory>
        .....
        <mapping class="A"/>
        <!-- no need to map B here, right?
        <mapping class="B"/>
        -->
        .....
    </session-factory>
</hibernate-configuration>


TestClass

public class HibernateTest {
    public static void main(String[] args) throws Exception {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        B temp = new B();
        temp.setSid(1);
        temp.setUid(2);
        temp.setXid(3);
        B target = session.get(B.class, temp);
        System.out.println("---------------" + target.getName());
        session.getTransaction().commit();
        session.close();
   }
}


Exception:

Exception in thread "main" org.hibernate.MappingException: Unknown entity: B
Perception
  • 79,279
  • 19
  • 185
  • 195
liuhebing
  • 13
  • 1
  • 3

1 Answers1

2

You have <mapping class="B"/> commented out with a question asking if it's needed. You need it.

Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199
  • 1
    but if I don't comment out B, there will be another exception:
    Caused by: java.lang.ClassCastException: org.hibernate.mapping.JoinedSubclass cannot be cast to org.hibernate.mapping.RootClass
    – liuhebing Jul 19 '11 at 04:00
  • 3
    @liuhebing: That's because you have it mapped wrong. You can't have an id property in B if it extends A, which already has an id. Also, you can't have two id's in A. Read up on [mapping id properties](http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-identifier) and on [mapping composite primary keys](http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e2177) with annotations. – Ryan Stewart Jul 19 '11 at 04:22
  • 1
    @liuhebing: On an unrelated note, all of the @Column annotations shown above are superfluous. Remove them all, and everything will work exactly the same. – Ryan Stewart Jul 19 '11 at 04:23