在开发软件时,通常要求每个开发人员遵守共同的命名策略。例如,数据库的表名以及字段名的所有字符都为大写,表名“S”结尾。对于Customer类,对应的数据库表名为CUSTOMERS。一种方法是手工设置表名和字段名,但这种方法很耗时,而且容易出错。还有一种方式是实现Hibernate的NamingStrategy接口。
- import net.sf.hibernate.cfg.NamingStrategy;
- import net.sf.hibernate.util.StringHelper;
- public class MyNamingStrategy implements NamingStrategy {
- public String classToTableName(String className) {
- return StringHelper.unqualify(className).toUpperCase() + 'S';
- }
- public String propertyToColumnName(String propertyName) {
- return propertyName.toUpperCase();
- }
- public String tableName(String tableName) {
- return tableName;
- }
- public String columnName(String columnName) {
- return columnName;
- }
- public String propertyToTableName(String className, String propertyName) {
- return classToTableName(className) + '_'
- + propertyToColumnName(propertyName);
- }
- }
- Congfiguration cnofig = new Configuration();
- config.setNameingStratefy(new MyNamingStrategy());
- SessionFactory sessionFactory = config.buildSessionFactory();
【编辑推荐】