简体   繁体   中英

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.

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.

Instead you need to detected all fields on the passed in entity object and check if the annotation is present on a field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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