开发者

Hibernate: Change the loaded entity after properties have been injected

After loading an entity (via load or find), just before the response is returned, i'd like to change the entity (the actual reference). Does anyone know how to do this? The reason is that the entity into which the properties were injected during load is a builder object. I tried to use a PostLoadEventListener like this:

public void onPostLoad(PostLoadEvent event) {
  Object entity = event.getEntity();
  if(开发者_如何学编程null != entity && entity instanceof MyBuilder){
    MyBuilder builder = (MyBuilder)entity;
    MyActualClass result = builder.build();
    event.setEntity(result);
  }
}

but it seems that whatever I set in that event is ignored and lost (makes sense, this is how events work). The only option that seems to be left is overriding an EntityPersister but that's so yucky! Do you know of another, more elegant solution? Thanks! Cristian


you can implement the Hibernate's EmptyIntercepter and provide the implementation for onLoad method where you can do whatever you want immediately after loading from the database and before sending the response.

you can get more info on this here http://docs.jboss.org/hibernate/core/3.3/reference/en/html/events.html


If you wish to make a read-only entity, then you can make all your setters protected and Hibernate will use reflection to initially set them. Then in your application the object will effectively be immutable.

Hibernate also allows entities to be read-only, but not necesarily immutable in the java sense.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜