eclipselink 数据库表命名规则 驼峰转下划线/表名转换

来源:互联网 发布:袜子属于淘宝哪个类目 编辑:程序博客网 时间:2024/06/06 04:47

最近公司做SAAS项目,以前用的数据源为c3p0,数据库表的命名规则为类名(驼峰)转为下划线。

比如:PersonMsg (类)  对应  表名 person_msg(表)

而现在公司用的是eclipselink做dao层操作。为了避免大量修改只能去看eclipselink是否有支持命名策略。

最后发现了终极boss《SessionCustomizer》,这个玩意。分享出来 ,以后不迷路。

public class SystemCustomizer implements SessionCustomizer {@Overridepublic void customize(Session session) throws Exception {Map<Class, ClassDescriptor> descs = session.getDescriptors();Collection<ClassDescriptor> descriptors = descs.values();for (ClassDescriptor desc : descriptors) {String fullClassName = desc.getJavaClassName();String className=Helper.getShortClassName(fullClassName);String tableName = camelToUnderline(className);Vector<String> tableNames = new Vector<String>();tableNames.add(tableName);desc.setTableNames(tableNames);updateMappings(desc, tableName);}}private void updateMappings(ClassDescriptor desc, String tableName) {for (DatabaseMapping mapping : desc.getMappings()) {if (mapping.isDirectToFieldMapping()) {DirectToFieldMapping directMapping = (DirectToFieldMapping) mapping;directMapping.getField().setTableName(tableName);}}}/**     * 驼峰法转下划线     */    public static String camelToUnderline(String line){        if(line==null||"".equals(line)){            return "";        }        line=String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));        StringBuffer sb=new StringBuffer();        Pattern pattern=Pattern.compile("[A-Z]([a-z\\d]+)?");        Matcher matcher=pattern.matcher(line);        while(matcher.find()){            String word=matcher.group();            sb.append(word.toLowerCase());            sb.append(matcher.end()==line.length()?"":"_");        }        return sb.toString();    }}