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;
}
}
相关文章
Java、C++中子类对父类函数覆盖的可访问性缩小的区别介绍
这篇文章主要给大家介绍了关于Java、C++中子类对父类函数覆盖的可访问性缩小的区别的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。2018-01-01使用Spring Boot快速构建基于SQLite数据源的应用
为了提供一个单包易部署的服务器应用,考虑使用Spring Boot,因为其集成了Apache Tomcat,易于运行,免去绝大部分了服务器配置的步骤2017-08-08
最新评论