修改String字段的getter的返回值 [英] Modifying return value of getters of String fields

查看:48
本文介绍了修改String字段的getter的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我的应用程序中具有类似于域类的类,其中包含一些Long,Double,Date和String字段.这些类通过一些公共字段和少量公共方法扩展了基类.每当我访问String的类字段(尽管是getter)时,我都想对返回的值进行一些更改(例如,删除html标签).有没有比为String类型的每个字段实现getter的方法更好的方法?那继承字段呢?

Let's say I have classes similar to domain classes in my application with some Long, Double, Date and String fields. These classes extend base class with some common fields and few common methods. Whenever I access class field (though getter) that is String, I want to make some changes to the value returned (for example remove html tags). Is there a better way than making implementations of getters for each fields of String type? What about inherited fields?

推荐答案

如果更改设置的值,或者返回与设置的值不同的值,则会使Hibernate感到困惑.这是因为从数据库加载实例时,Hibernate会将原始数据保留在其一级缓存中,并向您返回一个域对象实例.刷新时,它将当前状态与原始状态进行比较,如果已更改,会将更改推送到数据库.因此,如果返回的值与设置的值不同,但又没有真正更改该值,则Hibernate无法分辨出该值.

If you change the value that's set, or return a value that's different from what was set, you'll confuse Hibernate. That's because when you load an instance from the database, Hibernate keeps the original data in its 1st-level cache, and returns a domain object instance to you. When you flush, it compares the current state with the original, and if it changed, it will push the changes to the database. So if you return a different value than what was set, but don't really change the value, Hibernate can't tell the difference.

最好不理会这些属性,而是创建返回更改后的数据的方法.我使用的一种约定是,例如,如果您有一个 String body 字段,则可以通过属性名称 body 或getter getBody()访问它,但是您可以创建Hibernate未知的 body()方法,并返回您想要的任何内容.

You're much better off leaving the properties alone and creating methods that return altered data. One convention I've used is that if for example you have a String body field, you can access it via the property name body or the getter getBody(), but you can create a body() method that's unknown to Hibernate and returns whatever you want.

这篇关于修改String字段的getter的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆