简体   繁体   中英

HIbernate gives unknown entity exception

This is my model classes(AppInfo , Userinfo)

@Entity
@Table(appliesTo="appinfo")
public class AppInfo  {

    @Id
    @Column(name="appid")
    private int appId;

    @Column(name="appname")
    private String appName;

    @Column(name="roleid")
    private int roleId;

    @OneToMany(fetch=FetchType.LAZY,targetEntity=UserInfo.class,cascade=CascadeType.ALL)
    @JoinColumn(name="Appid",referencedColumnName="appid")
    private Set<UserInfo> userInfo;

        // setters & getters
}

@Entity
@Table(appliesTo = "userinfo")
public class UserInfo {

    @Id
    @Column(name = "userid")
    private int userId;

    @Column(name = "username")
    private String userName;

            @Column(name = "hoid")
            private String hoId;
//setters & getters
    }

My hbm config file

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/taskdb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping class="com.myproject.hibernate.model.UserInfo.java"></mapping>
        <mapping class="com.myproject.hibernate.model.AppInfo.java"></mapping>
    </session-factory>

My utility class

   public class UtilityAnnotation {


                private static final SessionFactory sessionFactory = buildSessionFactory();

                @SuppressWarning

s("deprecation")
            private static SessionFactory buildSessionFactory() {
                try {
                    // Create the SessionFactory from hibernate.cfg.xml
                    return new AnnotationConfiguration().configure().buildSessionFactory();
                } catch (Throwable ex) {
                    // Make sure you log the exception, as it might be swallowed
                    System.err.println("Initial SessionFactory creation failed." + ex);
                    throw new ExceptionInInitializerError(ex);
                }
            }

            public static SessionFactory getSessionFactory() {
                return sessionFactory;
            }

            public static void shutdown() {
                // Close caches and connection pools
                getSessionFactory().close();
            }

    }

And finally main class

public class OneToMany {

    public static void main(String[] args) {
        Session session = UtilityAnnotation.getSessionFactory().openSession();
        session.beginTransaction();
        UserInfo info = new UserInfo();
        AppInfo ap = new AppInfo();

        ap.setAppId(1);
        ap.setAppName("Check");
        ap.setRoleId(1);

        info.setUserName("Grey");
        info.setUserId(4);
        info.setHoneyId("4");

        Set<UserInfo> mys = new HashSet<UserInfo>();
        mys.add(info);

        ap.setUserInfo(mys);

        session.save(ap);
        session.getTransaction().commit();
        session.close();
    }
}

when I run the main class Iget following error

Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.myproject.hibernate.model.AppInfo
    at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:693)
    at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1485)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:120)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
    at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
    at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
    at com.myproject.hibernate.practice.OneToMany.main(OneToMany.java:32)

I searched for solution and in many have told to change the config file mapping where class path should be correct but I have given the right class path so whats the mistake I am making here.

I also have a separate main class which adds info into userinfo and that works perfectly.

If you want to add your entities using annotation, you need to add your annotated entities in the configuration object

new AnnotationConfiguration().configure().addAnnotatedClass(AppInfo.class).addAnnotatedClass(UserInfo.class).buildSessionFactory();

also remove .java from the mapping class xml configuration if you are using xml configuration

Replace

    <mapping class="com.myproject.hibernate.model.UserInfo.java"></mapping>
    <mapping class="com.myproject.hibernate.model.AppInfo.java"></mapping>

with

    <mapping class="com.myproject.hibernate.model.UserInfo"/>
    <mapping class="com.myproject.hibernate.model.AppInfo"/>

Use Java to include Entity instead of xml, it's more maintainable and readable for fellow developers.

Current exception is due to .java in the mapping class xml configuration

If you want to add your entities using annotation, prefer to add your annotated entities in the configuration object

    new AnnotationConfiguration().configure().addAnnotatedClass(AppInfo.class).addAnnotatedClass(UserInfo.class).buildSessionFactory();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM