SQLGrammarException:错误:关系“ angajat”不存在

时间:2019-05-22 10:31:21

标签: java sql postgresql hibernate jpa

编辑:通过更新所有导入的库(休眠,postgresql等)解决了问题。

我想通过PostgreSQL中的本地数据库服务器设置一个休眠的小型应用程序。我通过事先使用所有引用和约束创建数据库来作弊,因此可以通过JPA从表生成实体。现在,我删除了整个数据库(包括架构,无论如何都是“公开的”),当我尝试进行测试并将一些实体添加到数据库时,我收到一条错误消息,提示“错误:错误:关系“ angajat”不存在”

我检查了SQL方言是否正确,与数据库本地服务器的连接是否正确,我已经从之前创建的数据库中生成了类,之后又删除了它,因此我可以从创建的实体中创建它,但是那样行不通,因为这会给我带来更多错误。 因此,我重新添加了手动创建的数据库,并尝试通过“
”对其进行“更新”

错误少,但问题仍然存在。

AbstractEntity.java

    package metamodel;

    import java.io.Serializable;
    import java.util.Calendar;
    import java.util.Date;

    import javax.persistence.Column;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.MappedSuperclass;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;
    import javax.persistence.Version;

    @MappedSuperclass
    public abstract class AbstractEntity implements Serializable {

        private static final long serialVersionUID = -4803471783122679780L;

        public static long getSerialVersionUID() {
            return serialVersionUID;
        }

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "id")
        protected Long id;

        @Version
        @Column(name = "version")
        private Integer version;
        private String createdByUser;
        private String updatedByUser;


        private String entity_type = this.getClass().getSimpleName();

        @Temporal(value = TemporalType.TIMESTAMP)
        @Column(name = "dateCreated", nullable = false)
        private Date dateCreated=Calendar.getInstance().getTime();

        @Temporal(value = TemporalType.TIMESTAMP)
        @Column(name = "dateUpdated", nullable = false)
        private Date dateUpdated=Calendar.getInstance().getTime();




        /**
         * The default constructor is always needed for JPA.
         */
        public AbstractEntity() {
            super();
        }

        public AbstractEntity(Long id) {
            this();
            this.id = id;

        }


        @Override
        public boolean equals(Object obj) {
            if (id == null)
                return super.equals(obj);
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            final AbstractEntity other = (AbstractEntity) obj;
            if (id == null) {
                if (other.id != null)
                    return false;
            } else if (!id.equals(other.id))
                return false;
            return true;
        }

        @Override
        public int hashCode() {
            if (id == null)
                return super.hashCode();

            final int prime = 31;
            int result = 1;
            result = prime * result + ((id == null) ? 0 : id.hashCode());
            return result;
        }

        public String getCreatedByUser() {
            return createdByUser;
        }

        public Date getDateCreated() {
            return dateCreated;
        }

        public Date getDateUpdated() {
            return dateUpdated;
        }

        public String getEntity_type() {
            return entity_type;
        }

        public Long getId() {
            return id;
        }



        public String getUpdatedByUser() {
            return updatedByUser;
        }

        public Integer getVersion() {
            return version;
        }



        public void setCreatedByUser(String createdByUser) {
            this.createdByUser = createdByUser;
        }

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

        public void setDateUpdated(Date dateUpdated) {
            this.dateUpdated = dateUpdated;
        }


        public void setEntity_type(String entity_type) {
            this.entity_type = entity_type;
        }

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


        public void setUpdatedByUser(String updatedByUser) {
            this.updatedByUser = updatedByUser;
        }

        public void setVersion(Integer version) {
            this.version = version;
        }

    }

Angajat.java

package sgsm.model.entities;

    import java.util.List;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.ManyToOne;
    import javax.persistence.NamedQuery;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;

    import metamodel.AbstractEntity;

    @Entity
    @NamedQuery(name="Angajat.findAll", query="SELECT a FROM Angajat a")
    public class Angajat extends AbstractEntity {

        //@Id
        @Column(unique = true)
        private long codangajat;

        private String email;

        private String functie;

        private String nume;

        //bi-directional many-to-one association to Echipa
        @OneToMany(mappedBy="angajat")
        private List<Echipa> echipe;

        // Contructors
        public Angajat() {
        }
        public Angajat(long codangajat, String email, String functie, String nume, List<Echipa> echipe) {
            super();
            this.codangajat = codangajat;
            this.email = email;
            this.functie = functie;
            this.nume = nume;
            this.echipe = echipe;
        }



        // Getters && Setters
        public long getCodangajat() {
            return this.codangajat;
        }

        public void setCodangajat(long codangajat) {
            this.codangajat = codangajat;
        }

        public String getEmail() {
            return this.email;
        }

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

        public String getFunctie() {
            return this.functie;
        }

        public void setFunctie(String functie) {
            this.functie = functie;
        }

        public String getNume() {
            return this.nume;
        }

        public void setNume(String nume) {
            this.nume = nume;
        }

        public List<Echipa> getEchipe() {
            return this.echipe;
        }

        public void setEchipe(List<Echipa> echipe) {
            this.echipe = echipe;
        }

        public Echipa addEchipa(Echipa echipa) {
            getEchipe().add(echipa);
            echipa.setAngajat(this);

            return echipa;
        }

        public Echipa removeEchipa(Echipa echipa) {
            getEchipe().remove(echipa);
            echipa.setAngajat(null);

            return echipa;
        }
    }

TestAngajati.java


    package sgsm.test.repository;

    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;

    import junit.framework.Assert;
    import sgsm.model.entities.Angajat;
    import sgsm.model.repository.MasterRepository;
    import sgsm.model.repository.MasterRepositoryDefault;

    public class TestAngajati {
        static MasterRepository repo = new MasterRepositoryDefault();

        static String[] angajatiNume = {"Gherman", "Arama", "Teodoru", "Nedelcu"};
        static String[] angajatiPrenume = {"Silviu", "Anca", "Rebeca", "Stefan"};

        public static void main(String[] args) {
            List<Angajat> x = repo.findAngajatAll();
            if (x.size() == 0)
            {
                adaugaAngajati();
                x = repo.findAngajatAll();
            }
            Assert.assertTrue( x.size() > 0);


        }

        public static void adaugaAngajati() {
            Angajat g = null;
            repo.beginTransaction();

            for (int i=0; i<4; i++) {

                g=new Angajat();
                g.setCodangajat(1000+i);
                g.setNume(angajatiNume[i]+" "+angajatiPrenume[i]);
                g.setEmail(angajatiNume[i].toLowerCase()+angajatiPrenume[i].toLowerCase()+"@email.com");
                g.setFunctie("Programator");

                repo.addAngajat(g);
            }
            repo.commitTransaction();
        }
    }

persistence.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="1.0"
        xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
        <persistence-unit name="SGSMPersistenceUnit"
            transaction-type="RESOURCE_LOCAL">
            <provider>org.hibernate.ejb.HibernatePersistence</provider>

            <properties>
                <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
                <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/postgres" />
                <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
                <property name="hibernate.connection.username" value="postgres" />
                <property name="hibernate.connection.password" value="postgres" />

                <property name="hibernate.hbm2ddl.auto" value="update" />
                <property name="hibernate.show_sql" value="true" />
                <property name="hibernate.format_sql" value="true" />
                <property name="spring.jpa.hibernate.ddl-auto=create" value="true"/>

            </properties>
        </persistence-unit>
    </persistence>

Expected: The test running successfully.
Actual: lots of errors


May 22, 2019 1:23:49 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
May 22, 2019 1:23:49 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.2.Final}
May 22, 2019 1:23:49 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 22, 2019 1:23:49 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 22, 2019 1:23:50 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 22, 2019 1:23:50 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
May 22, 2019 1:23:50 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: true
May 22, 2019 1:23:50 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/postgres/public]
May 22, 2019 1:23:50 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=postgres, password=****, autocommit=true, release_mode=auto}
May 22, 2019 1:23:50 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
May 22, 2019 1:23:50 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 22, 2019 1:23:50 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
May 22, 2019 1:23:50 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
May 22, 2019 1:23:51 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
May 22, 2019 1:23:51 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
May 22, 2019 1:23:51 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
May 22, 2019 1:23:51 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 42703
May 22, 2019 1:23:51 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ERROR: column t1.tgconstrname does not exist
  Position: 113
May 22, 2019 1:23:51 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: HHH000299: Could not complete schema update
java.lang.NullPointerException
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    at org.hibernate.tool.hbm2ddl.DatabaseMetadata.getTableMetadata(DatabaseMetadata.java:129)
    at org.hibernate.cfg.Configuration.generateSchemaUpdateScript(Configuration.java:1131)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:212)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:178)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:495)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1741)
    at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:93)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890)
    at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:57)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
    at metamodel.AbstractRepository.<clinit>(AbstractRepository.java:30)
    at sgsm.test.repository.TestAngajati.<clinit>(TestAngajati.java:21)

Hibernate: 
    select
        angajat0_.id as id1_,
        angajat0_.createdByUser as createdB2_1_,
        angajat0_.dateCreated as dateCrea3_1_,
        angajat0_.dateUpdated as dateUpda4_1_,
        angajat0_.entity_type as entity5_1_,
        angajat0_.updatedByUser as updatedB6_1_,
        angajat0_.version as version1_,
        angajat0_.codangajat as codangajat1_,
        angajat0_.email as email1_,
        angajat0_.functie as functie1_,
        angajat0_.nume as nume1_ 
    from
        Angajat angajat0_
May 22, 2019 1:23:51 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 42703
May 22, 2019 1:23:51 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ERROR: column angajat0_.id does not exist
  Position: 8
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: ERROR: column angajat0_.id does not exist
  Position: 8
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1365)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1293)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:265)
    at sgsm.model.repository.MasterRepositoryDefault.findAngajatAll(MasterRepositoryDefault.java:98)
    at sgsm.test.repository.TestAngajati.main(TestAngajati.java:27)
Caused by: org.hibernate.exception.SQLGrammarException: ERROR: column angajat0_.id does not exist
  Position: 8
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at com.sun.proxy.$Proxy18.executeQuery(Unknown Source)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:1962)
    at org.hibernate.loader.Loader.doQuery(Loader.java:829)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289)
    at org.hibernate.loader.Loader.doList(Loader.java:2447)
    at org.hibernate.loader.Loader.doList(Loader.java:2433)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2263)
    at org.hibernate.loader.Loader.list(Loader.java:2258)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1215)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:256)
    ... 2 more
Caused by: org.postgresql.util.PSQLException: ERROR: column angajat0_.id does not exist
  Position: 8
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2096)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1829)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:510)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:386)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:271)
    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.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
    ... 17 more

1 个答案:

答案 0 :(得分:1)

  • 休眠错误抱怨Angajat.java中不存在列id, 由于您有codangajat列的@Column(unique = true)规范,因此不妨使用@Id注释。

  • 由于不推荐使用PostgreSQL82Dialect,因此您应该使用PostgreSQLDialect。 来源-org.hibernate.dialect.PostgreSQLDialect is deprecated

  • 您知道PostGreSQL方言区分大小写-对吗?

您的@NamedQuery由大写的 A 表名和 Angajat 组成,其中@OneToMany由小写的 a 组成 angajat 。而且您还没有提到数据库表名实际上是在什么情况下。

以适当的区分大小写的方式更新代码,这很好。