I am having a field - expiryLimit in my Item entity for which I thought of using joda-time Period which would be an appropriate type to use here.
Just to explain - expiryLimit is the number of year, month, days, or any duration after which a particular item will expire and using which I can calculate the exact expiryDate of an Item given a deliveryDate.
Now the problem I'm facing is finding an appropriate way to map this type into JPA.
Is there any available API or 3rd party library which provides some annotation to do that? Also I've used the Eclipse Link @Converter annotation to map DateTime with MySQL TimeStamp. So, would I need to do the same thing with Period also. And if yes, then to what type should I convert it. To varchar? or to Long? or some other type appropriate to represent a Period.
Ok, finally I've solved the issue by using EclipseLink @Converter only. This is how I've done it. I also welcome any comments on this way: -
public class ItemMaster {
@Converter(
name="periodConverter",
converterClass = com.joda.converter.PeriodConverter.class
)
@Convert("periodConverter")
@Column(name = "expiry_limit", length = 2000)
private Period expiryLimit;
/** Constructors **/
public Period getExpiryLimit() {
return expiryLimit;
}
public void setExpiryLimit(Period expiryLimit) {
this.expiryLimit = expiryLimit;
}
}
public class PeriodConverter implements Converter {
private Logger log;
private static final long serialVersionUID = 1L;
@Override
public Object convertDataValueToObjectValue(Object str, Session session) {
if (str == null) {
log.info("convertDataValueToObjectValue returning null");
return null;
}
return new Period(str);
}
@Override
public Object convertObjectValueToDataValue(Object period, Session session) {
/** str format should be: - `PyYmMwWdDThHmMsS` **/
if (period == null) {
log.info("convertObjectValueToDataValue returning null");
return null;
}
return period.toString();
}
@Override
public void initialize(DatabaseMapping mapping, Session session) {
log = Logger.getLogger("com.joda.converter.PeriodConverter");
((AbstractDirectMapping) mapping).setFieldType(java.sql.Types.VARCHAR);
}
@Override
public boolean isMutable() {
return true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With