java扩展Hibernate注解支持java8新时间类型
扩展hibernate注解@creationtimestamp,@updatetimestamp支持java8新的时间类型
hibernate version: 4.3.5.final
package com.hibernate.annotation;
import org.hibernate.hibernateexception;
import org.hibernate.tuple.annotationvaluegeneration;
import org.hibernate.tuple.valuegenerator;
import java.lang.annotation.annotation;
import java.sql.time;
import java.sql.timestamp;
import java.time.localdate;
import java.time.localdatetime;
import java.time.localtime;
import java.util.calendar;
import java.util.date;
/**
* created with intellij idea.
* user: zhonggang
* date: 14-4-16
* time: 上午11:40
* <p/>
* 支持java8新的时间包
*
* @see java.time.localdatetime
* @see java.time.localdate
* @see java.time.localtime
*/
public abstract class abstracttimegeneration<a extends annotation> implements annotationvaluegeneration<a> {
protected valuegenerator<?> generator;
@override
public void initialize(a annotation, class<?> propertytype) {
if (localdatetime.class.isassignablefrom(propertytype)) {
generator = (session, owner) -> localdatetime.now();
} else if (localdate.class.isassignablefrom(propertytype)) {
generator = (session, owner) -> localdate.now();
} else if (localtime.class.isassignablefrom(propertytype)) {
generator = (session, owner) -> localtime.now();
} else if (java.sql.date.class.isassignablefrom(propertytype)) {
generator = (session, owner) -> new java.sql.date(new date().gettime());
} else if (time.class.isassignablefrom(propertytype)) {
generator = (session, owner) -> new time(new date().gettime());
} else if (timestamp.class.isassignablefrom(propertytype)) {
generator = (session, owner) -> new timestamp(new date().gettime());
} else if (date.class.isassignablefrom(propertytype)) {
generator = (session, owner) -> new date();
} else if (calendar.class.isassignablefrom(propertytype)) {
generator = (session, owner) -> {
calendar calendar = calendar.getinstance();
calendar.settime(new date());
return calendar;
};
} else {
throw new hibernateexception("unsupported property type for generator annotation " + annotation.getclass().getsimplename());
}
}
@override
public valuegenerator<?> getvaluegenerator() {
return generator;
}
@override
public boolean referencecolumninsql() {
return false;
}
@override
public string getdatabasegeneratedreferencedcolumnvalue() {
return null;
}
}