0

My Model Class:

        package com.igate.model;

        import java.util.Date;
        //import java.sql.Date;
        import java.sql.Timestamp;

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

        @Entity
        @Table(name="Employee")
        public class Employee
        {
            @Id
            @Column(name="empid")
            @GeneratedValue(strategy=GenerationType.IDENTITY)
            int         id;

            @Column(name="empname")
            String      name;

            String      job;
            Date        hiredate;
            int         sal;
            int         deptid;
            public int getId() {
                return id;
            }
            public void setId(int id) {
                this.id = id;
            }
            public String getName() {
                return name;
            }
            public void setName(String name) {
                this.name = name;
            }
            public String getJob() {
                return job;
            }
            public void setJob(String job) {
                this.job = job;
            }
            public Date getHiredate() {
                return hiredate;
            }
            public void setHiredate(Date hiredate) {
                this.hiredate = hiredate;
            }
            public int getSal() {
                return sal;
            }
            public void setSal(int sal) {
                this.sal = sal;
            }
            public int getDeptid() {
                return deptid;
            }
            public void setDeptid(int deptid) {
                this.deptid = deptid;
            }
            public void setHiredate(Timestamp hiredate) {
                this.hiredate = hiredate;
            }

        }

My cfg file:

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-configuration SYSTEM 
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

    <hibernate-configuration>
        <session-factory>
            <!--connection properties  -->
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
            <property name="connection.username">root</property>
            <property name="connection.password">MenhiBaba</property>

            <!--hibernate properties  -->
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
            <property name="hb2ddl.auto">validate</property>
            <property name="show_sql">true</property>
            <!-- <property name="use_sql_comments">true</property>
            <property name="format_sql">true</property>
             -->
            <!-- Resource mapping -->
            <mapping class="com.igate.model.Employee"/>
        </session-factory>
    </hibernate-configuration>

My Error:

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 Employee (deptid, hiredate, job, empname, sal) values (?, ?, ?, ?, ?)
problem in creating session object
Exception in thread "main" java.lang.ExceptionInInitializerError
    at Test.main(Test.java:37)
Caused by: org.hibernate.exception.GenericJDBCException: could not insert: [com.igate.model.Employee]
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.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 Test.main(Test.java:27)
Caused by: java.sql.SQLException: General error,  message from server: "Field 'empid' doesn't have a default value"
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1977)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1163)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1272)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:2236)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1741)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1588)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
    ... 16 more

Main method:

import java.sql.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.igate.model.Employee;
import com.igate.utils.HibernateUtils;


public class Test 
{
    public static void main(String[] args) {
        Session session =null;
        Transaction txn = null;
        try
        {
            session = HibernateUtils.getSessionFactory().openSession();
            txn = session.beginTransaction();
            txn.begin();
            Employee emp = new Employee();
            emp.setId(101);
            emp.setName("Rahim");
            emp.setJob("PO");
            emp.setHiredate(new Date(24-11-2011));
            emp.setSal(5500);
            emp.setDeptid(20);
            int i=(Integer)session.save(emp);
            if(i>=0)
                System.out.println("data saved");
            else
                System.out.println("data not saved");
            txn.commit();
            session.close();
        }catch(Exception e)
        {
            System.out.println("problem in creating session object");
            throw new ExceptionInInitializerError(e);
        }
    }
}

Before this i executed many programs but i did not get any problem.but i don't know what is problem in my code.i expended 2 hours on this simple program. Please anybody can help me ?

Thanks in advance.

anand mishra
  • 900
  • 1
  • 11
  • 30
  • Why do you assign a value to an auto-generated field using `emp.setId(101);`? – Tiny Jan 08 '16 at 01:14
  • It appears that you forgot to add `AUTO_INCREMENT` in MySQL while creating the associated table. Thus, the key is not auto-generated as expected by `@GeneratedValue(strategy=GenerationType.IDENTITY)`. – Tiny Jan 08 '16 at 01:21
  • If we don't use in this case Hibernate will create it automatically. – vicky kumar jaiswal Jan 08 '16 at 02:49
  • i assigned emp.setId(101) to check it will override by the hibernate or not. – vicky kumar jaiswal Jan 08 '16 at 02:51
  • An auto-generated primary key is necessary on the back-end side `CREATE TABLE Employee (id int(11) unsigned NOT NULL AUTO_INCREMENT ...)`, if `@GeneratedValue(strategy=GenerationType.IDENTITY)` is used on the fornt-end side. If an auto-generated key is however, not needed in your case, then drop it on both the sides - Hibernate as well as MySQL and assign an `id` manually like `emp.setId(101);`, when an entity corresponding to a row in that table is to be persisted. – Tiny Jan 08 '16 at 03:07

1 Answers1

0

Set the auto increment field to NULL or 0 if you want it to be automatically assigned. For more details see How to insert data to MySQL having auto incremented primary key?

Community
  • 1
  • 1
anand mishra
  • 900
  • 1
  • 11
  • 30