Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Ignore Certain Fields in unit tests, Hibernate

I have the following field in my entity model.

@Column(name="key")
@ColumnTransformer(
        read="AES_DECRYPT(key, SHA1('passcode'))", 
        write="AES_ENCRYPT(?, SHA1('passcode'))")
private String secret_key;

I am using MySql database and hibernate will perfectly encrypt/decrypt the key value with AES_ENCRYPT and AES_DECRYPT function. However, the spring embedded databases (HSQL or H2) doesn't know about this specific MySql functions. It throws the following error:

 javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not insert: [com.xxx.Table]
    at ...

Caused by: org.hibernate.exception.SQLGrammarException: could not insert: [com.xxx.Table]
    at ...

Caused by: java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: AES_ENCRYPT

So my question is,

  1. How can I tell hibernate to ignore this field from writing in certain databases. OR
  2. How can I get HSQL and/or H2 work with this mysql function.

Thank you

like image 478
Kid F Avatar asked Oct 21 '25 08:10

Kid F


1 Answers

add this class to your test config:

@Component
public class RemoveAesFunction {



    @PostConstruct
    public void postConstruct() {
        setKey(MyEntity.class);
    }

    private void setKey(Class<?> clazz) {
        try {
            Field field = clazz.getDeclaredField("firstName");

            ColumnTransformer columnTransformer = field.getDeclaredAnnotation(ColumnTransformer.class);
            updateAnnotationValue(columnTransformer, "read","");
            updateAnnotationValue(columnTransformer, "write","?");
        } catch (NoSuchFieldException | SecurityException e) {
            throw new RuntimeException();
        }
    }

    @SuppressWarnings("unchecked")
    private void updateAnnotationValue(Annotation annotation, String annotationProperty,String value) {
        Object handler = Proxy.getInvocationHandler(annotation);
        Field merberValuesField;
        try {
            merberValuesField = handler.getClass().getDeclaredField("memberValues");
        } catch (NoSuchFieldException | SecurityException e) {
            throw new IllegalStateException(e);
        }
        merberValuesField.setAccessible(true);
        Map<String, Object> memberValues;
        try {
            memberValues = (Map<String, Object>) merberValuesField.get(handler);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new IllegalStateException(e);
        }

        memberValues.put(annotationProperty, value);
    }
}
like image 63
DD. Avatar answered Oct 23 '25 22:10

DD.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!