Created
May 6, 2013 05:53
-
-
Save danveloper/5523554 to your computer and use it in GitHub Desktop.
EclipseLink class descriptor customizer that mimics Hibernate's ImprovedNamingStrategy for table and field naming
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ImprovedNamingDescriptorCustomizer implements DescriptorCustomizer { | |
@Override | |
public void customize(ClassDescriptor classDescriptor) throws Exception { | |
String className = classDescriptor.getJavaClassName(); | |
String shortName = Helper.getShortClassName(className); | |
String improvedName = toImprovedName(shortName); | |
classDescriptor.setTableName(improvedName); | |
updateMappings(classDescriptor, improvedName); | |
for (DatabaseField field : classDescriptor.getPrimaryKeyFields()) { | |
field.setName(toImprovedName(field.getName())); | |
} | |
} | |
void updateMappings(ClassDescriptor classDescriptor, String improvedTableName) { | |
for (DatabaseMapping mapping : classDescriptor.getMappings()) { | |
if (mapping.isDirectToFieldMapping()) { | |
DirectToFieldMapping directToFieldMapping = (DirectToFieldMapping) mapping; | |
String newFieldName = directToFieldMapping.getFieldName().replaceAll(improvedTableName+".",""); | |
// If the field name is not overridden, then derive the column name from the attribute name | |
if (newFieldName.toLowerCase().equals(directToFieldMapping.getAttributeName().toLowerCase())) { | |
newFieldName = toImprovedName(directToFieldMapping.getAttributeName()); | |
} | |
directToFieldMapping.getField().setName(newFieldName); | |
directToFieldMapping.getField().setTableName(improvedTableName); | |
} | |
} | |
} | |
String toImprovedName(String s) { | |
String[] parts = s.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"); | |
StringBuilder sb = new StringBuilder(); | |
for (int i=0;i<parts.length;i++) { | |
sb.append(parts[i].toLowerCase()); | |
if (i+1 < parts.length) { | |
sb.append("_"); | |
} | |
} | |
return sb.toString(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
@Customizer(ImprovedNamingDescriptorCustomizer.class) | |
public class MyEntity { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private long id; | |
// Column *will not* be overridden since it is explicitly defined here. | |
@Column(name = "FOO") | |
private boolean deleted; | |
// ... getters & setters | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment