Insert/select joda-time date types into/from datab

2019-08-31 03:20发布

问题:

What's the best way to insert jodatime objects into database using JDBC, and how to get them from it? I used to use MutableDateTime, and covert it into Timestamp before insert. But when I want to get my data from database, i got an issue.. i dont know how to do it, and how to parse types. So once again: how to insert and select Joda-Time objects into/from database.

回答1:

You can use an ORM that supports custom types. For example, sormula Joda Time example. Implement a TypeTranslator like LocalDateTranslator and all uses of corresponding class, LocalDate, will use type translator to convert to/from column in db.

@ExplicitType(type=LocalDate.class, translator=LocalDateTranslator.class)
public class StudentLD
{
    int id;
    String firstName;
    String lastName;
    LocalDate graduationDate;
...


回答2:

If you have a Timestamp, and want to convert it back to a MutableDateTime, you just need

new MutableDateTime(timestamp.getTime());


回答3:

JodaTime objets are more expressive than the DateTime datatypes than SQL and most (if not all) databases support, hence there is no general foolproof recipe. Related question