1

I've found out that the database I'm using contains in some fields some special characters, like ASCII control characters (26 SUB etc.). They are causing problems because they made XMLs invalid etc. I'd like to filter them out with the most transparent way as possible.

Is it possible to activate some filter in JPA, that will process the string values read from database and will apply to every text field, without doing the filtering manually?

Applying filters like those mentioned in removing invalid XML characters from a string in java works, when I manually change the string field in entity.

Community
  • 1
  • 1
Danubian Sailor
  • 1
  • 38
  • 145
  • 223

1 Answers1

3

You can use lifecycle listeners. You can define listener callback methods inside your entity or in an own class. In your case I would create a listener class, since it seems that you will be needing the filtering in multiple entities. Since you want to filter data coming from the DB, you can use the PostLoad callback.

public class StringFilter {

  @PostLoad
  public void filter(Object obj) {
   // filterString
  }
}

Then assign your listener class to the entity:

@EntityListeners({StringFilter.class})
public class  SomeEntity {
...
kostja
  • 60,521
  • 48
  • 179
  • 224
  • 1
    I suppose your solution requires creating generif `filter(Object obj)` method and using reflection to process all string fields? – Danubian Sailor Jul 17 '14 at 08:06
  • You're right. If the listener is applied to multiple classes, you need to use a common ancestor of those. So you either have to use Object or you let your classes implement a common interface (or derive from a common entity ancestor). Then you can work with your interface inside the listener – kostja Jul 17 '14 at 08:53