代码示例:
Converter class:
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import
com.yxt.qida.im.api.common.QidaConstants;
import
com.yxt.qida.im.api.repo.TrainingRepositoryImpl;
//@Converter(autoApply = true)
@Converter
public class OracleDate2StringConverter
implements
AttributeConverter {
final static SimpleDateFormat DateFormater = new
SimpleDateFormat(
DEFAULT_TIME_FORMAT_YYYY_MM_DD_HH_MM_SS);
@Override
public Date convertToDatabaseColumn(String attribute) {
Date date = null;
if (StringUtils.isNotBlank(attribute)) {
try {
date = DateFormater.parse(attribute);
} catch (Exception e) {
LOGGER.error("Error to format time:" + attribute, e);
}
}
return date;
}
@Override
public String convertToEntityAttribute(Date dbData) {
String value = null;
if (dbData != null) {
Date date = new Date(dbData.getTime());
try {
value = DateFormater.format(date);
} catch (Exception e) {
LOGGER.error("Error to format time:" + dbData, e);
}
}
return value;
}
}
Entity:
public class entityclass{
@Column(name = "ENDTIME")
@Convert(converter =
OracleDate2StringConverter.class)
public String getEndtime() {
return endtime;
}
public void setEndtime(String endtime) {
this.endtime = endtime;
}
private String endtime;
}