0

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 = ?")
3
  • I'm getting same error " Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.4.v20160829-44060b6): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'train_schedule_id' cannot be null Error Code: 1048 Call: INSERT INTO train_station (id, date, name, sequence, train_schedule_id) VALUES (?, ?, ?, ?, ?) bind => [null, null, NY, null, null] Query: InsertObjectQuery(com.test.temp.core.data.TrainstationData@12b0565e) Commented Jul 22, 2018 at 13:23
  • could you please support me to figure it out... Commented Jul 22, 2018 at 13:25
  • do you have a DDL for SEQUENCE table ? Commented Jul 22, 2018 at 14:34

6 Answers 6

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

It means supply data(from some source and of a type that matches the db field type for "id") for the "id" column to insert into the database with the call. Somewhere you are not supplying and "id" data to the query in your code.

Comments

0

Add

@GeneratedValue(strategy = GenerationType.AUTO)

to your Leave ID

@Id
@Column(name="id",nullable=false,updatable=false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

or create Leave constructor with Long Id arg to set your id. So, you wont be able to create Leave instance with id set to null.

Comments

0

Is it missing GeneratedValue annotation in id field?

If you use AUTO generation, the id generation will be depend on Persistence Provider. You might need to set auto increment for primary key.

@Entity
@Table(name="Leave")
public class Leave implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id",nullable=false,updatable=false)
    private Long id;

    @OneToOne
    @GeneratedValue(strategy = GenerationType.AUTO) --> remove this code
    @JoinColumn(name = "person_id", referencedColumnName="id")
    private Person person;

}

Comments

0

You are not setting the id in your code and you are not telling your JPA provider to generate it either.

You can use the @GeneratedValue annotation to tell your JPA provider to generate your id.

Here is an example

3 Comments

seems like he isn't even using Hibernate either ;-) but yes, GeneratedValue is missing from Leave class
Yep u are correct. I did that and im getting these error :S and i have not a clue why it is sequence.. i dont have any table like that and also dont wat to create like that...
@Pitch you don't have to use @GeneratedValue(strategy=GenerationType.SEQUENCE... You can simply use @GeneratedValue(strategy = GenerationType.IDENTITY)
0

I figure it out my problem thank you guys for help. I solved my problem in that way... eclipselink needs sequence table on my database and i created one then it works... Thank you again :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.