0

我很难将数据从 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;

而我的 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 {

}

}

和错误...

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

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

为什么我会遇到这些异常......而且我真的在挖掘,但对我没有任何帮助,请帮助我,谢谢......

编辑-

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

6 回答 6

1

似乎您尝试保留您的实体,并且它的 id 仍然为空。这就是为什么您会遇到约束违规错误。

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

于 2013-07-29T07:48:42.630 回答
0

字段中是否缺少GeneratedValue注释id

如果您使用AUTO生成,则 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;

}
于 2013-07-29T08:09:42.607 回答
0

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

于 2013-07-30T06:43:57.983 回答
0

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

于 2013-07-29T07:49:03.680 回答
0

添加

@GeneratedValue(strategy = GenerationType.AUTO)

到您的休假 ID

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

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

于 2013-07-29T07:53:00.383 回答
0

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

您可以使用@GeneratedValue注释告诉您的 JPA 提供者生成您的 id。

这是一个例子

于 2013-07-29T07:54:47.367 回答