* 使用方法:
* 在实体类上增加
* \@TypeDef(name="interval", typeClass = IntervalType.class)
* 在字段定义上增加:
* \@Type(type = "interval")
*
* http://stackoverflow.com/questions/1945615/how-to-map-the-type-interval-in-hibernate/6139581#6139581
*
* @version 1.0
* @since 1.0
*/
public class IntervalType implements UserType {
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}
public Object deepCopy(Object value) throws HibernateException {
return value;
}
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
public boolean equals(Object arg0, Object arg1) throws HibernateException {
return arg0 != null && arg1 != null && arg0.equals(arg1) || arg0 == null && arg1 == null;
}
public int hashCode(Object object) throws HibernateException {
return object.hashCode();
}
@Override
public Object nullSafeGet(ResultSet resultSet, String[] names, SharedSessionContractImplementor sessionImplementor, Object o) throws HibernateException, SQLException {
String interval = resultSet.getString(names[0]);
if (resultSet.wasNull() || interval == null) {
return null;
}
PGInterval pgInterval = new PGInterval(interval);
return getDuration(pgInterval);
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor sessionImplementor) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.OTHER);
} else {
//this http://postgresql.1045698.n5.nabble.com/Inserting-Information-in-PostgreSQL-interval-td2175203.html#a2175205
Duration duration = (Duration) value;
st.setObject(index, getInterval(duration), Types.OTHER);
}
}
public static Duration getDuration(PGInterval pgInterval) {
return Duration.ofSeconds(pgInterval.getDays() * 24 * 3600 +
pgInterval.getHours() * 3600 +
pgInterval.getMinutes() * 60 +
(int) pgInterval.getSeconds());
}
private static PGInterval getInterval(Duration value) {
long seconds = value.getSeconds();
int days = (int) (seconds / (24 * 3600));
seconds -= days * 24 * 3600;
int hours = (int) (seconds / 3600);
seconds -= hours * 3600;
int minutes = (int) (seconds / 60);
seconds -= minutes * 60;
seconds = Math.abs(seconds);
return new PGInterval(0, 0, days, hours, minutes, seconds);
}
public boolean isMutable() {
return false;
}
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
public Class returnedClass() {
return Duration.class;
}
public int[] sqlTypes() {
return new int[]{Types.OTHER};
}
}
使用自定义类型
至此,我们已经定义好了自己的数据类型。但Hibernate还不知道怎么使用它。为此,我们需要通过在Entity上使用使用TypeDef注解,并在属性上使用Type注解。
比如:
...
@Entity
@TypeDef(name = "interval", typeClass = IntervalType.class)
public class PaperStatis implements Serializable {
...
@Column(name = "avg_duration")
@Type(type = "interval")
public Duration getAvgDuration() {
return this.avgDuration;
}
...
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
QQ客服
公众号
手机版
帮助中心