How to set annotation attribute value based on the active profile in Spring Boot?

Viewed 751

I use two mirror database schemas in my Spring Boot application with Flyway migration on startup: an in-memory H2 - for demo profile, and Postgres - for prod. In each schema, there is a reset_token field which is defined like this:

CREATE TABLE users( 
    ... 
    reset_token CHAR(36)
);

The problem is that Hibernate expects two different annotations to be used for correct mapping of String property in my User entity into corresponding table column: @Column(columnDefinition = "char") - for H2 and @Column(columnDefinition = "bpchar") - for Postgres. How can I do that? I mean, is it possible to set the value of columnDefinition attribute, based on the active profile, so that not to create two different User entities for each profile?

@Data
@NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
@RequiredArgsConstructor
@Entity
@Table(name = "users")
public class User {
    ...
    @Column(columnDefinition = "char")
    // @Column(columnDefinition = "bpchar")
    private final String resetToken;        
}
3 Answers

You could try sticking to @Column(columnDefinition = "bpchar") and appending ;MODE=PostgreSQL to the H2 JDBC connection string.

If that doesn't work, perhaps this answer will help.

If that doesn't work either, then I'd suggest the answer just below it.

I think you don't need columnDefinition, just use @Column

In the annotation you can use final var. So you will need to add a final variable that will hold your tokenType. This var will be populated from the active profile. You can use something like this:

@Value("${tokenType}") // will take the value from active profile
private final String tokenType = "char";

@Column(columnDefinition = tokenType)
private final String resetToken;
Related