【发布时间】:2010-10-05 17:43:48
【问题描述】:
要验证我收到的数据,我需要确保长度不会超过数据库列的长度。现在所有长度信息都存储在 Hibernate 映射文件中,是否可以通过编程方式访问这些信息?
【问题讨论】:
-
另请参阅stackoverflow.com/questions/1816780 以了解针对此问题的 JPA 解决方案。
标签: database hibernate validation
要验证我收到的数据,我需要确保长度不会超过数据库列的长度。现在所有长度信息都存储在 Hibernate 映射文件中,是否可以通过编程方式访问这些信息?
【问题讨论】:
标签: database hibernate validation
你可以做到,但这并不容易。您可能希望在启动时执行以下操作并存储值的静态缓存。有很多特殊情况需要处理(继承等),但它应该适用于简单的单列映射。我可能遗漏了一些 instanceof 和 null 检查。
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();
}
}
【讨论】:
根据 Brian 的回答,这就是我最终要做的。
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;
}
这似乎运作良好。希望这对偶然发现这个问题的人有所帮助。
【讨论】:
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build(); List<PersistentClass> persistentClasses = new ArrayList<PersistentClass>(metaData.getEntityBindings());
我首选的开发模式是将列长度基于一个常数,可以很容易地引用:
class MyEntity {
public static final int MY_FIELD_LENGTH = 500;
@Column(length = MY_FIELD_LENGTH)
String myField;
...
}
【讨论】:
有时获取 Configuration 对象可能会出现问题(如果您正在使用某些应用程序框架并且您没有使用 Configuration 自己创建会话工厂)。
如果您正在使用例如 Spring,您可以使用 LocalSessionFactoryBean(来自您的 applicationContext)来获取配置对象。然后获得列长度只是小菜一碟;)
factoryBean.getConfiguration().getClassMapping(String entityName) .getTable().getColumn(Column col).getLength()
【讨论】:
但是,当我尝试访问 LocalSessionFactoryBean 时,我遇到了类转换异常
LocalSessionFactoryBean factoryBean = (LocalSessionFactoryBean) WebHelper.instance().getBean("sessionFactory");
例外:
org.hibernate.impl.SessionFactoryImpl cannot be cast to org.springframework.orm.hibernate3.LocalSessionFactoryBean
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean>
这看起来很狡猾……
编辑:找到了答案。您需要在 bean 名称字符串前面使用 & 符号
LocalSessionFactoryBean factoryBean = (LocalSessionFactoryBean) WebHelper.instance().getBean("&sessionFactory");
【讨论】: