Hibernate中调用带有underscore的Column Name

Hibernate中默认的NamingStrategy不支持调用带有下划线的column name。在hibernate的bean中必须使用camel case。使用ImprovedNamingStrategy可以使hibernate成功map到带有下划线的column name。代码如下:

1. Configure文件

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
          Configuration configuration = new Configuration().configure();
          System.setProperty("hibernate.connection.password", DEFAULT_PASSWORD);
          System.setProperty("hibernate.connection.username", DEFAULT_USER);
          System.setProperty("hibernate.connection.driver_class", DEFAULT_DRIVER_CLASS);
          System.setProperty("hibernate.connection.url", DEFAULT_URI);
          System.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
          configuration.setProperties(System.getProperties());
          sessionFactory = configuration.buildSessionFactory();
        }
        return sessionFactory;
    } 

2. Bean

@Entity
@Table(name = "version")
public class Version {
  private int versionId;
  @Id
  @Column(name="version_id")
  public int getVersionId() {
	return versionId;
  }
  public void setVersionId(int versionId) {
	this.versionId = versionId;
  }
}

3. Unit Test

@Test
public void testVersionBean() {
	 Session session = Config.getSessionFactory().openSession();
	 session.beginTransaction();
	
	 Query query = session.createQuery("select versionId from Version");
	
	 @SuppressWarnings("unchecked")
	 List<Object> version = query.list();
	 assertEquals(version.get(0), 1);
	 
	 session.getTransaction().commit();
	 session.close();
}

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。