Skip to main content

Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Eclipse Projects » EclipseLink » Customize JPA field name mapping using EclipseLink
icon5.gif  Customize JPA field name mapping using EclipseLink [message #1180319] Sun, 10 November 2013 23:08
Jianbao Tao is currently offline Jianbao TaoFriend
Messages: 1
Registered: November 2013
Junior Member
I need to map camel-case names to underscore-separated names in my current project, which uses EclipseLink, due to historical reasons. I know we can customize name mapping individually in JPA, but we have a long list of camel-case names to change, so we want to avoid that kind of boilerplate codes if all possible.

What I want to achieve is as follows. Suppose we have an entity class as below:

public class FooBar {
    @Id @GeneratedValue
    private Long id;

    @Temporal( TemporalType.TIMESTAMP )
    private Date dateCreated;

I want this class maps to a table with name "foo_bar" and columns "id" and "date_created". Note that all names in database are in lower case.

I googled around, and found a solution for changing table names. However, I can't figure out how to change field names in an entity class.

Below is my name-mapping customizer, where the method updateFieldNameMappings() is not giving what I want. So, how do I do this correctly?

public class JpaNameMappingCustomizer implements SessionCustomizer {

    public void customize( Session session ) throws Exception {
        Map<Class, ClassDescriptor> descs = session.getDescriptors();
        Collection<ClassDescriptor> descriptors = descs.values();

        // This code assumes single table per descriptor!
        for (ClassDescriptor desc : descriptors) {
            String fullClassName = desc.getJavaClassName();
            String className= Helper.getShortClassName( fullClassName );
            String tableName = camelCaseToUnderscore(className);
            desc.setTableName( tableName );

    private void updateFieldNameMappings( ClassDescriptor desc ) {
        for (DatabaseMapping mapping : desc.getMappings()) {
            if (mapping.isDirectToFieldMapping()) {

                DirectToFieldMapping directMapping = (DirectToFieldMapping) mapping;

                // oldFieldName is something like "foo_bar.ID"
                String oldFieldName = directMapping.getFieldName();

                String newFieldName = camelCaseToUnderscore( oldFieldName ); // wrong

                directMapping.setFieldName( newFieldName );

Previous Topic:SQL Exception not being caught
Next Topic:zero as a primary key
Goto Forum:

Current Time: Sat Mar 28 15:39:22 GMT 2020

Powered by FUDForum. Page generated in 0.01955 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top