?
Solved

Hibernate Annotation Example id null issue

Posted on 2010-01-08
13
Medium Priority
?
1,757 Views
Last Modified: 2013-11-24
Hi,

I am using annotation tags within hibernate example 'CreateData.java'class to do simple insert into oracle 10g database table 'student2'. IP am 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.
Hibernate: insert into student2 (scourse, sname, sroll) values (?, ?, ?)
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not insert: [ri.Student2]
      at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
      at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
      at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:40)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)
      at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
      at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
      at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
      at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
      at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
      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(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)
      at $Proxy8.save(Unknown Source)
      at ri.CreateData.main(CreateData.java:22)
Caused by: java.sql.SQLException: ORA-01400: cannot insert NULL into ("DELIVERYTEST7"."STUDENT2"."ID")

      at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
      at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
      at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:590)
      at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1973)
      at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1119)
      at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2191)
      at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:2064)
      at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2989)
      at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:658)
      at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:33)
      ... 22 more



My createData.jaava looks like

package ri;

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();
            
            Student2 stu = new Student2();
            stu.setId(1);
            stu.setSname("sai");
            stu.setSroll(100211);
            stu.setScourse("M.S");
            
            sess.save(stu);//Save data
            tr.commit();
            System.out.println("Successfully inserted");
            //sess.close();
      }

}




hibernate-cfg class 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.MySQLDialect</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">update</property>

<mapping class="roseindia.Student2"/>

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


student2.java class looks like


package ri;

import java.io.Serializable;

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

import javax.persistence.Table;;

@Entity
@Table(name = "student2")
public class Student2 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;
      }
      
}


within oracle 10g my student2 table creation syntax looks like
CREATE TABLE student2(
  id VARCHAR2(20 BYTE) primary key NOT NULL,
  sname varchar(40) NOT NULL,
  sroll int(11) NOT NULL,
  scourse varchar(10) NOT NULL,
 
) ;
I am not sure why it is complaining about id is not null.

How can i resolve this issue. Any ideas, suggestions, links, resources, sample code highlly appreciated. Thanks in advance
0
Comment
Question by:gudii9
  • 6
  • 5
  • 2
13 Comments
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 26212564
as per code....

ur already insert the value...again ur going ur insert the same means primary key violation error will come so
stu.setId(2);

and run
0
 
LVL 20

Assisted Solution

by:a_b
a_b earned 400 total points
ID: 26212573
Since the id is generated do you need to call set on that?
0
 
LVL 7

Author Comment

by:gudii9
ID: 26212641
Hi,

I tried

>>>stu.setId(2);
still getting error like

Caused by: java.sql.SQLException: ORA-01400: cannot insert NULL into ("DELIVERYTEST7"."STUDENT2"."ID")

      at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)



>>>Since the id is generated do you need to call set on that?

 id is already set as per this code.

student2.java class looks like


package ri;

import java.io.Serializable;

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

import javax.persistence.Table;;

@Entity
@Table(name = "student2")
public class Student2 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;
      }
     
}

Not sure where else to set. Please advise
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 20

Expert Comment

by:a_b
ID: 26212645
Can you try executing the code after removing the setId() call?
0
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 26212654
     @Id
      @GeneratedValue
means u no need to set the value ...
its automatically generated!!
0
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 26212721
what is this???
@Id
      @GeneratedValue
      private int id;
bean define in but table varchar

id VARCHAR2(20 BYTE) primary key NOT NULL,
0
 
LVL 20

Accepted Solution

by:
Sathish David  Kumar N earned 1600 total points
ID: 26212727
bean define int but  in table varchar
0
 
LVL 7

Author Comment

by:gudii9
ID: 26212755
Hi,

>>>means u no need to set the value ...

 i commented the setter code in student2.java


I also commented the code within CreateData.java like

Student2 stu = new Student2();
            //stu.setId(2);



still getting same error as earlier...

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into student2 (scourse, sname, sroll) values (?, ?, ?)
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not insert: [roseindia.Student2]
      at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
      at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
      at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:40)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)
      at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)
      at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
      at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
      at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
      at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
      at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
      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(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)
      at $Proxy8.save(Unknown Source)
      at roseindia.CreateData.main(CreateData.java:22)
Caused by: java.sql.SQLException: ORA-01400: cannot insert NULL into ("DELIVERYTEST7"."STUDENT2"."ID")

      at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
      at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
      at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:590)
      at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1973)
      at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1119)
      at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2191)
      at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:2064)
      at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2989)
      at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:658)
      at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:33)
      ... 22 more



I suspect on table creation syntax is auto-increment or sequence etc is missing? please advise
0
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 26212814
@GeneratedValue menas its automatically genrated the value . no need to set.
that will take care of annotation !!increment

ur pblm is
in ur bean  ur define the id  value as int
but in table u define as varchar !!

0
 
LVL 7

Author Comment

by:gudii9
ID: 26213345
Hi,

I changed the varchar to int in the database still getting same error. Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 26214459
Hi,

Above example working fine in mysql when i d column is set as auto increment. But in oracle there is no concept of auto increment. I am not sure how to make it work.


I tried other example without annotation againest same database like

public class Contact {
      private String firstName;
      private String lastName;
      private String email;
      private long id;

      /**
       * @return Email
       */
      public String getEmail() {
            return email;
      }

      /**
       * @return First Name
       */
      public String getFirstName() {
            return firstName;
      }

      /**
       * @return Last name
       */
      public String getLastName() {
            return lastName;
      }

      /**
       * @param string Sets the Email
       */
      public void setEmail(String string) {
            email = string;
      }

      /**
       * @param string Sets the First Name
       */
      public void setFirstName(String string) {
            firstName = string;
      }

      /**
       * @param string sets the Last Name
       */
      public void setLastName(String string) {
            lastName = string;
      }

      /**
       * @return ID Returns ID
       */
      public long getId() {
            return id;
      }

      /**
       * @param l Sets the ID
       */
      public void setId(long l) {
            id = l;
      }

}



java class looks like


public class FirstExample {
      public static void main(String[] args) {
            Session session = null;

            try{
                  // This step will read hibernate.cfg.xml and prepare hibernate for use
                  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
                   session =sessionFactory.openSession();
                        object
                   org.hibernate.Transaction tr = session.beginTransaction();
                         System.out.println("Inserting Record");
                        Contact contact = new Contact();
                        contact.setId(13);
                        contact.setFirstName("sai11");
                        contact.setLastName("baba11");
                        contact.setEmail("baba11@gmail.com");
                        session.save(contact);
                        tr.commit();
                        System.out.println("Done");
            }catch(Exception e){
                  System.out.println(e.getMessage());
            }finally{
                  
                  session.flush();
                  session.close();

                  }
            
      }
}


Please advise on why annotation one does not work on oracle
0
 
LVL 7

Author Comment

by:gudii9
ID: 26247595
Hi,

I found the issue

in hibernate.cfg.xml file dialect i have not changed to oracle still pointing to old mysql. After changing everything working fine
0
 
LVL 7

Author Closing Comment

by:gudii9
ID: 31674704
Thank you very much. I appreciate it
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
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…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Suggested Courses
Course of the Month17 days, 11 hours left to enroll

829 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