Solved

hibernate project throwing exception

Posted on 2009-07-06
8
2,137 Views
Last Modified: 2013-11-23
Hi,



I am running a example project from intertnet and got exception like



log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select hibernate_sequence.nextval from dual
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not get next sequence value
      at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
      at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
      at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:96)
      at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:99)
      at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
      at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
      at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172)
      at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
      at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
      at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
      at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
      at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:615)
      at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)
      at $Proxy5.save(Unknown Source)
      at roseindia.CreateData.main(CreateData.java:21)
Caused by: java.sql.SQLException: ORA-02289: sequence does not exist

      at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:111)
      at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:330)
      at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:287)
      at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:742)
      at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
      at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:812)
      at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1048)
      at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:853)
      at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1153)
      at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3369)
      at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3414)
      at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:75)
      ... 16 more


createData java looks like

package roseindia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class CreateData {


      public static void main(String[] args) throws Exception {
            // TODO Auto-generated method stub
            
            SessionFactory sessFact = HibernateUtil.getSessionFactory();
            Session sess = sessFact.getCurrentSession();
            org.hibernate.Transaction tr = sess.beginTransaction();
            
            Student stu = new Student();
            stu.setSname("Ganesh");
            stu.setSroll(100);
            stu.setScourse("B.C.A.");
            
            sess.save(stu);//Save data
            tr.commit();
            System.out.println("Successfully inserted");
            //sess.close();
      }

}



student.java looks like


/**
 *
 */
package roseindia;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import javax.persistence.Table;;

/**
 * @author Rose India
 *
 */
@Entity
@Table(name = "student")

public class Student implements Serializable{
      
            
      @Id
      @GeneratedValue
      
      private int id;
      public int getId() {
            return id;
      }

      public void setId(int id) {
            this.id = id;
      }
      
      @Column(name="sname", nullable=false,length=40)
      private String sname;
      public String getSname() {
            return sname;
      }

      public void setSname(String sname) {
            this.sname = sname;
      }
      
      @Column(name="sroll",nullable=false)
      private int sroll;
      public int getSroll() {
            return sroll;
      }

      public void setSroll(int sroll) {
            this.sroll = sroll;
      }
      
      @Column(name="scourse",nullable=false,length=10)
      private String scourse;
      public String getScourse() {
            return scourse;
      }

      public void setScourse(String scourse) {
            this.scourse = scourse;
      }
      
}



hibernate.cfg.xml looks like

<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="connection.username">deliverytest7</property>
<property name="connection.password">dbpassword</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">none</property>

<mapping class="roseindia.Student"/>

</session-factory>
</hibernate-configuration>



hibernate util class looks like


package roseindia;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
      //Singleton class
      private static final SessionFactory sessionFactory;
      static{
            try{
                  sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
            }catch(Throwable th){
                  System.err.println("Enitial SessionFactory creation failed"+th);
                  throw new ExceptionInInitializerError(th);
            }
      }
      
      public static SessionFactory getSessionFactory(){
            return sessionFactory;
      }

}


I was able to insert values outside hibernate through regular java program without any issues.

Any links, resources, ideas, sample code highly appreciated. Thanks in advance










0
Comment
Question by:gudii9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24787147
When using Hibernate with Oracle, the way you get incrementing primary keys / ID fields is by using sequences.

Hibernate Oracle dialect does this for you, but you must first create the sequence in the dabase.


SQL> create sequence foo_id_seq start with 1;

View your Hibernate entity file or annotations to see the name of the sequence that is expected. My Hibernate entities have a section that looks like this. The sequence below is named, and that is what you create.


		<id name="id" column="ID">
			<generator class="sequence">
				<param name="sequence">provider_id_seq</param>
			</generator>
		</id>

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
ID: 24790265
i changed Student.java as

/**
 *
 */
package roseindia;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author Rose India
 *
 */
@Entity
@Table(name = "student")

public class Student implements Serializable{
      
            
      @Id
      /////////////@GeneratedValue(strategy=GenerationType.IDENTITY )
      @GeneratedValue(strategy=GenerationType.AUTO, generator="increment")
      private int id;
      public int getId() {
            return id;
      }

      public void setId(int id) {
            this.id = id;
      }
      
      @Column(name="sname", nullable=false,length=40)
      private String sname;
      public String getSname() {
            return sname;
      }

      public void setSname(String sname) {
            this.sname = sname;
      }
      
      @Column(name="sroll",nullable=false)
      private int sroll;
      public int getSroll() {
            return sroll;
      }

      public void setSroll(int sroll) {
            this.sroll = sroll;
      }
      
      @Column(name="scourse",nullable=false,length=10)
      private String scourse;
      public String getScourse() {
            return scourse;
      }

      public void setScourse(String scourse) {
            this.scourse = scourse;
      }
      
}



and also created sequence like

   CREATE SEQUENCE  "DELIVERYTEST7"."STUDENTID"  MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 321 CACHE 20 NOORDER  NOCYCLE ;
   
   




but still getting error like
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Enitial SessionFactory creation failedorg.hibernate.AnnotationException: Unknown Id.generator: increment
Exception in thread "main" java.lang.ExceptionInInitializerError
      at roseindia.HibernateUtil.<clinit>(HibernateUtil.java:14)
      at java.lang.J9VMInternals.initializeImpl(Native Method)
      at java.lang.J9VMInternals.initialize(J9VMInternals.java:177)
      at roseindia.CreateData.main(CreateData.java:12)
Caused by: org.hibernate.AnnotationException: Unknown Id.generator: increment
      at org.hibernate.cfg.BinderHelper.makeIdGenerator(BinderHelper.java:413)
      at org.hibernate.cfg.AnnotationBinder.bindId(AnnotationBinder.java:1795)
      at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1229)
      at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:733)
      at org.hibernate.cfg.AnnotationConfiguration.processArtifactsOfType(AnnotationConfiguration.java:498)
      at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:277)
      at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1286)
      at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:915)
      at roseindia.HibernateUtil.<clinit>(HibernateUtil.java:11)
      ... 3 more

Please advise
0
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24790294
Try:

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="STUDENTID")

0
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 
LVL 7

Author Comment

by:gudii9
ID: 24790679
I tried

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="STUDENTID")

now getting error message like

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Enitial SessionFactory creation failedorg.hibernate.AnnotationException: Unknown Id.generator: STUDENTID
Exception in thread "main" java.lang.ExceptionInInitializerError
      at roseindia.HibernateUtil.<clinit>(HibernateUtil.java:14)
      at java.lang.J9VMInternals.initializeImpl(Native Method)
      at java.lang.J9VMInternals.initialize(J9VMInternals.java:177)
      at roseindia.CreateData.main(CreateData.java:12)
Caused by: org.hibernate.AnnotationException: Unknown Id.generator: STUDENTID
      at org.hibernate.cfg.BinderHelper.makeIdGenerator(BinderHelper.java:413)
      at org.hibernate.cfg.AnnotationBinder.bindId(AnnotationBinder.java:1795)
      at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1229)
      at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:733)
      at org.hibernate.cfg.AnnotationConfiguration.processArtifactsOfType(AnnotationConfiguration.java:498)
      at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:277)
      at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1286)
      at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:915)
      at roseindia.HibernateUtil.<clinit>(HibernateUtil.java:11)
      ... 3 more

Please advise
0
 
LVL 40

Accepted Solution

by:
mrjoltcola earned 500 total points
ID: 24790814
See this:

http://forum.springsource.org/showthread.php?t=27837

Quoting from the link:

@Entity
public class Train {

 @Id
 @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "TRAIN_SEQ")
 @SequenceGenerator(name="TRAIN_SEQ", sequenceName = "train_seq")
 private long id;

...

Does that work?
0
 
LVL 7

Author Comment

by:gudii9
ID: 24791645
finally this one worked fine

public class Student implements Serializable{
      
            
      @Id
      
      @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="STUDENTID")
      @SequenceGenerator(name="STUDENTID", sequenceName = "STUDENTID")
0
 
LVL 7

Author Closing Comment

by:gudii9
ID: 31600257
thank you very much for your help
0

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This video teaches viewers about errors in exception handling.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question