【发布时间】:2014-12-26 23:11:02
【问题描述】:
我正在尝试使用 DAO 模式创建一个简单的注册 Servlet,当我尝试将数据添加到数据库时出现异常。似乎 ID 出于某种原因没有获得价值,但为什么呢?
integrity constraint violation:
java.sql.SQLIntegrityConstraintViolationException NOT NULL check constraint;
SYS_CT_10092 table: CUSTOMER column: ID
数据库架构(使用 hsqldb):
CREATE SEQUENCE seq1 AS INTEGER START WITH 1;
CREATE TABLE customer (
id BIGINT NOT NULL PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
surname VARCHAR(255) NOT NULL,
code VARCHAR(255) NOT NULL,
);
INSERT INTO customer VALUES(NEXT VALUE FOR seq1,'Jane','Doe','123'); --test data
向数据库插入数据的Dao方法:
public void addCustomer(Customers c) {
try {
pst = getConnection().prepareStatement("insert into customer(first_name,surname,code)"
+ " values(?,?,?)");
pst.setString(1, c.getFirst_name());
pst.setString(2, c.getSurname());
pst.setString(3, c.getCode());
pst.executeUpdate();
} catch(Exception e) {
throw new RuntimeException(e);
} finally {
closeResources();
}
}
在servlet类中调用dao方法:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CustomerDao dao = new CustomerDao();
String firstname = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String code = request.getParameter("code");
Customers customer = new Customers();
customer.setFirst_name(firstname);
customer.setSurname(lastName);
customer.setCode(code);
dao.addCustomer(customer);
}
【问题讨论】: