休眠如何在属性上使用String.intern [英] How to have hibernate use String.intern on attributes
问题描述
对于某些实体,我们需要将成千上万个独立实体的负载永久保存在内存中.它们的许多属性来自一组有限的字符串(尽管不够有限,无法将其放入枚举中).休眠是否可以将String.intern用于这些属性以节省空间?
For some entities we need to keep loads (thousands) of detached enties permanently in memory. Many of their attributes are from a limited set of strings (though not limited enough to put it into an enumeration). Is it possible to have hibernate use String.intern for those attributes to save space?
理想情况下,应该通过注释来起作用,我可以在每个属性或易于更改的属性上加上注释,而不会因实现问题而使源代码过于混乱.
Ideally that should work via an annotation I could put on each of those attributes, or something easily changeable, without confusing the source code too much by this implementation concern.
推荐答案
正如您所建议的那样,使用JPA属性转换器是完全可行的.您可以通过在转换器上使用 autoApply = true
在常规级别上执行此操作,也可以使用 @Convert
批注在逐字段级别上进行操作.>
As you suggest yourself, it's perfectly doable with a JPA attribute converter. You could do it on a general level by using autoApply = true
on the converter, or you could do it on a field by field level with the @Convert
annotation.
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class StringInternConverter implements AttributeConverter<String, String> {
@Override
public String convertToDatabaseColumn(String attribute) {
return attribute;
}
@Override
public String convertToEntityAttribute(String dbData) {
return dbData != null? dbData.intern(): null;
}
}
在Hibernate 5.2.10上进行了测试,就像一个魅力一样!
Tested with Hibernate 5.2.10 and works like a charm!
这篇关于休眠如何在属性上使用String.intern的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!