简体   繁体   中英

JPA AttributeConverter comparison?

I'm looking for an easy way to query a database column of type string in format YYYYMMDD. This could be done with a native query like:

select * from TPRODUCT where to_date(ENDOFPRODUCTION, 'YYYYMMDD') > CURRENT_DATE;

But is there a way to achieve this comparison with an AttributeConverter

@NamedQuery(name = "product.filterByEOP", query =
    "select p from Product p where p.eop > :currentDate")

Well, it turns out you can. In case anyone else is looking into this, after checking the reference I ended up with:

public class DateConverter implements AttributeConverter<Date, String> {

    private final String DATE_FORMAT = "YYYYMMDD";

    @Override
    public String convertToDatabaseColumn(Date date) {
        return new SimpleDateFormat(DATE_FORMAT).format(date);
    }

    @Override
    public Date convertToEntityAttribute(String dateString) {
        Date converted = null;
        try {
            converted = new SimpleDateFormat(DATE_FORMAT).parse(dateString);
        } catch (ParseException ex) {
        }
        return converted;
    }
}

which you can then use on an entity attribute:

@Column(name = "ENDOFPRODUCTION")
@Convert(converter = DateConverter.class)
private Date eop;

and use the query:

final TypedQuery<Product> query = this.entityManager.createNamedQuery("product.filterByEOP", Product.class);
query.setParameter("currentDate", new Date());
List<Product> models = query.getResultList();

Why you don't convert your String to a date and use this last like it is :

String myDate = "20170607";
DateFormat format = new SimpleDateFormat("YYYYMMDD");
Date newDate = format.parse(myDate);

Now you can use :

query.setParameter("currentDate", newDate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM