Java tutorial
/** * Copyright (c) 2015 https://github.com/zhaohuatai * * Licensed under the Apache License, Version 2.0 (the "License"); */ package org.zht.framework.zhtdao.hibernate; import java.util.Iterator; import org.hibernate.cfg.Configuration; import org.hibernate.mapping.Column; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; public class HibernateConfigurationUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; private static Configuration configuration; public static Configuration getConfiguration() { if (configuration == null) { // ?sessionFactory?& LocalSessionFactoryBean factory = (LocalSessionFactoryBean) applicationContext .getBean("&sessionFactory"); configuration = factory.getConfiguration(); } return configuration; } private static <T> PersistentClass getPersistentClass(Class<T> clazz) { synchronized (HibernateConfigurationUtil.class) { PersistentClass pc = getConfiguration().getClassMapping(clazz.getSimpleName()); if (pc == null) { configuration = configuration.addClass(clazz); pc = configuration.getClassMapping(clazz.getName()); } return pc; } } /** * ?? * * @param clazz * Class * @return ?? */ public static <T> String getTableName(Class<T> clazz) { return getPersistentClass(clazz).getTable().getName(); } /** * ?? * * @param clazz * Class * @return ?? */ public static <T> String getPKColumnName(Class<T> clazz) { return getPersistentClass(clazz).getTable().getPrimaryKey().getColumn(0).getName(); } /** * ?? * * @param clazz * Class * @param propertyName * ?? * @return ?? */ public static <T> String getColumnName(Class<T> clazz, String propertyName) { String columnName = ""; PersistentClass persistentClass = getPersistentClass(clazz); Property property = persistentClass.getProperty(propertyName); Iterator<?> iterator = property.getColumnIterator(); if (iterator.hasNext()) { Column column = (Column) iterator.next(); columnName += column.getName(); } return columnName; } @Override public void setApplicationContext(ApplicationContext context) throws BeansException { applicationContext = context; } }