0

EDIT: Problem solved by updating all the imported libraries (hibernate, postgresql, etc.).

I want to set up a hibernate small app through a local database server in PostgreSQL. I cheated a little bit by creating the Database before-hand with all the references and constraints, so I could generate the entities from tables through JPA. Now I deleted the whole database (including schema, which was 'public' anyway), and when I'm trying to do a test and add some entities to the database, I get an error saying "ERROR: ERROR: relation "angajat" does not exist"

I've checked if the SQL dialect is correct, if the connection to the DB local server is right, I've generated the classes from a DB i've created before-hand and I've deleted it afterwards, so i can create it from the entities I've created, but that didn't work because that'd give me even more errors. So, I've added back the manually created database and attempted to "update" it through

Less errors, but the problem is still there.

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
DayDreamer
  • 11
  • 5
  • I think you have not included the classes in Persistence Uint. Can you check once? – Ramachandra Reddy May 22 '19 at 11:05
  • @RamachandraReddy I'm not really familiar with that, but I google'd it up and I added the classes in the persistence.xml like mentioned here: https://stackoverflow.com/a/16205291/8851972 It didn't do the thing though. No changes, same errors. – DayDreamer May 22 '19 at 11:25
  • Do you have Hibernate configured to create the tables: – Simon Martinelli May 22 '19 at 15:08
  • @SimonMartinelli I've tried to change it to create, then to update back and now I did get past that problem, but I have another one. It says https://pastebin.com/iHjDLLfw ERROR: HHH000299: Could not complete schema update ------ And I'm using the right dialect in the persistence.xml. Furthermore, the classes I have were generated through an PostgreSQL DB – DayDreamer May 22 '19 at 17:03
  • Can you please post the whole stacktrace that commes after HHH000299 – Simon Martinelli May 22 '19 at 17:16
  • @SimonMartinelli Isn't it the one I uploaded on the pastebin link from my previous comment? https://pastebin.com/NgScJdxP – DayDreamer May 22 '19 at 17:48
  • O I didn't see that. Can you please try to use org.hibernate.dialect.PostgreSQL9Dialect – Simon Martinelli May 22 '19 at 18:02
  • Getting this nasty bad boy + an error window https://pastebin.com/vaZ6DrHE – DayDreamer May 22 '19 at 18:44

1 Answers1

1
  • Hibernate errors are complaining about column id not being exist in Angajat.java, Since you have @Column(unique = true) specification for codangajat column, might as well use @Id annotation.

  • you ought to use PostgreSQL82Dialect as PostgreSQLDialect is deprecated. Source - org.hibernate.dialect.PostgreSQLDialect is deprecated

  • You're aware that PostGreSQL dialect is case sensitive - right?

your @NamedQuery consist of capital A table name with Angajat where as your @OneToMany consist of lowercase a angajat. And you've not mentioned in what case your database table name actually is.

Update your code with appropriate case sensitivity and you're good to go.

Milan Desai
  • 1,228
  • 8
  • 23
  • I tried everything you mentioned, but it didn't do the trick :( Same thing going on, except I get more errors if I add Id's to the classes (Angajat.java) in this case, and remove the Id from the "AbstractEntity.class". – DayDreamer May 22 '19 at 16:53
  • @DayDreamer do you have column `Id` exist in table codangajat ? Are you certain that table structure is identical to entity? – Milan Desai May 23 '19 at 09:18
  • 1
    I managed to get over the problem by updating all the libraries. What I was using was a little bit outdated. Thank you for the suggestions nonetheless :) – DayDreamer May 23 '19 at 10:23