这就是我在 Java、MySQL db 和 OpenJPA2 中处理日期时间字段的方式。我希望字段是 java.util.Calendar 类型,dbfield datetime 和 dbvalue 作为 UTC 值。Mysql 对时区一无所知,因此使用自定义转换器可以设置和读取“yyyy-MM-dd HH:mm:ss”字符串。仍然是实体 bean 中的有效日期时间 sql 列和 java.util.Calendar。
@Entity @Table(name="user") @Access(AccessType.FIELD)
public class User {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private long id; // primary key (autogen surrogate)
private String name;
@Column(name="updated_utc") // use custom serializer so that UTC-stringified
@Temporal(TemporalType.TIMESTAMP) // db datetime is properly set to calendar instance
@Factory("JPAUtil.db2calendar") @Externalizer("JPAUtil.calendar2db")
private Calendar updated;
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name=name; }
public Calendar getUpdated() { return updated; }
public void setUpdated(Calendar cal) { updated=cal; }
}
- - -
public class JPAUtil {
public static final TimeZone TIMEZONE_UTC = TimeZone.getTimeZone("UTC");
public static String calendar2db(Calendar val, StoreContext ctx) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TIMEZONE_UTC);
return df.format(cal.getTime()); // return date as UTC string value
}
public static Calendar db2calendar(String val, StoreContext ctx) {
try {
// returned calendar is using a default timezone, val was set as utc string
return DateUtil.parseDateTimeFromUTC(val);
} catch (Exception ex) {
return null;
}
}
}
- - -
CREATE TABLE user (
id bigint NOT NULL auto_increment,
name varchar(64) NOT NULL default '',
updated_utc datetime NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY USERNAME (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
ps:DateUtil 是我的随机工具类,提供一些基本的转换。