休眠:未找到表-org.h2.jdbc.JdbcSQLException

时间:2019-02-04 05:08:21

标签: hibernate jpa java-ee

我目前正在学习Java EE,并且JPA存在问题。似乎Hibernate无法找到我的名为“ category”的表(尽管它确实存在!)。我不认为这是命名的问题,因为我什至试图明确设置实体表名称。

我正在使用GlassFish(Payara)作为服务器。

如果有人可以发现问题,那就太好了。

顺便说一句,调用private void me.yanik.booksyanik.CategoryEditor.init()(像异常状态一样)应该没有问题。

除了堆栈跟踪和persistence.xml文件之外,我还提供了我现在拥有的3个类和pom.xml的源代码。

堆栈跟踪:

org.jboss.weld.exceptions.WeldException: WELD-000049: Unable to invoke private void me.yanik.booksyanik.CategoryEditor.init() on me.yanik.booksyanik.CategoryEditor@1a5c558f
    at org.jboss.weld.injection.producer.DefaultLifecycleCallbackInvoker.invokeMethods(DefaultLifecycleCallbackInvoker.java:85)
    at org.jboss.weld.injection.producer.DefaultLifecycleCallbackInvoker.postConstruct(DefaultLifecycleCallbackInvoker.java:66)
    at org.jboss.weld.injection.producer.BasicInjectionTarget.postConstruct(BasicInjectionTarget.java:122)
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:162)
    at org.jboss.weld.util.bean.IsolatedForwardingBean.create(IsolatedForwardingBean.java:45)
    at org.jboss.weld.contexts.AbstractContext.get(AbstractContext.java:96)
    at org.jboss.weld.contexts.PassivatingContextWrapper$AbstractPassivatingContextWrapper.get(PassivatingContextWrapper.java:76)
    at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.get(ContextualInstanceStrategy.java:100)
    at org.jboss.weld.bean.ContextualInstanceStrategy$CachingContextualInstanceStrategy.get(ContextualInstanceStrategy.java:177)
    at org.jboss.weld.bean.ContextualInstance.get(ContextualInstance.java:50)
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:700)
    at org.jboss.weld.module.web.el.AbstractWeldELResolver.lookup(AbstractWeldELResolver.java:107)
    at org.jboss.weld.module.web.el.AbstractWeldELResolver.getValue(AbstractWeldELResolver.java:90)
    at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:188)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:180)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:208)
    at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:116)
    at com.sun.el.parser.AstValue.getBase(AstValue.java:151)
    at com.sun.el.parser.AstValue.getValue(AstValue.java:200)
    at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
    at org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:97)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:181)
    at javax.faces.component.UIData.getValue(UIData.java:760)
    at javax.faces.component.UIData.getDataModel(UIData.java:1873)
    at javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:503)
    at javax.faces.component.UIData.setRowIndex(UIData.java:492)
    at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:564)
    at javax.faces.component.UIData.encodeBegin(UIData.java:1177)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1667)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:590)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1670)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1673)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1673)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:492)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:194)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:156)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:126)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:223)
    at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:732)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:475)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1628)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:755)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:575)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    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:498)
    at org.jboss.weld.injection.producer.DefaultLifecycleCallbackInvoker.invokeMethods(DefaultLifecycleCallbackInvoker.java:83)
    ... 72 more
Caused by: javax.ejb.EJBException
    at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:750)
    at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:700)
    at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:505)
    at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4664)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2131)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2101)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:90)
    at com.sun.proxy.$Proxy287.findAll(Unknown Source)
    at me.yanik.booksyanik.__EJB31_Generated__CategoryService__Intf____Bean__.findAll(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:498)
    at org.jboss.weld.util.reflection.Reflections.invokeAndUnwrap(Reflections.java:410)
    at org.jboss.weld.module.ejb.EnterpriseBeanProxyMethodHandler.invoke(EnterpriseBeanProxyMethodHandler.java:134)
    at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:56)
    at org.jboss.weld.module.ejb.InjectionPointPropagatingEnterpriseTargetBeanInstance.invoke(InjectionPointPropagatingEnterpriseTargetBeanInstance.java:68)
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:106)
    at me.yanik.booksyanik.CategoryService$Proxy$_$$_Weld$EnterpriseProxy$.findAll(Unknown Source)
    at me.yanik.booksyanik.CategoryEditor.init(CategoryEditor.java:28)
    ... 77 more
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not prepare statement
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1538)
    at org.hibernate.query.Query.getResultList(Query.java:168)
    at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:76)
    at me.yanik.booksyanik.CategoryService.findAll(CategoryService.java:54)
    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:498)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:953)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1017)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4884)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:836)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    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:498)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:895)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:835)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at org.jboss.weld.module.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:72)
    at org.jboss.weld.module.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
    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:498)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:895)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:835)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:374)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4856)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4844)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    ... 91 more
Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1990)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1920)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898)
    at org.hibernate.loader.Loader.doQuery(Loader.java:937)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340)
    at org.hibernate.loader.Loader.doList(Loader.java:2695)
    at org.hibernate.loader.Loader.doList(Loader.java:2678)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2512)
    at org.hibernate.loader.Loader.list(Loader.java:2507)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:504)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:396)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:224)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1511)
    at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1561)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1529)
    ... 125 more
Caused by: java.sql.SQLException: java.lang.reflect.UndeclaredThrowableException
    at com.sun.gjc.spi.jdbc40.ProfiledConnectionWrapper40.prepareStatement(ProfiledConnectionWrapper40.java:247)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
    ... 141 more
Caused by: java.lang.reflect.UndeclaredThrowableException
    at com.sun.proxy.$Proxy281.prepareStatement(Unknown Source)
    at com.sun.gjc.spi.base.ConnectionHolder.prepareStatement(ConnectionHolder.java:586)
    at com.sun.gjc.spi.jdbc40.ProfiledConnectionWrapper40.prepareCachedStatement(ProfiledConnectionWrapper40.java:372)
    at com.sun.gjc.spi.jdbc40.ProfiledConnectionWrapper40.prepareCachedStatement(ProfiledConnectionWrapper40.java:66)
    at com.sun.gjc.spi.ManagedConnectionImpl.prepareCachedStatement(ManagedConnectionImpl.java:1071)
    at com.sun.gjc.spi.jdbc40.ProfiledConnectionWrapper40.prepareStatement(ProfiledConnectionWrapper40.java:243)
    ... 143 more
Caused by: java.lang.reflect.InvocationTargetException
    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:498)
    at com.sun.gjc.spi.JdbcObjectsFactory$1.invoke(JdbcObjectsFactory.java:143)
    ... 149 more
Caused by: org.h2.jdbc.JdbcSQLException: Table "CATEGORY" not found; SQL statement:
select category0_.id as id1_0_, category0_.name as name2_0_ from Category category0_ [42102-196]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.command.Parser.readTableOrView(Parser.java:5552)
    at org.h2.command.Parser.readTableFilter(Parser.java:1266)
    at org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1946)
    at org.h2.command.Parser.parseSelectSimple(Parser.java:2095)
    at org.h2.command.Parser.parseSelectSub(Parser.java:1940)
    at org.h2.command.Parser.parseSelectUnion(Parser.java:1755)
    at org.h2.command.Parser.parseSelect(Parser.java:1743)
    at org.h2.command.Parser.parsePrepared(Parser.java:449)
    at org.h2.command.Parser.parse(Parser.java:321)
    at org.h2.command.Parser.parse(Parser.java:293)
    at org.h2.command.Parser.prepareCommand(Parser.java:258)
    at org.h2.engine.Session.prepareLocal(Session.java:578)
    at org.h2.engine.Session.prepareCommand(Session.java:519)
    at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1204)
    at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:73)
    at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:677)
    ... 154 more

persistence.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.2"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
    <persistence-unit name="bookspu" >
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <exclude-unlisted-classes>false</exclude-unlisted-classes>

        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect" />
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/books" />
            <property name="javax.persistence.jdbc.user" value="bookuser" />
            <property name="javax.persistence.jdbc.password" value="password" />
        </properties>
    </persistence-unit>
</persistence>

Category.java

package me.yanik.booksyanik;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;

@Entity
@Table(name = "category")
public class Category implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id = -1;
    private String name;

    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;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Category category = (Category) o;
        return id == category.id &&
                Objects.equals(name, category.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }

    @Override
    public String toString() {
        return "Category{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

CategoryEditor.java

package me.yanik.booksyanik;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;


@Named
@SessionScoped
public class CategoryEditor implements Serializable {
    private static final long serialVersionUID = 1L;
    private static final Logger logger = Logger.
            getLogger("CategoryEditor");
    private List<Category> categories;
    private List<Category> deletedCategories;

    @Inject CategoryService categoryService;

    @PostConstruct
    private void init() {
        categories = categoryService.findAll();
        deletedCategories = new ArrayList<>();
    }

    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }

    public String addCategory() {
        categories.add(new Category());
        return "";
    }

    public String deleteCategory(Category category) {
        if (category.getId() >= 0) {
            deletedCategories.add(category);
        }
        categories.remove(category);
        return "";
    }

    public String save() {
        for (Category category: categories) {
            categoryService.save((category));
        }
        for (Category category: deletedCategories) {
            categoryService.delete(category);
        }
        deletedCategories = new ArrayList<>();

        return "";
    }
}

CategoryService.java

package me.yanik.booksyanik;

import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;

@Stateless
public class CategoryService {
    @PersistenceContext(unitName = "bookspu")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public Category create(Category entity) {
        getEntityManager().persist(entity);
        return entity;
    }

    public Category read(Object id) {
        return getEntityManager().find(Category.class, id);
    }

    public Category update(Category entity) {
        return getEntityManager().merge(entity);
    }

    public void delete(Category entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    /**
     * Convenience method, to create or update automatically
     *
     * @param entity
     * @return managed entity
     */
    public Category save(Category entity) {
        if (entity.getId() < 0) {
            return create(entity);
        }
        return update(entity);
    }

    public List<Category> findAll() {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().
                createQuery();
        cq.select(cq.from(Category.class));
        return getEntityManager().createQuery(cq).getResultList();
    }

}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>me.yanik</groupId>
    <artifactId>BooksYanik</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>BooksYanik</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.0.Final</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>8.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
    </dependencies>
</project>

一些MySQL命令:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| books              |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

mysql> show tables;
+-----------------+
| Tables_in_books |
+-----------------+
| category        |
+-----------------+

mysql> select User from mysql.user;
+------------------+
| User             |
+------------------+
| bookuser         |
| mysql.infoschema |
| mysql.session    |
| mysql.sys        |
| root             |
+------------------+

3 个答案:

答案 0 :(得分:1)

我从报告的 stacktrace 中可以看到 H2 被用作您的数据源,但是从persistence.xml中,您将MySQL指定为JPA方言。 / p>

如果容器配置正确,您将找到已配置的MySQL数据源的JNDI名称,我们将其称为dataSource

从那里,您可以通过在persistence-unit标签内添加以下标签来修改persistence.xml:

<jta-data-source>dataSource</jta-data-source>

答案 1 :(得分:0)

我猜您需要在persistent.xml中的persistent-unit部分提及您的休眠实体

<persistent-unit>
 <class>me.yanik.booksyanik.Category</class>
...
</persistent-unit>

还要检查您是否正在使用Spring Boot,需要将其添加到主类中

@EntityScan(basepackage={me.yanik.*})

如果您在春季进行显式配置,则需要在配置类中添加

答案 2 :(得分:0)

最后,我找到了问题的答案!有些事情我做错了,我不知道。

如果您正在使用Java EE,并且没有在transaction-type文件中为persistence-unit指定persistence.xml,则默认为transaction-type="JTA"。同样,如果您使用的是Java SE,但未指定transaction-type,则默认为transaction-type="RESOURCE_LOCAL"

因此,在这种情况下,我使用的是Java EE,这意味着transaction-type默认为JTA。在不指定jta-data-source的情况下,使用的是默认数据源(EJB容器上的jdbc/__default)。此默认数据源是 H2 数据源。

我已经在persistence.xml文件中建立了直接的MySQL JDBC驱动程序连接。因此,我以为我正在连接它。但是,实际上是使用默认的H2数据源。由于我的表位于MySQL数据库而不是H2数据库中,因此找不到我的表。

我了解到的是,如果我使用Java EE,则应该使用JTA数据源,而不要直接建立JDBC驱动程序连接。这提供了一些优势,例如连接池和注入EntityManager

话虽如此,我对persistence.xml文件进行了一些更改。另外,我正在使用Maven标准目录结构在glassfish-resources.xml中创建一个src/main/setup文件。每当我使用NetBeans部署Web应用程序时,此文件就会加载适当的JDBC资源。请注意,通过使用MySQL8,数据源类名称应为com.mysql.cj.jdbc.MysqlConnectionPoolDataSource,而不是com.mysql.jdbc.jdbc2.optional.MysqlDataSource。此外,如果您在开发环境中未使用SSL,则需要将?useSSL=false参数添加到JDBC URL。

这是包含更改的文件。

persistence.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.2"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
    <persistence-unit name="bookspu" transaction-type="JTA">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <jta-data-source>jdbc/books</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>

        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect" />
        </properties>
    </persistence-unit>
</persistence>

glassfish-resources.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN"
        "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
    <jdbc-resource enabled="true"
                   jndi-name="jdbc/books"
                   object-type="user"
                   pool-name="mysql_Books_booksPool"/>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false"
                          connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10"
                          connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0"
                          connection-validation-method="auto-commit"
                          datasource-classname="com.mysql.cj.jdbc.MysqlConnectionPoolDataSource"
                          fail-all-connections="false" idle-timeout-in-seconds="300"
                          is-connection-validation-required="false" is-isolation-level-guaranteed="true"
                          lazy-connection-association="false" lazy-connection-enlistment="false"
                          match-connections="false" max-connection-usage-count="0" max-pool-size="32"
                          max-wait-time-in-millis="60000" name="mysql_Books_booksPool"
                          non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource"
                          statement-timeout-in-seconds="-1" steady-pool-size="8"
                          validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="127.0.0.1"/>
        <property name="portNumber" value="3306"/>
        <property name="databaseName" value="books"/>
        <property name="User" value="bookuser"/>
        <property name="Password" value="password"/>
        <property name="URL" value="jdbc:mysql://127.0.0.1:3306/Books?useSSL=false"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    </jdbc-connection-pool>
</resources>