Search code examples
javahibernateormhibernate-mapping

Hibernate GenericJDBCException : Field 'KeyID' doesn't have a default value


Hi I am trying to create one to many relationship with string object with the different key id on same table.

But when i insert the data it will show the exception "General error message from server: "Field 'qid' doesn't have a default value".

How to resolve the problem in hibernate. Please refer the below code.

     <class name="com.db.HRQuestion" table="HRQuestion">
      <id name="id">
      <generator class="increment"></generator>
      </id>
      <property name="qname"></property>
      <list name="answers" table="answer">
        <key column="qid"></key>
        <index column="type"></index>
        <element column="answer" type="string"></element>
      </list>
       </class>
      <class name="com.db.JavaQuestion" table="javaQuestion">
        <id name="id">
            <generator class="increment"></generator>
         </id>
        <property name="qname"></property>

        <list name="answers" table="answer">
             <key column="java_qid"></key>
            <index column="type"></index>
            <element column="answer" type="string"></element>
        </list>

    </class>

Java code is :

 JavaQuestion javaQuestion= new JavaQuestion();
javaQuestion.setQname("What is meant by java?");
ArrayList<String> javaanswerlist=new ArrayList<String>();
javaanswerlist.add("java is Object oriented programming ");
javaanswerlist.add("java is a platform independent");
javaQuestion.setAnswers(javaanswerlist);

HRQuestion hrquestion=new HRQuestion();
hrquestion.setQname("Hr Question one");
ArrayList<String> list2=new ArrayList<String>();
list2.add("My profile .....");
list2.add("My objetcive...");
hrquestion.setAnswers(list1);

session.save(javaQuestion);
session.save(hrquestion);

Solution

  • As you map two lists of Answers to the same table, you have to define both key column qid and java_qid as nullable.

    <key column="qid" not-null="false"></key>
    ....
    <key column="java_qid" not-null="false"></key>