【问题标题】:Tomcat + hibernate = no persistent classes found for query classTomcat + hibernate = 没有找到查询类的持久类
【发布时间】:2017-06-24 02:07:47
【问题描述】:

我正在开发一个 Web 应用程序并将其部署在 Tomcat 7.0 上。我的应用程序使用 MySQL 数据库。我已经配置了应用程序和数据库之间的连接,并希望添加 Hibernate 5.2.5 支持。我可以通过下面的配置通过 Hibernate 控制台与数据库通信,并且当我在非网络应用程序中使用它时它可以工作。问题仅在于我将其部署在服务器上时。我收到警告

no persistent classes found for query class: from entities.UserH

然后是它导致的500服务器错误。

我的实体类:

@Entity
@Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames =     {"id"})})
public class UserH {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, unique = true, length = 11)
    private int id;
    @Column(name = "login", nullable = false, length = 45)
    private String login;
    @Column(name = "name", nullable = false, length = 45)
    private String name;
    @Column(name = "surname", nullable = false, length = 45)
    private String surname;

    /* getters and setters*/
}

我的hibernate-annotation.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection properties - Driver, URL, user, password -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/web-database</property>
        <property name="hibernate.connection.username">username</property>
        <property name="hibernate.connection.password">password</property>

        <!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
        <property name="hibernate.current_session_context_class">thread</property>

        <!-- Mapping with model class containing annotations -->
        <mapping class="entities.UserH"/>
    </session-factory>
</hibernate-configuration>

应该获得用户的方法:

public List<UserH> getAllUsers() {

    try (Session session = HibernateUtils.getSessionAnnotationFactory().getCurrentSession()) {
        session.beginTransaction();
        Query<UserH> usersQuery = session.createQuery("from entities.UserH", UserH.class);
        List<UserH> usersList = usersQuery.getResultList();

        session.getTransaction().commit();

        return usersList;
    }
}

正如我所提到的 - 它适用于普通应用程序,但不适用于 Tomcat。我将所有可用元素添加到 Web 工件中,但没有帮助。我什至尝试使用 persistance.xml 添加 JPA 支持,但仍然没有成功。

还有什么问题?

编辑:我的 HibernateUtils 类:

public class HibernateUtils {
    private static SessionFactory sessionAnnotationFactory;

    private static SessionFactory buildSessionAnnotationFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration();
            configuration.configure("hibernate-annotation.cfg.xml");
            System.out.println("Hibernate Annotation Configuration loaded");

            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            System.out.println("Hibernate Annotation serviceRegistry created");

            SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

            return sessionFactory;
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionAnnotationFactory() {
        if (sessionAnnotationFactory == null) 
            sessionAnnotationFactory = buildSessionAnnotationFactory();
        return sessionAnnotationFactory;
    }
}

【问题讨论】:

  • 请附上您的HibernateUtils 课程代码。
  • @Naros,我编辑了我的帖子。

标签: java mysql hibernate tomcat


【解决方案1】:

也许这不是我的问题的正确答案,但这实际上对我有用。我用 JPA 配置 + hibernate 替换了 hibernate。

所以我没有使用hibernate-annotation.cfg.xml + Session,而是使用persistance.xml + EntityManager:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">

    <persistence-unit name="NewPersistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>entities.UserH</class>

        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/web-database"/>
            <property name="javax.persistence.jdbc.user" value="Admin"/>
            <property name="javax.persistence.jdbc.password" value="password2@"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>

</persistence>

getEntityManager:

public static EntityManager getEntityManager() {
    EntityManager entityManager = Persistence
            .createEntityManagerFactory("NewPersistenceUnit")
            .createEntityManager();

    return entityManager;
}

获取所有用户:

public List<UserH> getAllUsers() {

    EntityManager entityManager = HibernateUtils.getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    TypedQuery<UserH> usersQuery = entityManager.createQuery("from UserH ", UserH.class);
    List<UserH> usersList = usersQuery.getResultList();
    transaction.commit();
    entityManager.close();

    return usersList;
}

但是,我仍然不明白为什么这个配置有效,而单独的休眠却没有。任何 cmets/建议将不胜感激。

【讨论】:

    【解决方案2】:

    您应该将查询更改为仅引用类名:

    session.createQuery( "FROM UserH", UserH.class )
    

    只有当您将实体定义为内部类时,包才是重要的。

    对于这些情况,您需要使用完整的类名com.c.SomeOutterClass$MyEntity。另一种选择是更改 @Entity 注释,使其包含 name 属性,以便显式命名实体类:

    public class SomeOutterClass {
      @Entity(name = "MyEntity")
      public static class MyEntity {
    
      }
    }
    

    【讨论】:

    • 我的班级不是内部班级。当我从查询中删除包部分时,我收到错误:QuerySyntaxException: UserH is not mapped [from UserH]。即使我在 @Entity 注释中指定名称也会发生这种情况。
    猜你喜欢
    • 1970-01-01
    • 2014-04-02
    • 2017-10-11
    • 1970-01-01
    • 2021-10-21
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    相关资源
    最近更新 更多