Question

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);
Was it helpful?

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>

OTHER TIPS

my english is not good but, you may have a column in your database table that is not defined in the entity class code, (self experience), if you touch a table "manually", for example, using a graphic interface like Heidi, and then you make changes in the entity class, is possible that the old column still in the table even if you don't use it in the code. So if you have attribute1, attribute2 and attribute3 in your entity class, you going to insert data through them, but there is a fieldX that exist in your table and there is neither a method to set/get or a default value defined, so when you try to insert, this "fieldX" sends an exception: "Field 'fieldX' doesn't have a default value". I fixed the problem supressing the table and re executing hibernate, then fieldX dissapear.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top