如何动态读取MYSQL中表的字段信息,或是表本身的信息
使用Hibernate3如何读,spring封闭的对hibernate操作的类,又该如何操作。基本思路是怎么的?
网上给的建议是:
Connection connection = getConnection();
// Create a result set
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM " + table);
// Get result set meta data
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
rsmd.getColumnName(i)
感觉好像不对,没有实验,但是为了读一个表的字段信息,就读出所有记录,未免有点小题大做了吧。
还在寻找思路
有人已经给出了答案,那就发扬一下“拿来主义”的精神吧
public String getTableName(Class clazz){
SessionFactory factory = getHibernateTemplate().getSessionFactory();
AbstractEntityPersister classMetadata = (SingleTableEntityPersister)factory.getClassMetadata(clazz);
return classMetadata.getTableName();
}
public List<String> getCellsName(Class clazz){
List<String> resultList = new ArrayList<String>();
SessionFactory factory = getHibernateTemplate().getSessionFactory();
AbstractEntityPersister classMetadata = (SingleTableEntityPersister)factory.getClassMetadata(clazz);
// 添加主键
resultList.addAll(Arrays.asList(classMetadata.getIdentifierColumnNames()));
String[] propertyNames = classMetadata.getPropertyNames();
for (String propertyName : propertyNames) {
// 判断是否一对多的对像,移除
boolean isCollection = classMetadata.getClassMetadata().getPropertyType(propertyName).isCollectionType();
if (!isCollection) {
String[] propertyColumnNames = classMetadata.getPropertyColumnNames(propertyName);
for (String columnName : propertyColumnNames) {
resultList.add(columnName);
}
}
}
return resultList;
}