1

I'm using JPA with Hibernate to connect to a Postgres database, and I'm unable to persist an Entity into the database.

I have the following in the database:

CREATE SEQUENCE "MODEL_C_MODEL_seq"
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 93
  CACHE 1;
ALTER TABLE "MODEL_C_MODEL_seq"

CREATE TABLE "MODEL"
(
  "C_USER" character varying(10) NOT NULL,
  "C_MODEL" serial NOT NULL,
  "TP_MODEL" character(5) NOT NULL,
  "NM_MODEL" character varying(20) NOT NULL,
  CONSTRAINT "MODEL_PK" PRIMARY KEY ("C_MODEL" ),
  CONSTRAINT "MODEL_CUSER_FK" FOREIGN KEY ("C_USER")
      REFERENCES "USER" ("C_USER") MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT "MODEL_TPMODEL_FK" FOREIGN KEY ("TP_MODEL")
      REFERENCES "ADM_TYPES" ("C_TYPE") MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT "MODEL_CUSER_NMNAME_UNIQUE" UNIQUE ("C_USER" , "NM_MODEL" )
)
WITH (
  OIDS=FALSE
);

My Entity is:

public class Model implements Serializable {
    private static final long serialVersionUID = 1L;

    **@Id
    @SequenceGenerator(name="modelPKgen", sequenceName="MODEL_C_MODEL_seq")
    @GeneratedValue(generator="modelPKgen", strategy= GenerationType.IDENTITY)
    @Column(name = "\"C_MODEL\"", unique=true, insertable=false)    
    private int cModel;**

    @OneToMany(cascade = CascadeType.ALL,  fetch= FetchType.EAGER)//, mappedBy = "model", fetch= FetchType.EAGER)
    @JoinColumn(name= "`C_MODEL`")
    private Collection<State> stateCollection;

    @JoinColumn(name = "`C_USER`", referencedColumnName ="`C_USER`", updatable = false)
    @ManyToOne(optional = false)
    private User user;

    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(name = "\"NM_MODEL\"")
    private String nmModel;     

    @JoinColumn(name = "\"TP_MODEL\"")
    @ManyToOne(optional = false)
    private AdmTypes admTypes;
...

Checking in many posts it seems that I have the correct annotations for the field cModel.

I have a class that does the following:

Model dbModel = new Model(user.getCUser(), simModel.getName());
        AdmTypes dbAdm = new AdmTypes(simModel.getType());
        dbModel.setAdmTypes(dbAdm);

        **em.persist(dbModel);**
        em.flush();

When executing em.persist I get an exception with this error:

Caused by: org.hibernate.exception.SQLGrammarException: The column name "C_MODEL" was not found in this ResultSet.

When checking the insert statement done by Hibernate in em.persist I see:

insert 
    into
        "MODEL"
        ("TP_MODEL", "NM_MODEL", "C_USER") 
    values
        (?, ?, ?)

Which is perfect because that sentence runs in postgres (inserting a new record with a newly generated C_MODEL id).

Does anyone knows what could it be?

Update (Complete stacktrace):

javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: The column name "C_MODEL" was not found in this ResultSet.
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1367)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1295)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1301)
    at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:866)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:269)
    at com.librethinking.simmodsys.persistence.adapters.ModelConverter.SIMModelToModel(ModelConverter.java:65)
    at com.librethinking.simmodsys.ejb.ModelBean.saveSIMModel(ModelBean.java:72)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5366)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5338)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5326)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    at $Proxy186.saveSIMModel(Unknown Source)
    at com.librethinking.simmodsys.ejb.__EJB31_Generated__ModelBean__Intf____Bean__.saveSIMModel(Unknown Source)
    at com.librethinking.simmodsys.web.ModelsController.saveModel(ModelsController.java:366)
    at com.librethinking.simmodsys.web.ModelsController.processRequest(ModelsController.java:104)
    at com.librethinking.simmodsys.web.ModelsController.doPost(ModelsController.java:181)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
Caused by: org.hibernate.exception.SQLGrammarException: The column name "C_MODEL" was not found in this ResultSet.
    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.AbstractResultSetProxyHandler.continueInvocation(AbstractResultSetProxyHandler.java:108)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at $Proxy189.getInt(Unknown Source)
    at org.hibernate.id.IdentifierGeneratorHelper.get(IdentifierGeneratorHelper.java:152)
    at org.hibernate.id.IdentifierGeneratorHelper.getGeneratedIdentity(IdentifierGeneratorHelper.java:92)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:100)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2767)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3278)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:203)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:183)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:167)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:320)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
    at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:78)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:208)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:151)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:78)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:844)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:819)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:823)
    at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:860)
    ... 58 more
Caused by: org.postgresql.util.PSQLException: The column name "C_MODEL" was not found in this ResultSet.
    at org.postgresql.jdbc2.AbstractJdbc2ResultSet.findColumn(AbstractJdbc2ResultSet.java:2550)
    at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getInt(AbstractJdbc2ResultSet.java:2414)
    at sun.reflect.GeneratedMethodAccessor93.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractResultSetProxyHandler.continueInvocation(AbstractResultSetProxyHandler.java:104)
    ... 83 more
Christian Vielma
  • 15,263
  • 12
  • 53
  • 60
  • Can you put the full stack trace up on a pastebin? This looks rather odd and I'm wondering if the JDBC driver could be the culprit. The code looks OK though. That exception is thrown from AbstractJdbc2ResultSet.findColumn, where it appears that the column names get lower-cased when they're added to the column-name map, and lower-cased when looked up. – Craig Ringer Oct 03 '12 at 01:45
  • I suspect it has to do with your seemingly inaccurate use of GenerationType.IDENTITY. My guess is that Hibernate is trying to read back the IDENTITY generated value from the INSERT using getGeneratedKeys but the JDBC driver is not passing it back since the column is not defined as an IDENTITY . But as Craig asks, the stack trace will help shed light on that. – Steve Ebersole Oct 03 '12 at 02:00
  • @CraigRinger and Steve Ebersole Thanks! I added the stacktrace. I don't know what could it be – Christian Vielma Oct 03 '12 at 13:05

1 Answers1

1

A few things jump out at me:

  1. You're creating a sequence generator and then telling the id generation to be GenerationType.IDENTITY. I would try GenerationType.SEQUENCE or GenerationType.AUTO. I'd be surprised if identity worked since Hibernate docs say that it is for DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL.

  2. I'd get rid of the insertable=false attribute from the @Column annotation on your identifier. I would assume that based on your sequence generation attributes, Hibernate is going to select the sequence value and insert it: SELECT currval(pg_get_serial_sequence(...)) which will only work if insertable is true.

  3. Change sequenceName="MODEL_C_MODEL_seq" for sequenceName="\"MODEL_C_MODEL_seq\"".

Christian Vielma
  • 15,263
  • 12
  • 53
  • 60
Jeff
  • 3,669
  • 1
  • 23
  • 33
  • Thanks @Jeff. I saw this blog and seemed different so I tried, it seems that worked for some people: http://www.dilino.org/blog/?p=185. About the point 3, it's weird, but I had to do that in order to other things to work (references to other tables), and it does works, see this post: http://stackoverflow.com/questions/11595599/querying-postgresql-using-hibernate-jpa-dont-find-table. When following the steps you indicate in 1 and 2 it gives: org.hibernate.exception.SQLGrammarException: ERROR: relation "model_c_model_seq" does not exist – Christian Vielma Oct 03 '12 at 15:27
  • Doing 1 and 2, and changing sequenceName="MODEL_C_MODEL_seq" for sequenceName="\"MODEL_C_MODEL_seq\"" does the trick, if you correct you question I'll select yours – Christian Vielma Oct 03 '12 at 15:31
  • 1
    Removed my comment about backticks vs quotes. Seems to me like Hibernate should be more consistent about handling these things. – Jeff Oct 03 '12 at 16:34