简体   繁体   English

从休眠拦截器获取实体字段注释

[英]Get entity field annotations from hibernate interceptor

I need to do some additional business logic for specified filed (with a custom annotation) after hibernate load this entity. 休眠加载该实体后,我需要为指定的字段(带有自定义注释)做一些其他业务逻辑。 So, I created a hibernate interceptor like this. 因此,我创建了一个像这样的休眠拦截器。 But what confused me is that I can't get the annotation information. 但是令我困惑的是我无法获得注释信息。 The encryptAnnotation is always null in the following codes. 在以下代码中,encryptAnnotation始终为null。

public class HibernateInterceptor extends EmptyInterceptor {

    public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        for (int i = 0; i < types.length; i++) {
            Type type = types[i];
            if (type instanceof StringType) {
                StringType stringType = (StringType) types[i];
                Encrypt encryptAnnotation = stringType.getJavaTypeDescriptor().getJavaTypeClass().getAnnotation(Encrypt.class);
                if (encryptAnnotation != null) {
                    //todo: decrypt field
                    return true;
                }
            }
        }
        return false;
    }
}

Here is the Entity and annotation definition: 这是实体和注释定义:

@Entity
@Table(name = "table_name")
public class Trade implements Serializable {
    @Encrypt
    private String shiptoAddr;
}


@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Encrypt {
}

You are trying to obtain the annotation from the mapping information and basically in the end you are trying to find the annotation on the String class, that is obviously not going to work. 您试图从映射信息中获取注释,并且基本上最后您试图在String类上找到注释,这显然是行不通的。

Instead you need to detected all fields on the passed in entity object and check if the annotation is present on a field. 相反,您需要检测传入的entity对象上的所有字段,并检查字段中是否存在注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM