Hibernate中默认的NamingStrategy不支持调用带有下划线的column name。在hibernate的bean中必须使用camel case。使用ImprovedNamingStrategy可以使hibernate成功map到带有下划线的column name。代码如下:
1. Config文件
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(); }