com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null?

Pitch picture Pitch · Jul 29, 2013 · Viewed 16.8k times · Source

im having difficulty inserting datas to database table from java classes. I'm getting "Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null"... I did some digging and couldn't figure it out. Let me post my codes... before that i explain what i want to do... This project contains Servlet class,JSP , and java classes. I'm using JSP html Form to get datas and records them to into a database. Codes here...

    @Entity
    @Table(name="\"Leave\"")
    public class Leave implements Serializable{


/**
 * 
 */
private static final long serialVersionUID = 9088190714759727299L;

@Id
@Column(name="id",nullable=false,updatable=false)
private Long id;

//@OneToOne(mappedBy=)
@GeneratedValue(strategy = GenerationType.AUTO)
@JoinColumn(name = "person_id",referencedColumnName="id")
private Person person;


//@Enumerated(LeaveType)
@Column(name="leavetype")
private LeaveType leavetype;

@Temporal(TemporalType.DATE)
@Column(name="prepdate")
private Date prepdate;

@Temporal(TemporalType.DATE)
@Column(name="startdate")
private Date startdate;

@Temporal(TemporalType.DATE)
@Column(name="enddate")
private Date enddate;

@Temporal(TemporalType.DATE)
@Column(name="oldstartdate")
private Date oldStartdate;

@Temporal(TemporalType.DATE)
@Column(name="oldenddate")
private Date oldEnddate;

@Column(name="workday")
private String workday;

@Column(name="calendarday")
private String calendarday;

@Column(name="reason")
private String reason;

    getters setters....

        @Entity
          @Table(name="\"Person\"")
          public class Person implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 2532993385565282772L;
@Id
@Column(name="id",nullable=false,updatable=false)
@GeneratedValue(strategy = GenerationType.AUTO)

private Long id;
private String name;
private String surname;
private String sskno;
private String workstartdate;
private String address;
private String telno;

@OneToMany
private List<Leave> leaves;

AND MY SERVLET CLASS IS....

    @WebServlet("/LeaveServlet")
    public class LeaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
 private static final String PERSISTENCE_UNIT_NAME = "EmployeeLeaveForm";
  private static EntityManagerFactory emf;
public LeaveServlet() {
    super();
}

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager entityManager =  emf.createEntityManager();

    try {

        PrintWriter out = response.getWriter();
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/FormInterface.jsp");
        Person person = new Person();
        Leave leave = new Leave();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        Date date = new Date();
        String choosenType = request.getParameter("leavetype");


        // LEAVING
        // TYPES---------------------------------------------------------------------------------------------------


        if (choosenType == null) {

            request.setAttribute("leaveTypeError",
                    "Izin turunu giriniz.");
            requestDispatcher.forward(request, response);

            return;
        }

        else if (choosenType.equals(LeaveType.ANNUAL.toString())) {

            leave.setLeavetype(LeaveType.ANNUAL);

        } else if (choosenType.equals(LeaveType.MARRIAGE.toString())) {

            leave.setLeavetype(LeaveType.MARRIAGE);

        } else if (choosenType.equals(LeaveType.FEEDING.toString())) {

            leave.setLeavetype(LeaveType.FEEDING);

        } else if (choosenType.equals(LeaveType.MEDICAL.toString())) {

            leave.setLeavetype(LeaveType.MEDICAL);

        } else if (choosenType.equals(LeaveType.MATERNITY.toString())) {

            leave.setLeavetype(LeaveType.MATERNITY);

        } else if (choosenType.equals(LeaveType.OTHER.toString())) {

            leave.setLeavetype(LeaveType.OTHER);
            leave.setReason(request.getParameter("reason"));

            if (leave.getReason() != null) {

            } else if (leave.getReason() == null) {
                request.setAttribute("errorNoReason",
                        "Please enter a reason");
                requestDispatcher.forward(request, response);

                return;

            }

        } else if (choosenType.equals(LeaveType.UNPAID.toString())) {

            leave.setLeavetype(LeaveType.UNPAID);
            leave.setReason(request.getParameter("reason"));

            if (leave.getReason() != null) {

            } else if (leave.getReason() == null) {
                request.setAttribute("errorNoReason",
                        "Please enter a reason");
                requestDispatcher.forward(request, response);

                return;

            }

        }
        // PASSING PARAMETERS TO LOCAL
        // VARIABLES---------------------------------------------------------------------------

        String prepdate = dateFormat.format(date);
        String startdate = request.getParameter("startdate");
        String enddate = request.getParameter("enddate");
        String oldStartdate = request.getParameter("oldStartdate");
        String oldEnddate = request.getParameter("oldEnddate");

        person.setName(request.getParameter("name"));
        person.setSurname(request.getParameter("surname"));
        person.setSskno(request.getParameter("sskno"));
        person.setworkStartdate(request.getParameter("workStarted"));  // DBden
        person.setAddress(request.getParameter("address"));
        person.setTelno(request.getParameter("telephone"));

        leave.setCalendarday(request.getParameter("calendarday"));
        leave.setWorkday(request.getParameter("workday"));
            leave.setPrepdate(dateFormat.parse(prepdate));
        leave.setStartdate(dateFormat.parse(startdate));
        leave.setEnddate(dateFormat.parse(enddate));
        leave.setOldStartdate(dateFormat.parse(oldStartdate));
        leave.setOldEnddate(dateFormat.parse(oldEnddate));


        // Checking the consistency of the
        // time----------------------------------------------------------------------------

        if (((leave.getEnddate() != null) && (leave.getOldEnddate() != null))) {


            entityManager.getTransaction().begin();
            entityManager.persist(leave);
            entityManager.getTransaction().commit();

            //db den return
            //info

        }

        else {

            if (leave.getEnddate() == null) {

                request.setAttribute("errorMessage1", "Please enter dates correctly");

            }
            if (leave.getOldEnddate() == null) {

                request.setAttribute("errorMessage2", "Please enter date correctly");

            }

        requestDispatcher.forward(request, response);

        }



    } catch (Throwable exc) {
        System.out.println(exc);
    }
    finally {
        // Close the database connection:
        if (entityManager.getTransaction().isActive())
            entityManager.getTransaction().rollback();
        entityManager.close();
    }


}

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

}

}

And errors...

        [EL Info]: 2013-07-29 10:05:47.872--ServerSession(76232710)--EclipseLink, version: Eclipse Persistence Services - 2.5.0.v20130507-3faac2b
[EL Info]: connection: 2013-07-29 10:05:48.207--ServerSession(76232710)--file:/C:/Users/VAIO/Desktop/workspace - Kopya/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/EmployeeLeaveForm/WEB-INF/classes/_EmployeeLeaveForm login successful
[EL Warning]: 2013-07-29 10:05:48.292--UnitOfWork(1213364484)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null
Error Code: 1048
Call: INSERT INTO `Leave` (id, calendarday, enddate, leavetype, oldenddate, oldstartdate, prepdate, reason, startdate, workday, person_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    bind => [11 parameters bound]
Query: InsertObjectQuery(com.eteration.leavesystem.model.Leave@4fff5f4f)
javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null
Error Code: 1048
Call: INSERT INTO `Leave` (id, calendarday, enddate, leavetype, oldenddate, oldstartdate, prepdate, reason, startdate, workday, person_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    bind => [11 parameters bound]
Query: InsertObjectQuery(com.eteration.leavesystem.model.Leave@4fff5f4f)

I also use mysql and i created a database table.

WHY am I getting these exceptions.. And seriously i did digging but nothing work for me pls help me thanks...

EDIT-

    [EL Info]: 2013-07-29 11:05:56.944--ServerSession(624062858)--EclipseLink, version: Eclipse Persistence Services - 2.5.0.v20130507-3faac2b
[EL Info]: connection: 2013-07-29 11:05:57.283--ServerSession(624062858)--file:/C:/Users/VAIO/Desktop/workspace - Kopya/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/EmployeeLeaveForm/WEB-INF/classes/_EmployeeLeaveForm login successful
[EL Warning]: 2013-07-29 11:05:57.362--ClientSession(72318077)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'eteration.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
    bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'eteration.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
    bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")

Answer

RadASM picture RadASM · Jul 29, 2013

It seems you try to persist your entity and its id remains null. That's why your get a constraint violation error.

To simply solve this error I suggest you to try create your database table using auto-incrementation option on your id. It should solve your problem, I guess.