ID de geração automática no Spring MVC
Estou tentando salvar dados coletados por uma página JSP em um banco de dados (Postgres). No começo, tentei inserir qualquer valor manualmente (incluindoid
) em um formulário e não tive problemas para salvar os dados no meu banco de dados. Agora estou tentando gerar automaticamente oid
valores, mas estou um pouco confuso sobre como fazê-lo corretamente.
Meu modelo - Produto
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
}
Meu controlador - 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);
}
}
Meu formulário em 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>
Erro quando eu envio o formulário
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).
Eu acho que o problema está noaddProduct
método: oid
O valor ainda não foi criado quando tentei obtê-lo.
Como posso implementar um ID gerado automaticamente? A anotação JPA é a maneira correta de fazer isso?