Getting column length from Hibernate mappings? Getting column length from Hibernate mappings? database database

Getting column length from Hibernate mappings?


You can get to it but it's not easy. You might want to do something like below at startup and store a static cache of the values. There are a lot of special cases to deal with (inheritance, etc), but it should work for simple single-column mappings. I might have left out some instanceof and null checks.

for (Iterator iter=configuration.getClassMappings(); iter.hasNext();) {    PersistentClass persistentClass = (PersistentClass)iter.next();    for (Iterator iter2=persistentClass.getPropertyIterator(); iter2.hasNext();) {       Property property = (Property)iter2.next();       String class = persistentClass.getClassName();       String attribute = property.getName();       int length = ((Column)property.getColumnIterator().next()).getLength();    }  }


Based on Brian's answer, this is what I ended up doing.

private static final Configuration configuration = new Configuration().configure();public static int getColumnLength(String className, String propertyName) {    PersistentClass persistentClass = configuration.getClassMapping(className);    Property property = persistentClass.getProperty(propertyName);    int length = ((Column) property.getColumnIterator().next()).getLength();    return length;}

This appears to be working well. Hope this is helpful to anyone who stumbles upon this question.


My preferred development pattern is to base the column length on a constant, which can be easily referenced:

class MyEntity {   public static final int FIELD_LENGTH = 500;   @Column(length = FIELD_LENGTH)   String myField;   ...}