Mysql表不存在/ JPA Annotation

时间:2015-04-30 20:09:41

标签: java mysql hibernate

我尝试将具有一些功能的Person添加到数据库中。我使用mysql和jpa annotation。当我在服务器上运行项目时,我有以下控制台输出:

Apr 30, 2015 10:42:14 PM com.sun.faces.context.ExceptionHandlerImpl log
    1100: JSF1073: javax.faces.view.facelets.TagAttributeException caught during processing of RENDER_RESPONSE 6 : UIComponent-ClientId=, Message=/person.xhtml @77,56 test="${!empty personService.listPersons()}" /person.xhtml @77,56 test="${!empty personService.listPersons()}": org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    Apr 30, 2015 10:42:14 PM com.sun.faces.context.ExceptionHandlerImpl log
    1100: /person.xhtml @77,56 test="${!empty personService.listPersons()}" /person.xhtml @77,56 test="${!empty personService.listPersons()}": org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    javax.faces.view.facelets.TagAttributeException: /person.xhtml @77,56 test="${!empty personService.listPersons()}" /person.xhtml @77,56 test="${!empty personService.listPersons()}": org.hibernate.exception.SQLGrammarException: could not extract ResultSet
        at com.sun.faces.facelets.tag.TagAttributeImpl.getObject(TagAttributeImpl.java:358)
        at com.sun.faces.facelets.tag.TagAttributeImpl.getBoolean(TagAttributeImpl.java:150)
        at com.sun.faces.facelets.tag.jstl.core.IfHandler.apply(IfHandler.java:91)
        at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
        at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
        at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:202)
        at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
        at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
        at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)
        at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87)
        at com.sun.faces.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:161)
        at com.sun.faces.application.view.FaceletViewHandlingStrategy.buildView(FaceletViewHandlingStrategy.java:991)
        at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:99)
        at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
        at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        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:170)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
        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:620)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
        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)
    Caused by: javax.el.ELException: /person.xhtml @77,56 test="${!empty personService.listPersons()}": org.hibernate.exception.SQLGrammarException: could not extract ResultSet
        at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114)
        at com.sun.faces.facelets.tag.TagAttributeImpl.getObject(TagAttributeImpl.java:356)
        ... 35 more
    Caused by: javax.el.ELException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
        at javax.el.BeanELResolver.invoke(BeanELResolver.java:191)
        at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
        at org.apache.el.parser.AstValue.getValue(AstValue.java:173)
        at org.apache.el.parser.AstEmpty.getValue(AstEmpty.java:46)
        at org.apache.el.parser.AstNot.getValue(AstNot.java:43)
        at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
        at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
        ... 36 more
    Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
        at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
        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.extract(ResultSetReturnImpl.java:89)
        at org.hibernate.loader.Loader.getResultSet(Loader.java:2065)
        at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
        at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
        at org.hibernate.loader.Loader.doQuery(Loader.java:909)
        at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
        at org.hibernate.loader.Loader.doList(Loader.java:2553)
        at org.hibernate.loader.Loader.doList(Loader.java:2539)
        at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
        at org.hibernate.loader.Loader.list(Loader.java:2364)
        at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
        at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
        at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
        at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
        at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
        at com.springhibernatejsf.dao.PersonDAOImpl.listPersons(PersonDAOImpl.java:32)
        at com.springhibernatejsf.service.PersonServiceImpl.listPersons(PersonServiceImpl.java:31)
        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:483)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
        at com.sun.proxy.$Proxy31.listPersons(Unknown Source)
        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:483)
        at javax.el.BeanELResolver.invoke(BeanELResolver.java:183)
        ... 42 more
    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'testdb.person' doesn't exist
        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:408)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
        at com.mysql.jdbc.Util.getInstance(Util.java:381)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
        at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
        at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
        at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643)
        at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
        at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2228)
        at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
        at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
        ... 76 more

据我所知,我不必在MySQLWorkbench中创建一个表.Entity类使用带注释的名称自动创建它。这就是为什么我只是在MySQL连接中创建了一个名为'TestDB'的模式并提供了它的功能WebContent / WEB-INF / applicationContext.xml文件。但是在运行程序之后,MySQL上的TestDB架构下没有创建表。

的applicationContext.xml

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

    <!-- DispatcherServlet Context: defines this servlet's request-processing 
        infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />


    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <beans:property name="url"
            value="jdbc:mysql://localhost:3306/TestDB" />
        <beans:property name="username" value="root" />
        <beans:property name="password" value="secret_root_password" />
    </beans:bean>

    <!-- Hibernate 4 SessionFactory Bean definition -->
    <beans:bean id="hibernate4AnnotatedSessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource" />
        <beans:property name="annotatedClasses">
            <beans:list>
                <beans:value>com.springhibernatejsf.model.Person</beans:value>
            </beans:list>
        </beans:property>
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
                </beans:prop>
                <beans:prop key="hibernate.show_sql">true</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>

    <beans:bean id="personDAO"
        class="com.springhibernatejsf.dao.PersonDAOImpl">
        <beans:property name="sessionFactory"
            ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="personService"
        class="com.springhibernatejsf.service.PersonServiceImpl">
        <beans:property name="personDAO" ref="personDAO"></beans:property>
    </beans:bean>

    <context:component-scan base-package="com.springhibernatejsf" />

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

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

</beans:beans>

Person.java

package com.springhibernatejsf.model;

import javax.faces.bean.ManagedBean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Entity bean with JPA annotations
 * 
 *
 */
@Entity
@Table(name="Person")
@ManagedBean(name="person")
public class Person {
    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    private String name;

    private String country;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

我是这些应用程序的新手。有一点我无法完全理解。虽然提供用户名和密码属性,但我有一些困惑。这个Table 'testdb.person' doesn't exist错误意味着与模式TestDB的连接成功?

另外,如何解决此Table 'testdb.person' doesn't exist错误?

2 个答案:

答案 0 :(得分:3)

您必须将hibernate.hbm2ddl.auto设置为create,以便创建不存在于db中的表。 (https://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch03.html#configuration-optional

 <!-- Hibernate 4 SessionFactory Bean definition -->
    <beans:bean id="hibernate4AnnotatedSessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource" />
        ...
        <beans:property name="hibernateProperties">
            <beans:props>
                ...
                <!-- Add this line -->
                <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>

            </beans:props>
        </beans:property>
    </beans:bean>

答案 1 :(得分:0)

尝试创建数据库TestDb并在其中创建表人员。这将有助于解决Testdb.person不存在错误。