Automatically convert parameter using Spring Data JPA

In our beans entity, we use a custom identifier format that includes a checksum to make sure the identifier is valid. Identifiers look like ID827391738979. To make sure that all code uses the correct identifiers, we created a wrapper around the ID line:

class ID {
    public ID(String id) {
       // parse and verify ID
    }

    public String toString() {
       return id;
    }
}

All code just uses this object ID. However, in our essence, we defined the ID as String:

class SomeEntity {
    @Column
    private String itsID;
}

Now we want to use Spring -Data-JPA to query some object by its identifier. So:

public SomeEntity findByItsID(ID itsId);

The problem is that Spring Data JPA is now trying to assign the requested ID, while the request, of course, is waiting String.

Spring Data JPA (, Spring), ? String :

public SomeEntity findByItsId(String itsId);

, ID , .

+4
1

JPA 2.1 @Convert, JPA ( Spring Data JPA , !), .:

Entity:

@Entity
class SomeEntity {

    @Column(name = "my_id_column_name")
    @Convert(converter = MyIDConverter.class)
    private ID itsID;
}

public class MyIDConverter implements AttributeConverter<ID, String> {

    @Override
    public String convertToDatabaseColumn(ItStaticDataKey javaKey) {
        // your implementation here
    }

    @Override
    public ItStaticDataKey convertToEntityAttribute(final String databaseKey) {
        // your implementation here
    }

}

:

+6

Source: https://habr.com/ru/post/1535758/


All Articles