java com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列“id”不能为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17918450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 19:36:33  来源:igfitidea点击:

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

javajpamysql-insert-id

提问by Pitch

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...

我很难将数据从 Java 类插入到数据库表中。我收到“内部异常:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列'id'不能为空”......我做了一些挖掘但无法弄清楚。让我发布我的代码...在此之前我解释一下我想要做什么...这个项目包含 Servlet 类、JSP 和 java 类。我正在使用 JSP html 表单来获取数据并将它们记录到数据库中。代码在这里...

    @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....

而我的 SERVLET 类是......

    @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.

我也使用 mysql 并创建了一个数据库表。

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 = ?")

回答by RadASM

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

看来您尝试保留您的实体并且其 id 保持为空。这就是为什么您会收到约束违规错误的原因。

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.

为了简单地解决这个错误,我建议您尝试在您的 id 上使用自动增量选项创建您的数据库表。我想它应该可以解决您的问题。

回答by nicephotog

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.

这意味着为“id”列提供数据(来自某个源并且类型与“id”的db字段类型匹配)以通过调用插入到数据库中。您没有在代码中向查询提供“id”数据的某处。

回答by Milan Baran

Add

添加

@GeneratedValue(strategy = GenerationType.AUTO)

to your Leave ID

到您的休假 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.

或使用 Long Id arg 创建 Leave 构造函数来设置您的 id。因此,您将无法创建 id 设置为 null 的 Leave 实例。

回答by M. Abbas

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

您没有id在代码中设置 ,也没有告诉 JPA 提供程序生成它。

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

您可以使用@GeneratedValue注释告诉您的 JPA 提供程序生成您的 ID。

Here is an example

这是一个例子

回答by Zaw Than oo

Is it missing GeneratedValueannotation in idfield?

是否缺少字段中的GeneratedValue注释id

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

如果您使用AUTOgeneration,则 id 生成将取决于Persistence Provider. 您可能需要为主键设置自动增量。

@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;

}

回答by Pitch

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 :)

我解决了我的问题,谢谢大家的帮助。我以这种方式解决了我的问题... eclipselink 需要我的数据库中的序列表,我创建了一个然后它就可以工作了...再次感谢您:)