【发布时间】:2016-07-23 04:24:55
【问题描述】:
我正在尝试将 JSP 页面收集的数据保存在数据库 (Postgres) 中。起初我尝试在表单中手动插入任何值(包括id),并且将数据保存在我的数据库中没有问题。现在我正在尝试自动生成id 值,但我对如何正确执行它有点困惑。
我的模型 - 产品
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String description;
private double price;
@DateTimeFormat(pattern = "dd/MM/yyyy")
private Date date;
public Product() { }
public Product(Long id, String description, double price, Date date) {
this.id = id;
this.description = description;
this.price = price;
this.date = date;
}
//getters and setters
}
我的控制器 - DBConnection
@Controller
public class DBConnection {
@Autowired
private ProductDao prDao;
@RequestMapping(value = "/newproduct", method = RequestMethod.GET)
public ModelAndView showForm() {
Product product = new Product();
return new ModelAndView("newproduct", "product", product);
}
@RequestMapping(value = "/newproduct", method = RequestMethod.POST)
public ModelAndView submitForm(@ModelAttribute("product") Product product) {
ModelAndView mav = new ModelAndView();
prDao.addProduct(product.getId(), product.getDescription(), product.getPrice(), product.getDate());
mav.setViewName("product");
mav.addObject("product", product);
return mav;
}
}
ProductDaoImpl
public class ProductDaoImpl implements ProductDao {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
@Override
public void setDataSource(DataSource ds) {
this.dataSource = ds;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public void addProduct(Long id, String description, double price, Date date) {
jdbcTemplate.update("INSERT INTO products values(?, ?, ?, ?)", id, description, price, date);
}
}
我在 newproduct.jsp 中的表单
<form:form method="POST" action="newproduct" modelAttribute="product">
<table>
<tr>
<td><form:label path="description">Description</form:label></td>
<td><form:input path="description" /></td>
</tr>
<tr>
<td><form:label path="price">Price</form:label></td>
<td><form:input path="price" /></td>
</tr>
<tr>
<td><form:label path="date">Date (dd/mm/yyyy)</form:label></td>
<td><form:input path="date" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
提交表单时出错
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [INSERT INTO products values(?, ?, ?, ?)]; ERROR: null values in column "id" violates not-null constraint
Detail: The row contains error (null, nnvfe, 10.00, 2010-10-10).; nested exception is org.postgresql.util.PSQLException: ERROR: null values in column "id" violates not-null constraint
Detail: The row contains error (null, nnvfe, 10.00, 2010-10-10).
我认为问题出在addProduct 方法中:当我尝试获取id 值时,它尚未创建。
如何实现自动生成的 ID? JPA 注释是做那件事的正确方法吗?
【问题讨论】:
-
您似乎在混合 JPA 和 JDBC。任选其一。
-
是的,因为我总是将 JPA 与 JSF 一起使用。我是 Spring 新手,很困惑。现在我解决了我的问题,感谢阿里的回答
标签: java spring postgresql jpa