是否可以关闭UserType的二级缓存?

时间:2014-02-07 20:18:21

标签: hibernate caching localization internationalization usertype

我在Spring / Hibernate应用程序中使用i18n设置很困难。我现在尝试按照这个方法:http://www.theserverside.com/news/1377072/Internationalized-Data-in-Hibernate

只要我不使用二级缓存,它就可以工作。当我使用它时,第一个值被缓存并返回,即使我稍后更改语言。 (通过拆卸和组装方法)。我真的希望有人可以帮我解决这个问题,因为我需要缓存CarType实体,而不是userType-part。 (I18nLocaleHolder在内存映射上运行)

谢谢!

以下是实体类的一部分:

   @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
   @Immutable
   @Table(name = "CAR_TYPE")
   public class CarType implements Serializable {

      @Id
      private Long id;

      @Type(type = "LocalizedLabelUserType")
      private String description;

        ...

这是userType:     public class LocalizedLabelUserType实现UserType {

   @Override
   public int[] sqlTypes() {
      return new int[] { Types.INTEGER };
   }

   @Override
   public Class<String> returnedClass() {
      return String.class;
   }

   @Override
   public boolean equals(Object x, Object y) throws HibernateException {
      return x == y;
   }

   @Override
   public int hashCode(Object x) throws HibernateException {
      return x == null ? 0 : x.hashCode();
   }

   @Override
   public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException,
         SQLException {
      Long labelId = (Long) LongType.INSTANCE.nullSafeGet(rs, names, session, owner);
      return I18nLocaleHolder.getDescription(labelId, LocaleContextHolder.getLocale().getLanguage());
   }

   @Override
   public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException,
         SQLException {
      Long code = I18nLocaleHolder.getCode((String) value, LocaleContextHolder.getLocale().getLanguage());
      LongType.INSTANCE.nullSafeSet(st, code, index, session);
   }

   @Override
   public Object deepCopy(Object value) throws HibernateException {
      return value;
   }

   @Override
   public boolean isMutable() {
      return false;
   }

   @Override
   public Serializable disassemble(Object value) throws HibernateException {
      return (Serializable) value;
   }

   @Override
   public Object assemble(Serializable cached, Object owner) throws HibernateException {
      return cached;
   }

   @Override
   public Object replace(Object original, Object target, Object owner) throws HibernateException {
      return original;
   }
}

1 个答案:

答案 0 :(得分:0)

需要删除注释@Immutable,否则Hibernate将不会检测更改的描述到类CarType

然后将CarType的缓存从READ_ONLY更改为READ_WRITE仍然允许实体缓存,但是当实体在数据库上更新时,缓存将反映新的价值description

@Table(name = "CAR_TYPE")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
 public class CarType implements Serializable {
     ...
 }