Skip to content

Instantly share code, notes, and snippets.

@iromu
Last active October 18, 2017 14:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save iromu/6864061 to your computer and use it in GitHub Desktop.
Save iromu/6864061 to your computer and use it in GitHub Desktop.
import java.sql.SQLException;
import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.tools.schemaframework.IndexDefinition;
/**
* @author Ivan Rodriguez Murillo
*/
public class CamelCaseSessionCustomizer implements SessionCustomizer {
@Override
public void customize(Session session) throws SQLException {
for (ClassDescriptor descriptor : session.getDescriptors().values()) {
// Only change the table name for non-embedable entities with no
// @Table already
if (!descriptor.getTables().isEmpty() && descriptor.getAlias().equalsIgnoreCase(descriptor.getTableName())) {
String tableName = addUnderscores(descriptor.getTableName());
descriptor.setTableName(tableName);
for (IndexDefinition index : descriptor.getTables().get(0).getIndexes()) {
index.setTargetTable(tableName);
}
}
for (DatabaseMapping mapping : descriptor.getMappings()) {
// Only change the column name for non-embedable entities with
// no @Column already
if (mapping.getField() != null && !mapping.getAttributeName().isEmpty()
&& mapping.getField().getName().equalsIgnoreCase(mapping.getAttributeName())) {
mapping.getField().setName(addUnderscores(mapping.getAttributeName()));
}
}
}
}
private static String addUnderscores(String name) {
StringBuffer buf = new StringBuffer(name.replace('.', '_'));
for (int i = 1; i < buf.length() - 1; i++) {
if (Character.isLowerCase(buf.charAt(i - 1)) && Character.isUpperCase(buf.charAt(i))
&& Character.isLowerCase(buf.charAt(i + 1))) {
buf.insert(i++, '_');
}
}
return buf.toString().toUpperCase();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="unit">
<properties>
<property name="eclipselink.session.customizer"
value="com...eclipselink.CamelCaseSessionCustomizer"/>
</properties>
</persistence-unit>
</persistence>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment