Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate and MS SQL Server Identity column

I'm new to Hibernate and am unable to use an Identity column. When I run my java program using identity as generator, it gives the error that it "...cannot insert default or null value" in the identity column in the table. When I use increment as generator, it gives the error that "...identity_insert is set to off".

Can someone please guide me how to fix this issue so I can use Hibernate with my table? Please let me know if I need to provide any other information.

I'm using the following jars:

  • hibernate-commons-annotations-4.0.1.Final.jar
  • hibernate-core-4.1.9.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • sqljdbc4.jar

My Table:

Create Table ABC (
    Unique_Number int IDENTITY(1,1),
    Col1 varchar(100),
    Col2 char(10),
    CONSTRAINT pk_ABC_id PRIMARY KEY(Unique_Number)
)

hbm.xml:

<class name="org.data.ABCData" table="ABC">
    <meta attribute="class-description">This is a test class.</meta>
    <id name="uniqueNumber" type="int" column="Unique_Number">
        <generator class="identity"/> <!-- tried identity, increment -->
    </id>
    <property name="col1" column="Col1" type="string" length="100"/>
    <property name="col2" column="Col2" type="string" length="10"/>
</class>

ABC Element Class:

public class ABC {

    private int uniqueNumber;
    private String col1;
    private String col2;

    public int getUniqueNumber() {
        return uniqueNumber;
    }

    public void setUniqueNumber(int uniqueNumber) {
        this.uniqueNumber = uniqueNumber;
    }

    public int getCol1() {
        return col1;
    }

    public void setCol1(String col1) {
        this.col1 = col1;
    }

    public int getCol2() {
        return col2;
    }

    public void setCol2(String col2) {
        this.col2 = col2;
    }
}

hibernate.cfg.xml:

<hibernate-configuration>
 <session-factory>
  <property name="hibernate.connection.driver_class"></property>
  <property name="hibernate.connection.url"></property>
   <property name="hibernate.connection.username"></property>
   <property name="connection.password"></property>
   <property name="connection.pool_size">1</property>
   <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
   <property name="show_sql">false</property>
   <mapping resource="data.hbm.xml"/>
 </session-factory>
</hibernate-configuration>
like image 912
Gagan Singh Avatar asked Nov 03 '22 20:11

Gagan Singh


1 Answers

Try native as generator class

<id name="uniqueNumber" type="int" column="Unique_Number">
    <generator class="native"/> <!-- This will pick identity, sequence or hilo based on type -->
</id>
like image 191
shazin Avatar answered Nov 15 '22 08:11

shazin