Jin Kim
Jin Kim

Reputation: 17752

How do I read string as date using Spring + Hibernate?

My Hibernate named query calls a stored procedure which returns a date as a formatted string (e.g. "2017/03/15") as one of its columns.

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

Sample output from callilng stored procedure:

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

Trouble is that I would like to store this field as a Date instead of a String.

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

Is there any way for me to do this?

For reference, I am using Java 6 and Hibernate 3.5.

Upvotes: 0

Views: 373

Answers (2)

01000001
01000001

Reputation: 873

Simple code in setter may work:

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

Upvotes: 2

NAMS
NAMS

Reputation: 991

One of the constructors for the Date class is Date(int year, int month, int day).

So you can take your formatted string, split it with String.split("/"), and extract the appropriate fields to use in the constructor.

Upvotes: 0

Related Questions