2

I am getting exception on save operation to postgresql database using hibernate when I call addEventAction method from another class.

EventDAO.java:

package com.sessionpoint.session.sessiondr.core;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.sessionpoint.session.sessiondr.db.DrAction;

/**
 * Logic for the database operations related to the actions.
 *
 */
public class EventDAO {

   //To get the logger for class
   Logger log = Logger.getLogger("EventDAO");

    /**
     * Add dispatched event action into the database.
     * 
     * @param eventAction
     */
    public void addEventAction(DrAction eventAction) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();

        log.info("Connection with the database created successfuly.");

        try {
            trns = session.beginTransaction();
            session.save(eventAction); //exception here
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }
}

HibernateUtil.java:

public class HibernateUtil {
    private static SessionFactory sessionFactory;

    //To get the logger for class
    static Logger log = Logger.getLogger("HibernateUtil");

    static {

        log.info("Trying to create a connection with the database.");
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        sessionFactory = configuration.buildSessionFactory(ssrb.build());
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Exception Trace:

org.hibernate.MappingException: Unknown entity: com.sessionpoint.session.sessiondr.db.DrAction
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1094)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1439)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:711)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:703)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:698)
    at com.sessionpoint.session.sessiondr.core.EventDAO.addEventAction(EventDAO.java:35)

UPDATE:

hibernate.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.password">user</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/drcore</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    </session-factory>
</hibernate-configuration>

DrAction.java:

/**
 * DrAction for the dr_action table
 */
public class DrAction implements java.io.Serializable {

    /**
     * Default serial version Id.
     */
    private static final long serialVersionUID = 1L;

    /**
     * Auto increment drActionId.
     */
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long drActionId;
    private String drVName;
    private String drVRequestId;

    private Long vKey;

    public long getDrActionId() {
        return drActionId;
    }
    public void setDrActionId(long drActionId) {
        this.drActionId = drActionId;
    }
    public Long getvKey() {
        return vKey;
    }
    public void setvKey(Long vKey) {
        this.vKey = vKey;
    }
    public String getDrVName() {
        return drVName;
    }
    public void setDrVName(String drVName) {
        this.drVName = drVName;
    }
    public String getDrVRequestId() {
        return drVRequestId;
    }
    public void setDrVRequestId(String drVRequestId) {
        this.drVRequestId = drVRequestId;
    }
}

UPDATE:

Exception Trace 2:

org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    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.extract(ResultSetReturnImpl.java:89)
    at org.hibernate.id.SequenceGenerator.generateHolder(SequenceGenerator.java:122)
    at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:115)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:711)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:703)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:698)
    at com.sessionpoint.session.sessiondr.core.EventDAO.addEventAction(EventDAO.java:35)    
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.postgresql.util.PSQLException: ERROR: relation "hibernate_sequence" does not exist
  Position: 17
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2157)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1886)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:555)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:417)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:302)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)

UPDATE:

Exception Trace 3:

Caused by: org.hibernate.MappingNotFoundException: resource: com/sessionpoint/session/sessiondr/db/DrAction.hbm.xml not found
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:767)
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2255)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2227)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2207)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2160)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2075)
    at com.sessionpoint.session.sessiondr.core.HibernateUtil.<clinit>(HibernateUtil.java:24)
sjain
  • 23,126
  • 28
  • 107
  • 185

3 Answers3

3

Add @Entity to DrAction class, and add <mapping class="your.package.DrAction"/> to hibernate.cfg.xml.

@Entity
@Table(name = "dr_action")
public class DrAction implements java.io.Serializable {

hibernate.cfg.xml

...
    <session-factory>
        ....
        <mapping class="your.package.DrAction"/>
    </session-factory>
....

UPDATE

You are probably using Oracle as DB, and Oracle doesn't support auto generated ids. You'll have to specify sequence that will be used for generating ids.

Execute this in database

create sequence DR_ACTION_SEQ;

And change the id mapping to this

@Id 
@GeneratedValue(generator="drActionIdSeq") 
@SequenceGenerator(name="drActionIdSeq",sequenceName="DR_ACTION_SEQ", allocationSize=5)
private long drActionId;

Note that this expects that your id column is named dractionid, if it is not then you'll have to add a @Column annotation to the field, something like this

@Column(name = "dr_action_id")

You will have to do this for every column whose name isn't the same as column in database table.

Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • So I am having 5 classes for 5 tables. Do I need to add each class entry to `session-factory` ? – sjain Jan 16 '15 at 11:10
  • Yes, and all of them should have `@Entity` and `@Table` annotations (`@Table` is necessary only if table name differs from entity name). – Predrag Maric Jan 16 '15 at 11:13
  • After adding a mapping to configuration file, I am getting a compile time error at `` tag that says - "`The content of element type "session-factory" must match "(property*,mapping*,(class-cache|collection-cache)*,event*,listener*)`"." – sjain Jan 16 '15 at 11:14
  • `` elements should be added just before closing `` tag. – Predrag Maric Jan 16 '15 at 11:16
  • Now I am getting `org.hibernate.exception.SQLGrammarException: could not extract ResultSet` on the same save method. Any idea ? – sjain Jan 16 '15 at 11:22
  • Can you update the question with exception stacktrace? Probably some mapping is wrong. – Predrag Maric Jan 16 '15 at 11:24
  • @MyGod , the problem may be due to mapping of column,you will have to map your entity attribute to table column aswell. – dReAmEr Jan 16 '15 at 11:25
  • Posted the exception trace. Please check once. – sjain Jan 16 '15 at 11:29
  • To correct you - I am using `postgresql` and I am using auto increment for field `drActionId`. Is that code doing the same ? – sjain Jan 16 '15 at 12:12
  • @MyGod Oh, my mistake. Are you using the same settings for all of your entities? – Predrag Maric Jan 16 '15 at 12:25
  • yes the hibernate config file is same for all but all entities have different classes and different fields. Also I have different `hbm.xml` file for each entity. – sjain Jan 16 '15 at 12:27
  • @MyGod You don't need `hbm.xml` files if you are using annotations (unless you use annotations for additional configuration). If you already had everything configured in `hbm.xml` files, you shouldn't have added the annotations, but you should have `` entries in `hibernate.cfg.xml`. – Predrag Maric Jan 16 '15 at 14:09
  • My hbm files are auto generated by a tool and I am using them. I have added mapping resource entry now as you said. Now I am getting `MappingNotFoundException` for resource. This is probably because my `hibernate.cfg.xml` is in `src/main/resources` but my `DrAction.hbm.xml` is in `src/main/java/com/sessionpoint/session/sessiondr/db`. How to resolve the path ? Please see the updated error trace above in question. – sjain Jan 16 '15 at 14:33
  • It's important that they are in the classpath of the output folder. So, when you build the application `hibernate.cfg.xml` and all `hbm.xml` files will be somewhere in the classpath, and `hibernate.cfg.xml` references them by their path in the build folder. – Predrag Maric Jan 16 '15 at 14:44
  • yes I am using maven and it is based on convention over configuration so had difficulty in getting the right path for xml's . I managed to set the correct path with maven + hibernate. Thanks for your right directions. – sjain Jan 16 '15 at 15:45
1

Add below lines to your hibernate.cfg.xml

<mapping class="xxx.yyy.DrAction"/>//provide full package name

and @Entity and @Table (name="dr_action") annotation onDrAction` class

dReAmEr
  • 6,986
  • 7
  • 36
  • 63
  • After adding a mapping to configuration file, I am getting an error at `` tag that says - "`The content of element type "session-factory" must match "(property*,mapping*,(class-cache|collection-cache)*,event*,listener*)`"." – sjain Jan 16 '15 at 11:13
  • @MyGod can you post your dr_action schema?because the problem arises because of column name difference between entity and table and you have not defined and mapping to this. – dReAmEr Jan 16 '15 at 11:30
  • I was having the same problem, despite the mapping in `hibernate.cfg.xml` being correct, as well as the annotations in the classes, and nothing resolved. After researching a lot about Hibernate 5.x.x., I found that beyond these settings, you need to add the line `cfg.addAnnotatedClass ()`, in your case, `cfg.addAnnotatedClass (DrAction.class)`, below the line `configuration.configure ("hibernate.cfg.xml")`. After that, it worked. – mari Apr 19 '16 at 00:31
0

The @GeneratedValue annotation in postgre use sequence tables. since you haven't explicitly provided a name hibernate by default looks for hibernate_sequence sequence table.

Either add a sequence table by name hibernate_sequence in postgre schema or by any other name and add the name in the annotation.

Rohit
  • 2,132
  • 1
  • 15
  • 24