[英]JPA: Using AttributeConverter in @Query
I wrote my own AttributeConverter to encrypt and decrypt ByteArrays based on thoughts-on-java and looks similar to:我写了我自己的 AttributeConverter 来加密和解密 ByteArrays 基于想法对 Java并且看起来类似于:
@Converter
public class CryptoByteArrayConverter implements AttributeConverter < Byte[], Byte[] > {
/**
* {@inheritDoc}
*/
@Override
public Byte[] convertToDatabaseColumn(Byte[] attribute) {
//...works fine
}
/**
* {@inheritDoc}
*/
@Override
public Byte[] convertToEntityAttribute(Byte[] dbData) {
//...works also fine
}
}
My entity class is using this converter:我的实体类正在使用此转换器:
@Entity
public class ArchivedInvoice implements Serializable {
//...
@Convert(converter=CryptoByteArrayConverter.class)
@JsonIgnore
private Byte[] encryptedXml;
//...
}
Everything works fine until here.一切正常,直到这里。 The data I had set is encrypted in the database and is also decrypted after getting the result set.
我设置的数据在数据库中加密,得到结果集后也解密。 But the CryptoByteArrayConverter is not used in @Query automatically.
但是 CryptoByteArrayConverter 不会自动在 @Query 中使用。 Is it possible to activate it or is there another good workaround?
是否可以激活它或者是否有其他好的解决方法?
For example:例如:
@Query("SELECT ai FROM #{#entityName} ai WHERE (ai.encryptedXml = :xml)")
Page < ArchivedInvoice > findByXml(@Param("xml") byte[] xml, Pageable p);
I make it run and realized that it is not needed to check if the decrypted values are equal or not.我让它运行并意识到不需要检查解密的值是否相等。 A comparison of the encrypted value of the DB attribute and the encrypted parameter returns the correct results.
DB 属性的加密值与加密参数的比较返回正确的结果。 After changing the parameter type from byte[] to Byte[] the AttributeConverter has been activated automatically and encrypted the parameter (xml):
将参数类型从 byte[] 更改为 Byte[] 后,AttributeConverter 已自动激活并加密参数 (xml):
@Query("SELECT ai FROM #{#entityName} ai WHERE (ai.encryptedXml = :xml)")
Page < ArchivedInvoice > findByXml(@Param("xml") Byte[] xml, Pageable p);
The following test shows what I mean:以下测试显示了我的意思:
@Test
public void saveTestEncryption() throws UnsupportedEncodingException {
repository.deleteAll();
ArchivedInvoice arcInv = createDTO(0);
repository.save(arcInv);
assertEquals(1, repository.count());
PageRequest pageRequest = new PageRequest(0, 25);
//Not encrypted!
String xml = arcInv.getXml();
Page < ArchivedInvoice > list =
repository.findByXml(ByteUtils.convert(xml.getBytes("UTF-8")), pageRequest);
assertEquals(1, list.getTotalElements());
xml += "A";
list = repository.findByXml(ByteUtils.convert(xml.getBytes("UTF-8")), pageRequest);
assertEquals(0, list.getTotalElements());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.