Automatically convert a parameter with Spring Data JPA

前端 未结 1 350
小蘑菇
小蘑菇 2021-01-17 17:04

In our entity beans we use a custom ID format which includes a checksum to verify that the ID is actually valid. Ids look like ID827391738979. To make sure that

相关标签:
1条回答
  • 2021-01-17 17:37

    You could use a custom type in your entity with JPA 2.1 @Convert, so JPA makes the conversion for you (I've tested it with Spring Data JPA also, and it worked transparently!), see:

    Entity:

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

    Converter:

    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
        }
    
    }
    

    Notes:

    1. Make sure you're using a JPA-2.1-compatible Spring Data JPA version. (I'm sure that Spring Data JPA 1.7.0 (and above) are (or at least should) be compatible).
    2. Unfortunately, it won't work if that field should also be annotated with @Id.
    3. If you use EclipseLink, you have to define converter in persistence.xml, or it doesn't pick it up. https://bugs.eclipse.org/bugs/show_bug.cgi?id=412454.
    4. With JPA on Spring, package containing converters have to appear in property packageToScan on EntityManagerFactoryBean.
    0 讨论(0)
提交回复
热议问题