-
1. Re: How to set auto trim on EntityManager?
berat Mar 9, 2009 5:36 AM (in response to cash1981)I am also interesting in this topic.
But I think it is not good to trim the value in data access tier.
This should be done by view/controller tier.
Maybe you can define an annotation your self such as @Trim for javabeans which will automatically trim string value
on getter methods. -
2. Re: How to set auto trim on EntityManager?
swd847 Mar 9, 2009 6:04 AM (in response to cash1981)You could add an Entity Listener in orm.xml that will accomplish this, you want it to listen to the pre-update and pre-persist events.
I would have this entity listener use component.getInstance to call out to a custom application scoped seam component. In this components create method you do something like this:
@Name("hibernateTrimmer") @Scope(ScopeType.APPLICATION) @AutoCreate @Startup public class HibernateTrimmer { class Prop { Method getter, setter; } Map<Class, List<Prop>> propMap = new HashMap<Class, List<Prop>>(); @In EntityManager entityManager; @Create public void findAnnotatedClasses() throws NoSuchMethodException { HibernateSessionProxy es = (HibernateSessionProxy) entityManager .getDelegate(); Map<String, ClassMetadata> map = es.getSessionFactory() .getAllClassMetadata(); for (String s : map.keySet()) { ClassMetadata m = map.get(s); Class c = m.getMappedClass(EntityMode.POJO); //scan through the properties using m.getPropertyNames() and m.getPropertyType() //add all strink proiperties that you want to trim to the list //using reflection to get the appropriate setter and getter } } @BypassInterceptors public void doTrim(Object o) throws InvocationTargetException, IllegalAccessException { List<Prop> cls = propMap.get(o.getClass()); if (cls == null) { return; } for (Prop m : cls) { String pb = m.getter.invoke(o); m.setter.invoke(o,pb.trim()); } } }
the code above is not complete, as I just ripped it out of a class of mine that does something similar (annotation based cache invalidation), but should give you the general idea.
-
3. Re: How to set auto trim on EntityManager?
cash1981 Mar 9, 2009 2:36 PM (in response to cash1981)Hmm, if it is that difficult then I will just write trim() manually :-)
-
4. Re: How to set auto trim on EntityManager?
stephen Mar 10, 2009 3:41 PM (in response to cash1981)If the problem are blanks that users accidentally enter into form fields, then a JSF converter would be the cleanest solution.
Seam even makes this a little easier with an annotation:@Converter(forClass = String.class) registers a seam component as default converter for all string valued properties.