views:

136

answers:

3

I'm using a convention of prefixing field names with an underscore. When I generate annotate entity classes with such fields I am stuck to using the underscore-prefixed property names in queries. I want to avoid that, and be able to do:

@Entity
public class Container {

    private String _value;
}

// in a lookup method
executeQuery("from Container where value = ?", value);

Is that possible with JPA in general or Hibernate in particular?


Update: Still trying to remember why, but I need this to be annotated on fields rather than on getters.

+1  A: 

You could perhaps write subclasses of your generated entity classes, which have getter methods on them, and then configure the entity manager to use getter/setter access instead if field access? Then your getters/setters could have any name you liked.

skaffman
+3  A: 

You can annotate the getter:

@Entity
public class Container {

    private String _value;

    @Column
    public String getValue()
    {
        return _value;
    }

    public void setValue( String value )
    {
        this._value = value;
    }

}
mtpettyp
Probably not an option if the class is generated, though.
skaffman
A: 

Have a look at NamingStrategy. It would be fairly easy to extend the DefaultNamingStrategy and override the columnName method to strip the first underscore (if it is there).

Maarten Winkels
Are you sure this deals in property names and not in database column names? The javadoc states that it is 'A set of rules for determining the physical column and table names given the information in the mapping document.'
Robert Munteanu
Hmm, you are right.Hibernate only deals in property (or field) to database mapping. There is no 'other' name that you can use. This solution will give you proper names in the database, but your property names (in HQL or Criteria queries) will still have the underscore.I think you can only use the other suggestion and use the getter for that.
Maarten Winkels