我很难从java类向数据库表插入数据。我得到“内部异常:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列'id'不能为空”...我做了一些挖掘,无法弄明白。让我发布我的代码...在此之前我解释我想要做什么...这个项目包含Servlet类,JSP和java类。我正在使用JSP html Form来获取数据并将它们记录到数据库中。这里的代码......
@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;
和我的服务类是......
@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 = ?")
答案 0 :(得分:1)
似乎您尝试保留您的实体并且其ID仍为null。这就是为什么你得到一个约束违规错误。
要简单地解决此错误,我建议您尝试使用id上的自动增量选项创建数据库表。它应该可以解决你的问题。
答案 1 :(得分:0)
它表示通过调用将“id”列插入到数据库中的供应数据(来自某些源和与“id”的db字段类型匹配的类型)。在某处您没有向代码中的查询提供“id”数据。
答案 2 :(得分: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。因此,您将无法创建将实例设置为null的Leave实例。
答案 3 :(得分:0)
答案 4 :(得分: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;
}
答案 5 :(得分:0)
我想出了我的问题,谢谢你们的帮助。我以这种方式解决了我的问题... eclipselink需要我的数据库上的序列表,我创建了一个然后它工作...再次感谢你:)