如何使用Spring + Hibernate读取字符串作为日期?

时间:2017-03-15 18:49:01

标签: java hibernate

我的Hibernate命名查询调用一个存储过程,该存储过程将日期作为格式化字符串(例如" 2017/03/15")作为其列之一返回。

<sql-query name="myReportQuery">
    <return alias="myReportQuery" class="com.example.report.ReportLine" />
    { call sproc_report( :fromDate, :toDate) }
</sql-query>

来自callilng存储过程的示例输出:

Date        Item    Price  Qty
----        ----    -----  ---
2017/01/22  Banana  0.75   10
2017/02/15  Apple   1.00   5
2017/02/25  Pear    1.50   8
2017/03/05  Apple   1.00   15

麻烦的是我想把这个字段存储为Date而不是String。

public class ReportLine {
    private Date date;
    private String item;
    private BigDecimal price;
    private int quantity;
}

我有什么方法可以这样做吗?

供参考,我使用的是Java 6和Hibernate 3.5。

2 个答案:

答案 0 :(得分:2)

setter中的简单代码可能有效:

String sDate1="31/12/1998";  
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);

答案 1 :(得分:0)

Date类的一个构造函数是Date(int year, int month, int day)

因此,您可以使用格式化的字符串,将其与String.split("/")分开,并提取要在构造函数中使用的相应字段。