Hibernate--根据实体类获得表名、主键名、字段名(与Spring集成)(一)

来源:互联网 发布:mac 六国 重新启动 编辑:程序博客网 时间:2024/05/16 11:45

本文参考自http://blog.csdn.net/fhwbj/article/details/3267787

在使用Hibernate时,我们有时可能需要根据实体类获得数据库表的信息,上面的那个链接的内容已经给出了模版,不过使用Hibernate4时,如果获得的PersistentClass一直为null,可以试着采用下面的方式初始化Configuration

[java] view plain copy
  1. if (configuration == null) {  
  2.     configuration = new Configuration().configure();  
  3.     configuration.buildSessionFactory();  
  4. }  
下面进入正题,在Hibernate和Spring集成时,如果我们是在Spring的配置文件中配置的Hibernate,即没有hibernate.cfg.xml文件(上面的方法必须要有此文件),那么我们又该如何获得Configuration呢?其实我们可以根据是Spring中配置的sessionFactory来获得Configuration对象,下面是具体的代码实现

HiberanteConfigurationUtil类 (映射工具类)

这里需要注意的是:

1.在取sessionFactory时要加上&号,原因可以看一下http://blog.csdn.net/zhangjk1993/article/details/40017583

2.这里采用的xml文件做的映射,要保证实体类名和对应的映射文件名一致

[java] view plain copy
  1. package util;  
  2.   
  3. import java.util.Iterator;  
  4.   
  5. import org.hibernate.cfg.Configuration;  
  6. import org.hibernate.mapping.Column;  
  7. import org.hibernate.mapping.PersistentClass;  
  8. import org.hibernate.mapping.Property;  
  9. import org.springframework.beans.BeansException;  
  10. import org.springframework.context.ApplicationContext;  
  11. import org.springframework.context.ApplicationContextAware;  
  12. import org.springframework.orm.hibernate4.LocalSessionFactoryBean;  
  13.   
  14. /** 
  15.  * 根据实体类得到对应的表名、主键名、字段名(与Spring集成) 
  16.  * 这里使用xml文件配置的映射,需要保证实体类名与对应映射文件名一致,即User.java与User.hbm.xml  
  17.  * </p> 
  18.  * 这里使用继承ApplicationContextAware的方式来获得ApplicationContext, 
  19.  * 因此需要在Spring配置文件中配置一下该类,才能自动注入ApplicationContext对象 
  20.  *  
  21.  * <bean class="util.HibernateConfigurationUtil"/> 
  22.  */  
  23. public class HibernateConfigurationUtil implements ApplicationContextAware {  
  24.   
  25.     private static ApplicationContext applicationContext;  
  26.   
  27.     private static Configuration configuration;  
  28.   
  29.     public static Configuration getConfiguration() {  
  30.   
  31.         if (configuration == null) {   
  32.             // 取sessionFactory的时候要加上&  
  33.             LocalSessionFactoryBean factory = (LocalSessionFactoryBean) applicationContext  
  34.                     .getBean("&sessionFactory");  
  35.             configuration = factory.getConfiguration();  
  36.         }  
  37.   
  38.         return configuration;  
  39.     }  
  40.   
  41.     private static <T> PersistentClass getPersistentClass(Class<T> clazz) {  
  42.         synchronized (HibernateConfigurationUtil.class) {  
  43.             PersistentClass pc = getConfiguration().getClassMapping(  
  44.                     clazz.getSimpleName());  
  45.             if (pc == null) {  
  46.                 configuration = configuration.addClass(clazz);  
  47.                 pc = configuration.getClassMapping(clazz.getName());  
  48.             }  
  49.             return pc;  
  50.         }  
  51.     }  
  52.   
  53.     /** 
  54.      * 获得实体类对应的表名 
  55.      *  
  56.      * @param clazz 
  57.      *            实体类的Class对象 
  58.      * @return 表名 
  59.      */  
  60.     public static <T> String getTableName(Class<T> clazz) {  
  61.         return getPersistentClass(clazz).getTable().getName();  
  62.     }  
  63.   
  64.     /** 
  65.      * 获得实体类对应表的主键字段名称 
  66.      *  
  67.      * @param clazz 
  68.      *            实体类的Class对象 
  69.      * @return 主键字段名称 
  70.      */  
  71.     public static <T> String getPKColumnName(Class<T> clazz) {  
  72.         return getPersistentClass(clazz).getTable().getPrimaryKey()  
  73.                 .getColumn(0).getName();  
  74.     }  
  75.   
  76.     /** 
  77.      * 获得类属性对应的字段名 
  78.      *  
  79.      * @param clazz 
  80.      *            实体类的Class对象 
  81.      * @param propertyName 
  82.      *            实体类的属性名 
  83.      * @return 属性对应的字段名 
  84.      */  
  85.     public static <T> String getColumnName(Class<T> clazz, String propertyName) {  
  86.         String columnName = "";  
  87.         PersistentClass persistentClass = getPersistentClass(clazz);  
  88.         Property property = persistentClass.getProperty(propertyName);  
  89.         Iterator<?> iterator = property.getColumnIterator();  
  90.         if (iterator.hasNext()) {  
  91.             Column column = (Column) iterator.next();  
  92.             columnName += column.getName();  
  93.         }  
  94.         return columnName;  
  95.     }  
  96.   
  97.     @Override  
  98.     public void setApplicationContext(ApplicationContext context)  
  99.             throws BeansException {  
  100.         applicationContext = context;  
  101.     }  
  102. }  


applicationContext.xml
[html] view plain copy
  1. <span style="white-space:pre">    </span><bean id="sessionFactory"  
  2.         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  3.         <property name="dataSource" ref="dataSource" />  
  4.         <property name="hibernateProperties">  
  5.             <props>  
  6.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
  7.                 <prop key="hibernate.show_sql">true</prop>  
  8.                 <prop key="hibernate.format_sql">true</prop>  
  9.             </props>  
  10.         </property>  
  11.         <property name="mappingResources">  
  12.             <list>  
  13.                 <value>bean/User.hbm.xml</value>  
  14.             </list>  
  15.         </property>  
  16.     </bean>  
  17.     <bean class="util.HibernateConfigurationUtil" />  

User类

[java] view plain copy
  1. package bean;  
  2.   
  3. public class User {  
  4.   
  5.     private int id;  
  6.   
  7.     private String username;  
  8.   
  9.     private String password;  
  10.   
  11.     public int getId() {  
  12.         return id;  
  13.     }  
  14.   
  15.     public void setId(int id) {  
  16.         this.id = id;  
  17.     }  
  18.   
  19.     public String getUsername() {  
  20.         return username;  
  21.     }  
  22.   
  23.     public void setUsername(String username) {  
  24.         this.username = username;  
  25.     }  
  26.   
  27.     public String getPassword() {  
  28.         return password;  
  29.     }  
  30.   
  31.     public void setPassword(String password) {  
  32.         this.password = password;  
  33.     }  
  34.   
  35. }  
User.hbm.xml

[html] view plain copy
  1. <?xml version='1.0' encoding='utf-8'?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping>  
  6.     <class name="bean.User" table="_user">  
  7.         <id name="id" type="int">  
  8.             <column name="id" />  
  9.             <generator class="identity" />  
  10.         </id>  
  11.         <property name="username" type="string">  
  12.             <column name="_username" />  
  13.         </property>  
  14.         <property name="password" type="string">  
  15.             <column name="_password" />  
  16.         </property>  
  17.     </class>  
  18. </hibernate-mapping>  
下面是测试代码

[java] view plain copy
  1. new ClassPathXmlApplicationContext("applicationContext.xml");  
  2. System.out.println(HibernateConfigurationUtil.getTableName(User.class));  
  3. System.out.println(HibernateConfigurationUtil.getPKColumnName(User.class));  
  4. System.out.println(HibernateConfigurationUtil.getColumnName(User.class,"username"));  
版权声明:本文为博主原创文章,未经博主允许不得转载。
阅读全文
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 手机被病毒入侵怎么办 苹果手机不息屏怎么办 苹果手机散屏怎么办 苹果手机屏幕死机了怎么办 苹果手机屏死机怎么办 微信号账号异常怎么办 手机设置加密了怎么办 华为手机触屏坏了怎么办 安卓启动器停止怎么办 手机显示停止运行怎么办 手机来电被拦截怎么办 手机被加黑名单怎么办 手机短信被屏蔽了怎么办 手机信息被拦截怎么办 手机有感染病毒怎么办 华为p10速度慢怎么办 华为手机清理慢 怎么办 华为手机有回音怎么办 手机没有返回键怎么办 手机总显示内存不足怎么办 扩音器耳麦接触不良怎么办 音响插头接触不良怎么办 华为手机耳机声音小怎么办 苹果耳机孔变形怎么办 耳机孔松了怎么办 荣耀9青春版费电怎么办 华为双清了怎么办 华为开不开机怎么办 华为手机黑屏打不开怎么办 荣耀v8指纹消失怎么办 耳机话筒进水了怎么办 beats耳机进水了怎么办 音量孔进水了怎么办 苹果手机屏幕进水了怎么办 耳机孔进水了怎么办 华为v10声音小怎么办 荣耀v10声音小怎么办 华为变耳机模式怎么办 小米六耳机模式怎么办 苹果成耳机模式怎么办 苹果调耳机模式怎么办