为啥休眠不能执行命令

Posted

技术标签:

【中文标题】为啥休眠不能执行命令【英文标题】:Why can't hibernate execute command为什么休眠不能执行命令 【发布时间】:2016-06-28 10:38:11 【问题描述】:

Hibernate 无法执行该表已经退出数据库的命令。我梳理了整个互联网,无法弄清楚问题到底是什么。无论如何,我是休眠的新手,下面是场景。我的 java 文件是

为什么休眠会抛出该错误?解决这个问题的最佳方法是什么?

这是我的 Users.java

   @Entity
    @Table(name="users")
    public class Users 
        @Id
        @Column(name="USERID")
        @GeneratedValue
        private int userId;
        @Column(name="FULLNAME")
        private String fullName;
        @Column(name="USERNAME",unique=true, nullable=false)
        private String userName;
        @Column(name="PASSWORD",nullable=false)
        private String passWord;
        @Column(name="BANKBRANCH", nullable=false)
        private String bankBranch;
        @Column(name="DEPARTMENT",nullable=false)
        private String department;
        @Column(name="ROLEID", unique=true, nullable=false)
        private int roleId;
        @Column(name="ATMGROUPID" ,unique=true, nullable=false)
        private int amtGroupID;
        @Column(name="DATECREATED")
        private Date dateCreated;
        @Column(name="LASTLOGIN")
        private Date lastLogin;
        @Column(name="USERCREATEDBY")
        private String userCreatedBy;

        @Column(name="STATE", nullable=false)
        private String state=State.ACTIVE.getState();

        // @ManyToMany(fetch = FetchType.EAGER)
         @ManyToMany(cascade=CascadeType.ALL)
         @JoinTable(name = "UserRoleStatus", 
         joinColumns =  @JoinColumn(name = "userId") , 
         inverseJoinColumns =  @JoinColumn(name = "roleId") )
    private Set<UserRoles> UserRoles = new HashSet<UserRoles>();


        public int getUserId() 
            return userId;
        

        public void setUserId(int userId) 
            this.userId = userId;
        

        public String getFullName() 
            return fullName;
        

        public void setFullName(String fullName) 
            this.fullName = fullName;
        

        public String getUserName() 
            return userName;
        

        public void setUserName(String userName) 
            this.userName = userName;
        

        public String getPassWord() 
            return passWord;
        

        public void setPassWord(String passWord) 
            this.passWord = passWord;
        

        public String getBankBranch() 
            return bankBranch;
        

        public void setBankBranch(String bankBranch) 
            this.bankBranch = bankBranch;
        

        public String getDepartment() 
            return department;
        

        public void setDepartment(String department) 
            this.department = department;
        

        public int getRoleId() 
            return roleId;
        

        public void setRoleId(int roleId) 
            this.roleId = roleId;
        

        public int getAmtGroupID() 
            return amtGroupID;
        

        public void setAmtGroupID(int amtGroupID) 
            this.amtGroupID = amtGroupID;
        

        public Date getDateCreated() 
            return dateCreated;
        

        public void setDateCreated(Date dateCreated) 
            this.dateCreated = dateCreated;
        

        public Date getLastLogin() 
            return lastLogin;
        

        public void setLastLogin(Date lastLogin) 
            this.lastLogin = lastLogin;
        

        public String getUserCreatedBy() 
            return userCreatedBy;
        

        public void setUserCreatedBy(String userCreatedBy) 
            this.userCreatedBy = userCreatedBy;
        

        public String getState() 
            return state;
        

        public void setState(String state) 
            this.state = state;
        

        public Set<UserRoles> getUserRoles() 
            return UserRoles;
        

        public void setUserRoles(Set<UserRoles> userRoles) 
            UserRoles = userRoles;
        

        @Override
        public int hashCode() 
            final int prime = 31;
            int result = 1;
            result = prime * result + userId;
            result = prime * result + ((userName == null) ? 0 : userName.hashCode());
            return result;
        

        @Override
        public boolean equals(Object obj) 
            if (this == obj)
                return true;
            if (obj == null)
                return false;

            /*if (getClass() != obj.getClass())
                return false;*/

            if (!(obj instanceof Users))
                return false;

            Users other = (Users) obj;
             if (userId != other.userId)
                    return false;
            if (userName == null) 
                if (other.userName != null)
                    return false;
             else if (!userName.equals(other.userName))
                return false;
            return true;
        

        @Override
        public String toString() 
            return "Users [userId=" + userId + ", fullName=" + fullName + ", userName=" + userName + ", passWord="
                    + passWord + ", bankBranch=" + bankBranch + ", department=" + department + ", roleId=" + roleId
                    + ", amtGroupID=" + amtGroupID + ", dateCreated=" + dateCreated + ", lastLogin=" + lastLogin
                    + ", userCreatedBy=" + userCreatedBy + ", state=" + state + ", UserRoles=" + UserRoles + "]";
        

我的 usersRoles.Java

@Entity
@Table(name = "USERROLES")
public class UserRoles 

     @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int roleId;

    @Column(name="ROLE",length=15, unique=true, nullable=false)
    private String role = UserRolesRoles.User.getUserRolesRoles();

    public int getRoleId() 
        return roleId;
    

    public void setRoleId(int roleId) 
        this.roleId = roleId;
    

    public String getRole() 
        return role;
    

    public void setRole(String role) 
        this.role = role;
    

    @Override
    public int hashCode() 
        final int prime = 31;
        int result = 1;
        result = prime * result + ((role == null) ? 0 : role.hashCode());
        result = prime * result + roleId;
        return result;
    

    @Override
    public boolean equals(Object obj) 
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (!(obj instanceof UserRoles))
            return false;

        /*
         * if (getClass() != obj.getClass()) return false;
         */

        UserRoles other = (UserRoles) obj;

        if (roleId != other.roleId)
            return false;

        if (role == null) 
            if (other.role != null)
                return false;
         else if (!role.equals(other.role))
            return false;

        return true;
    


我的 serverlet.xml

<context:property-placeholder location="classpath:resources/database.properties" />
    <context:component-scan base-package="recon.controller" />

    <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>

    <!-- viewResolver tell which viewResolver to use it tell the location of 
        the view in the project -->

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <mvc:resources location="/resoures/**" mapping="/resoures/" />
    <mvc:default-servlet-handler />
    <mvc:annotation-driven />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="$database.driver" />
        <property name="url" value="$database.url" />
        <property name="username" value="$database.user" />
        <property name="password" value="$database.password" />
    </bean>

    <bean id="sessionFactory" 
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="recon.model" />

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">$hibernate.dialect</prop>
                <prop key="hibernate.show_sql">$hibernate.show_sql</prop>
                <prop key="hibernate.hbm2ddl.auto">$hibernate.hbm2ddl.auto</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateTransactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

web.xml

<servlet>
  <servlet-name>spring-dispatcher</servlet-name>
  <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
  </servlet>

  <servlet-mapping>
  <servlet-name>spring-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
  </servlet-mapping>


  <session-config>
        <session-timeout>15</session-timeout>
        <tracking-mode>COOKIE</tracking-mode>
    </session-config>



    <welcome-file-list>  
  <welcome-file>index.jsp</welcome-file>  
 </welcome-file-list>  

     <!-- Spring Security -->  
    <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

完整的堆栈跟踪

Mar 13, 2016 2:22:41 AM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Unable to execute command [alter table UserRoleStatus add constraint FKon0rvnj31qoi3177vwn868stx foreign key (roleId) references USERROLES (roleId)]
org.hibernate.tool.schema.spi.CommandAcceptanceException: Unable to execute command [alter table UserRoleStatus add constraint FKon0rvnj31qoi3177vwn868stx foreign key (roleId) references USERROLES (roleId)]
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:63)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlString(SchemaMigratorImpl.java:567)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlStrings(SchemaMigratorImpl.java:551)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:510)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.performMigration(SchemaMigratorImpl.java:309)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:137)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:110)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:176)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:372)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:454)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:439)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: Can't create table 'G-Recon.#sql-33d9_378' (errno: 150)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2618)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
    at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:842)
    at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:681)
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:51)
    ... 51 more

Mar 13, 2016 2:22:42 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'spring-dispatcher': initialization completed in 20634 ms
Mar 13, 2016 2:22:42 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring-dispatcher] in context with path [/G_Rcon_Hibernate] threw exception
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1060)
    at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:326)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:255)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

mySql 表

CREATE TABLE `UserRoleStatus` (
  `userId` bigint(20) UNSIGNED NOT NULL,
  `roleId` bigint(20) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `UserRoleStatus` (`userId`, `roleId`) VALUES
(2, 2),
(1, 3);



ALTER TABLE `UserRoleStatus`
  ADD PRIMARY KEY (`userId`,`roleId`),
  ADD KEY `roleId` (`roleId`),
  ADD KEY `userId` (`userId`);

ALTER TABLE `UserRoleStatus`
  ADD CONSTRAINT `FKefv8xn71lecn5wv6nfs8leeu1` FOREIGN KEY (`userId`) REFERENCES `users` (`userId`),
  ADD CONSTRAINT `UserRoleStatus_ibfk_1` FOREIGN KEY (`roleId`) REFERENCES `userRoles` (`roleId`),
  ADD CONSTRAINT `UserRoleStatus_ibfk_2` FOREIGN KEY (`userId`) REFERENCES `users` (`userId`);

【问题讨论】:

您可能需要关注错误跟踪,其中 Hibernate 无法运行此查询alter table UserRoleStatus add constraint FKon0rvnj31qoi3177vwn868stx foreign key (roleId) references USERROLES (roleId),您可以尝试自己在 mySQL 客户端中运行该语句。如果您遇到相同的错误,那么您必须修复它。一些很好的原因列表是here,例如。是 FKon0rvnj31qoi3177vwn868stx 已经定义,都是同一引擎上的表等。 【参考方案1】:

在休眠启动时,您可以激活更新数据库、验证实体或创建数据库的模式...。 查看您使用的 persistence.xml 女巫模式。 寻找房产 hibernate.hbm2ddl.auto

您可以在此处找到有关此的更多信息:

Hbms2ddl

【讨论】:

这是我的 HDMs2ddl 它已经设置为更新 hibernate.hbm2ddl.auto=update 尝试验证更新,但您必须手动更新您的数据库。

以上是关于为啥休眠不能执行命令的主要内容,如果未能解决你的问题,请参考以下文章

OleDbCommand 不能执行这个命令,为啥?

为啥不能在多行执行 PSQL 元命令

为啥python3不能执行一些linux命令?

当命令在 Ubuntu 终端中运行时,为啥 Dart 的“Process.start”不能执行 Ubuntu 命令?

oracle exp命令为啥不能用

linux shell脚本为啥不能执行if命令