org.hibernate.exception.SQLGrammarException:无法执行语句

时间:2016-03-04 05:09:11

标签: java sql-server spring hibernate spring-mvc

我是Hibernate和Spring的新手我试图使用Spring和Hibernate Configuration将Employee Object保存到SQL Server 2012中。但是我收到了错误!

  Mar 04, 2016 11:16:57 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4629104a: startup date [Fri Mar 04 11:16:57 EST 2016]; root of context hierarchy
Mar 04, 2016 11:16:57 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Mar 04, 2016 11:16:57 AM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Mar 04, 2016 11:16:57 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
Mar 04, 2016 11:16:57 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Mar 04, 2016 11:16:57 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.6.Final}
Mar 04, 2016 11:16:57 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 04, 2016 11:16:57 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Mar 04, 2016 11:16:58 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServer2012Dialect
Mar 04, 2016 11:16:58 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Mar 04, 2016 11:16:58 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Employee SignUp 1
e1
Employee SignUp 2
Employee SignUp 3
Employee SignUp 4
Mar 04, 2016 11:16:59 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 208, SQLState: S0002
Mar 04, 2016 11:16:59 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Invalid object name 'Employee'.
Mar 04, 2016 11:16:59 AM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
    at org.rajan.csci7795.service.EmployeeService.signUpEmployee(EmployeeService.java:55)
    at org.rajan.csci7795.model.EmployeeDB.main(EmployeeDB.java:18)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'Employee'.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1493)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:390)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:340)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:179)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:154)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:308)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 14 more

我的员工类

 package org.rajan.csci7795.model;

    import javax.persistence.Column;
    import javax.persistence.Entity;
   import javax.persistence.Id;
   import javax.persistence.Table;

@Entity
@Table(name="Employee")
public class Employee {
    @Id
    @Column(name="E_id")
    private String Employee_id;
    @Column(name="Password")
    private String Password;
    @Column(name="First_Name")
    private String first_name;
    @Column(name="Last_Name")
    private String last_name;
    @Column(name="Email")
    private String Email;
    @Column(name="Phone")
    private String phone;


public String getEmployee_id() {
    return Employee_id;
}
public void setEmployee_id(String employee_id) {
    Employee_id = employee_id;
}
public String getPassword() {
    return Password;
}
public void setPassword(String password) {
    Password = password;
}
public String getFirst_name() {
    return first_name;
}
public void setFirst_name(String first_name) {
    this.first_name = first_name;
}
public String getLast_name() {
    return last_name;
}
public void setLast_name(String last_name) {
    this.last_name = last_name;
}
public String getEmail() {
    return Email;
}
public void setEmail(String email) {
    Email = email;
}
public String getPhone() {
    return phone;
}
public void setPhone(String phone) {
    this.phone = phone;
}

}

我的EmployeeSample类

package org.rajan.csci7795.model;

import org.rajan.csci7795.service.EmployeeService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class EmployeeSample {


    public static void main(String[] args) throws ClassNotFoundException {


     ApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");
     EmployeeService src = appContext.getBean("employeeService",EmployeeService.class);  
    src.signUpEmployee();

}
}

我的EmployeeService类

package org.rajan.csci7795.service;



import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.rajan.csci7795.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

@Component
public class EmployeeService{


    @Autowired
    private SessionFactory sessionFactory;

    private String Employee_id;
    private String Password;
    private String first_name;
    private String last_name;
    private String Email;
    private String phone;

    public void signUpEmployee()
    {
        System.out.println("Employee SignUp 1");
        Employee employee= new Employee();
        employee.setEmployee_id("e1");
        employee.setPassword("rajan");
        employee.setFirst_name("Rajan");
        employee.setLast_name("Patel");
        employee.setEmail("rajan@ymail.com");
        employee.setPhone("y016801218");
        System.out.println(employee.getEmployee_id());
        System.out.println("Employee SignUp 2");
        sessionFactory=getSessionFactory();
        Session session=sessionFactory.openSession();
        session.beginTransaction();
        System.out.println("Employee SignUp 3");

        session.save(employee);
        System.out.println("Employee SignUp 4");
        session.getTransaction().commit();
        System.out.println("Employee SignUp 5");
        session.flush();
        session.close();
        System.out.println("Employee SignUp");
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }


}

Spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-4.1.xsd" 
     xmlns:context="http://www.springframework.org/schema/context">

    <context:annotation-config/>
    <context:component-scan base-package="org.rajan.csci7795.service" />
    <context:component-scan base-package="org.rajan.csci7795.model" /> 



    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
    <property name="url" value ="jdbc:sqlserver://localhost:1433;databaseName=MyStoreDB;integratedSecurity=true;"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="org.rajan.csci7795.model"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</prop>
                <prop key="show_sql">false</prop>
                <prop key="hbm2ddl.auto">create</prop>
                <prop key="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</prop>
            </props>
        </property>
    </bean>

</beans>    

prom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.rajan.csci7795</groupId>
  <artifactId>mobileshop</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>mobileshop Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
     <dependency> 
      <groupId>org.glassfish.jersey.bundles</groupId>
      <artifactId>jaxrs-ri</artifactId>
      <version>2.16</version>
  </dependency>
   <dependency> 
      <groupId>org.glassfish.jersey.media</groupId>
      <artifactId>jersey-media-moxy</artifactId>
      <version>2.16</version>
  </dependency>
  <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.6.Final</version>
    </dependency>


   <!--  <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate</artifactId>
        <version>3.2.3.ga</version>
</dependency> -->

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.3.2.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-annotations</artifactId>
    <version>3.5.0-Final</version>
</dependency>


    <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
    </dependency>
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.31</version>
        </dependency>
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <!-- <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>4.0</version>
        </dependency> -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.0.8.RELEASE</version>        
        </dependency>
        <!-- <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.0.1.GA</version>
        </dependency> -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>

 </dependencies>

 <build>
    <finalName>mobileshop</finalName>
    <plugins>
    <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.5.1</version>
    <inherited>true</inherited>
    <configuration>
    <source>1.7</source>
    <target>1.7</target> 
    </configuration>
    </plugin>
    </plugins>

  </build>
</project>

我没有在我的数据库中创建任何表。在映射期间hibernate会自动创建一个吗?

1 个答案:

答案 0 :(得分:0)

尝试更改此语句,使代码数量减少第一行。

<context:annotation-config/>
    <context:component-scan base-package="org.rajan.csci7795.service" />
    <context:component-scan base-package="org.rajan.csci7795.model" /> 

<context:annotation-config/>
    <context:component-scan base-package="org.rajan.csci7795" />
  

现在这个陈述可能有问题

<beans xmlns="http://www.springframework.org/schema/beans"
   ...........
   ...........
   ...........
   ...........
     xmlns:context="http://www.springframework.org/schema/context">

复制这篇文章与任何其他来源可能有所帮助。

ERROR: Invalid object name 'Employee'.你专注于这个吗? 您已使用@Table(name = "Employee")。请先验证您的表名。它是Employee还是存在于任何其他Name

您可以更改DTO课程Employee

的代码
@Table(name = "Actual_Table_Name_Found_in_Database");