当前位置: 首页 > 知识库问答 >
问题:

Hibernate发生断言失败(这可能表明Hibernate中存在错误,但更可能是由于会话的不安全使用)

蓬弘
2023-03-14

我刚从Hibernate4.X)更改为hibernate 5.0,我相应地更改了配置文件,但我遇到了一个奇怪的错误。

出现断言失败(这可能表明Hibernate中有错误,但更有可能是由于会话的不安全使用):org . Hibernate . assertion failure:Table x _ database。找不到用户

我希望你能帮忙。

下面您可以看到我的会话文件和XML配置文件。

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQLDialect
        </property>

        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

        <!-- Connects to the localhost database. This is for development purposes only. !-->
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/x_database</property>
        <!-- Should the system flush the database before running or only update the database? !-->
        <property name="hbm2ddl.auto">
            create
        </property>

        <property name="hibernate.connection.username">
            root
        </property>

        <property name="hibernate.connection.password">
            root
        </property>

        <mapping class="org.hva.folivora.model.user.UserEntity"></mapping>
        <mapping class="org.hva.folivora.model.user.ParentEntity"></mapping>
        <mapping class="org.hva.folivora.model.user.StudentEntity"></mapping>
        <mapping class="org.hva.folivora.model.questionanswer.QuestionEntity"></mapping>
        <mapping class="org.hva.folivora.model.global.GroupEntity"></mapping>
        <mapping class="org.hva.folivora.model.global.ThemeEntity"></mapping>

    </session-factory>

</hibernate-configuration>

在我的会话工厂下面。

    public class Database {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
            Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();
            return metadata.getSessionFactoryBuilder().build();
        } 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 Session getSession() {

        return getSessionFactory().openSession();
    }

    public static void main(final String[] args) throws Exception {
        final org.hibernate.Session session = getSession();
        try {
            System.out.println("querying all the managed entities...");
            final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
            for (Object key : metadataMap.keySet()) {
                final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
                final String entityName = classMetadata.getEntityName();
                final Query query = session.createQuery("from " + entityName);
                System.out.println("executing: " + query.getQueryString());
                for (Object o : query.list()) {
                    System.out.println("  " + o);
                }
            }
        } finally {
            session.close();
        }

    }
}

下面是完整的堆栈跟踪。

                01-May-2016 18:18:08.136 SEVERE [http-nio-8079-exec-4] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [IJBurg API/BACKEND] in context with path [] threw exception [org.glassfish.jersey.server.ContainerException: java.lang.ExceptionInInitializerError] with root cause
 org.hibernate.AssertionFailure: Table pad_ijburg.User not found
    at org.hibernate.persister.entity.AbstractEntityPersister.getTableId(AbstractEntityPersister.java:5139)
    at org.hibernate.persister.entity.JoinedSubclassEntityPersister.<init>(JoinedSubclassEntityPersister.java:433)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:344)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
    at org.hva.folivora.Database.buildSessionFactory(Database.java:26)
    at org.hva.folivora.Database.<clinit>(Database.java:19)
    at org.hva.folivora.MyResource.getIt(MyResource.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:317)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:298)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1096)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:760)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1480)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

我的会话工厂

   package org.hva.folivora;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.metadata.ClassMetadata;

import java.util.Map;

public class Database {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
            Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();
            return metadata.getSessionFactoryBuilder().build();
        } 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 Session getSession() {

        return getSessionFactory().openSession();
    }

    public static void main(final String[] args) throws Exception {
        final org.hibernate.Session session = getSession();
        try {
            System.out.println("querying all the managed entities...");
            final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
            for (Object key : metadataMap.keySet()) {
                final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
                final String entityName = classMetadata.getEntityName();
                final Query query = session.createQuery("from " + entityName);
                System.out.println("executing: " + query.getQueryString());
                for (Object o : query.list()) {
                    System.out.println("  " + o);
                }
            }
        } finally {
            session.close();
        }

    }
}

package org.hva.folivora.model.user;

import javax.jws.soap.SOAPBinding;
import javax.persistence.*;

@Entity
@Table(name = "User", schema = "pad_ijburg")
@Inheritance(strategy = InheritanceType.JOINED)
public class UserEntity {
    private int idUser;
    private String email;
    private String firstName;
    private String lastName;
    private String password;
    private Boolean admin = false;
    private Boolean teacher = false;

    public UserEntity(){

    }

    public UserEntity(String email, String firstName, String lastName, String password, Boolean admin, Boolean teacher){
        this.email = email;
        this.firstName = firstName;
        this.lastName = lastName;
        this.password = password;
        this.admin = admin;
        this.teacher = teacher;
    }

    @Basic
    @Column(name = "teacher")
    public Boolean getTeacher() {
        return teacher;
    }

    public void setTeacher(Boolean teacher) {
        this.teacher = teacher;
    }

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idUser", nullable = false, updatable = false, unique = true)
    public int getIdUser() {
        return idUser;
    }

    public void setIdUser(int idUser) {
        this.idUser = idUser;
    }

    @Basic
    @Column(name = "email", unique = true, nullable = false)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Basic
    @Column(name = "firstName")
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Basic
    @Column(name = "lastName")
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Basic
    @Column(name = "password")
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Basic
    @Column(name = "admin")
    public Boolean getAdmin() {
        return admin;
    }

    public void setAdmin(Boolean admin) {
        this.admin = admin;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        UserEntity that = (UserEntity) o;

        if (idUser != that.idUser) return false;
        if (email != null ? !email.equals(that.email) : that.email != null) return false;
        if (firstName != null ? !firstName.equals(that.firstName) : that.firstName != null) return false;
        if (lastName != null ? !lastName.equals(that.lastName) : that.lastName != null) return false;
        if (password != null ? !password.equals(that.password) : that.password != null) return false;
        if (admin != null ? !admin.equals(that.admin) : that.admin != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = idUser;
        result = 31 * result + (email != null ? email.hashCode() : 0);
        result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
        result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
        result = 31 * result + (password != null ? password.hashCode() : 0);
        result = 31 * result + (admin != null ? admin.hashCode() : 0);
        return result;
    }
}

共有3个答案

况弘新
2023-03-14

首先,< code>USER是MySQL中的保留关键字。这可能是问题的一个原因。请使用复数名称

@Table(name = "users", schema = "pad_ijburg")
public class User {

}

您需要在数据库中有pad_ijburg模式。如果您不这样做,则需要使用hibernate.hbm2ddl.auto=update更新或创建模式。

下一次,启用SQL日志并使用Hibernate引导提供日志。Hibernate提供了关于创建表的SQL的信息。

海保臣
2023-03-14

降级到Hibernate 4.1-FINAL,它应该会再次工作。显然Hibernate 5仍然有很多麻烦…(或者他们完全删除了加入的策略)很难过…

谈灵均
2023-03-14

这似乎与@继承有关。当我删除继承连接类型时,它将工作。我仍然无法继续,因为我仍然需要加入继承。

 类似资料:
  • 问题内容: 我们的项目使用Hibernate的程序来设置我们的SessionFactory等。我只是将我们从Hibernate的版本3迁移到了版本4。现在,我收到错误消息“必须声明元素类型“ hibernate-mapping”。它说是SaxParseException。很好,一切都很好,但是我检查了WEB-INF / lib目录,并找到了Hibernate的版本4核心.jar文件,因此它位于类路

  • 我们的项目使用Hibernate的编程配置来设置SessionFactory等。我刚刚将我们从Hibernate的版本3迁移到了版本4。现在我得到了一个错误“Element type”hibernate mapping“必须声明”它说这是一个SaxParseException。这很好,但我检查了我的WEB-INF/lib目录和Hibernate的版本4核心。jar文件在那里,所以它在类路径上。 起

  • 我需要从遗留系统进行数据迁移,总共有20,000条记录[所有数据将由csv文件提供],由于一些技术原因,我必须使用JPA/Hibernate将这些数据导入到您当前使用的新系统中。 当我进行导入时,总是遇到如下交易问题: 数据库是 MS SQL Server 2005 org . hibernate . assertion failure:< code > xxxx 条目中的id为空(发生异常后不要

  • 问题内容: 在配置hibernate.cfg.xml中,我添加 Hibernate并在运行应用程序时自动创建表。但是,我通过运行drop table sql从数据库中手动删除该表。然后再次运行hibernate应用程序。出现异常 引起原因:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:表’test.person’不存在 解决该问

  • 问题内容: 我知道会话不是线程安全的。我的第一个问题:将实体传递给另一个线程,对它做一些工作,然后将其传递回原始线程并进行更新,是否安全? 我的第二个问题:在一个线程中创建一个实体并将其保存在另一个线程中是否安全? 编辑 我忘了提到实体是为快速加载而专门配置的 问题答案: 否。该实体已附加到会话中,并包含链接到该会话的代理(以延迟自身加载)。因此,这样做将使用多个线程中的会话。由于会话不是线程安全

  • 以下问题:避免!=空语句我问我们的一位高级开发人员为什么不使用断言。虽然他的回答被证明是合理的(我们使用自定义异常),但他也声称断言是在开发和测试时使用的,而不是在生产中使用的。 但在甲骨文的文档中http://docs.oracle.com/javase/6/docs/technotes/guides/language/assert.html看起来断言的使用超出了测试范围,甚至考虑到禁用它们的可