在Spring MVC中自动生成id

时间:2016-04-03 17:48:36

标签: java spring postgresql jpa

我正在尝试保存数据库中的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注释是否是正确的做法?

1 个答案:

答案 0 :(得分:3)

  

现在我正在尝试自动生成id值,但我有一点点   对如何正确地做到这一点感到困惑

如果您想自动生成id,请不要提供一个,即使它是null。因此,请从id方法中删除addProduect

@Override
public void addProduct(String description, double price, Date date) {
    jdbcTemplate.update("INSERT INTO products values(?, ?, ?)", description, price, date);
}

另外,请制作id字段auto-increment,如此question

或者,更改addProduct方法并使用EntityManager#persist方法:

@Override
public void addProduct(Product product) {
    entityManager.persist(product);
}

关于错误:

  

错误:列“id”中的空值违反了非空约束

由于您的表单未从客户端获取id值,因此/newproduct端点的Productnullid

@RequestMapping(value = "/newproduct", method = RequestMethod.POST)
public ModelAndView submitForm(@ModelAttribute("product") Product product) { ... }

然后将此null值作为参数传递给addProduct方法:

prDao.addProduct(product.getId(), ...)

最后addProduct会尝试将null值保存为主键的值,该值具有非空约束,所以你得到了那个错误。

此外,使用 Entity 对象作为与客户端通信的方式,例如Product,不是一个好习惯。尝试定义一些辅助抽象,如表单或DTO,并将它们用于表单处理或响应组装。

相关问题