Search code examples
jpaeclipselinkjpa-2.0jpa-2.1

Map two fields to one database column


Question: Am I somehow able to map two fields of my Entity class to only one Column in the Database?

Scenario: The database is not fully normalized. There exists one Column which contains a composite information. It is not my actual use case, but an comprehensible example might be X- and Y-coordinate of a point in the plane. So the Database may contain a String 12:45 and the Entity class should contain only two integer field x width value 12 and ywith value 45.

Currently the Entity class has just two additional getter and setter for x and y and performs the proper translation. But I am wondering if there is a way to let JPA do this for me magically in the background.

I am already working with custom converter classes, e.g. for a proper mapping between between enums and database columns, but this works only for a "one-to-one" mapping between the field in the Entity class and the column in the database.

Of course it would be the most preferable way to redesign the table in the database, but that's not an option at the moment.

Vendor specific solutions are also fine.


Solution

  • 2 Entity fields into one database column can be done fairly simply by specifying JPA use your accessor in the entity to handle the conversion:

    @Entity
    @Access(AccessType.FIELD)
    class myEntity {
    @Id
    int id;
    @Transient
    String x;
    @Transient
    String y;
    
    @Mutable //EclipseLink specific to prevent change tracking issues
    @Access(AccessType.PROPERTY)
    @Column(name="yourDatabaseFieldName")
    private String getCoords() {
     return x+":"+y;
    }
    private void setCoords(String coords) {
      //parse the string and set x+y.
    }
    

    EclipseLink and Hibernate have transformation mappings that are able to handle the reverse; 2 or more database fields into one java property but this is outside of JPA.