服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - java扩展Hibernate注解支持java8新时间类型

java扩展Hibernate注解支持java8新时间类型

2019-11-19 14:43java教程网 JAVA教程

这篇文章主要介绍了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;
    }
}

 

延伸 · 阅读

精彩推荐