Search code examples
javaregexspring-bootspring-data-jpaentity

JPA annotation replace characters on insert


I have an Entity where I declare a field called "name". This field represents a file name. What I need to do is to replace all special characters that aren't allowed on Windows file names with empty or another string, so that they don't go to the DB when I save that entity.

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Where(clause = "is_active = true")
@EqualsAndHashCode(callSuper = true)
@Table(name = "File")
public class FileEntity extends BaseEntity {

    @NotBlank
    @Column(name = "Name", unique = true)
    private String name;

    ...
}

So let's say I place a name School project : 123 I want to replace the colons with underline, just like you would do via name.replaceAll("[^/./\\:*?\"<>|]", "_");, thus the resulting name stored in the DB would be School project _ 123

Is this even possible through an annotation (to include that replaceAll() there) or am I asking the wrong question here?


Solution

  • You need to declare setter in which convert original string by replacing symbols you want to replace.