保存日期

时间:2018-04-01 04:52:50

标签: java sql date jdbc

我正在使用H2数据库和Date数据类型我正在使用spring Mvc in和我的模型我正在使用java.sql.date为我的pojo,我写了一个添加新订单方法,看起来像这样

    public final Order addOrder(Order order) {
        LOGGER.debug("addOrder({})", order);
        MapSqlParameterSource
        namedParameters = new MapSqlParameterSource();

        namedParameters.addValue("petrolQty",
                order.getPetrolQty());

        namedParameters.addValue("price",
                order.getPrice());

        namedParameters.addValue("orderDate",
                order.getOrderDate());

        namedParameters.addValue("truckId",
                order.getTruckId());

        KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
        namedParameterJdbcTemplate
                .update(addOrderSql,
                        namedParameters, generatedKeyHolder);
        order.setOrderId(generatedKeyHolder.getKey().intValue());
        return order;
    }

所以我写了一个解析的测试,但是当我在最后一行调试时,我得到一个java.text.parsedException这里是我的测试,我可以更好地进行日期转换吗?

private static final String DATE = "2006-1-21";

    @Autowired
    private OrderDao orderDao;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

 @Test
    public void addOrder() throws ParseException {
        Collection<Order> orders = orderDao.getAllOrders();
        int sizeBefore = orders.size();

        Date dd =  formatter.parse(DATE);
        java.sql.Date sqlDate = new java.sql.Date(dd.getTime());

        Order order = new Order(234.3, 342.2,sqlDate , 1);
        Order order1 = orderDao.addOrder(order);
        Assert.assertNotNull(order1);


    Assert.assertTrue(order.getOrderDate().equals(formatter.parse("2006-1-21")));**excetion thrown here java.text.parsedException during debug only.
            Assert.assertTrue((sizeBefore+1) == orderDao.getAllOrders().size());

在最后一行我在调试期间得到异常,但是在它实际保存到db之后,还有什么更好的方法来处理这个日期?谢谢 我的订单类 *订单日期是java.sql.Date

public class Order {
    private Integer orderId;
    private Double petrolQty;
    private Double price;
    private Date orderDate;

    private Integer truckId;
    public Order() {
    }
    public final Integer getOrderId() {
        return orderId;
    }

sql -order.add =

INSERT INTO orderz (petrolQty, price, orderDate, truckId) values (:petrolQty,:price, :orderDate, :truckId)

0 个答案:

没有答案