[英]How to set annotation attribute value based on the active profile in Spring Boot?
我在 Spring Boot 应用程序中使用两个镜像数据库模式,并在启动时进行 Flyway 迁移:内存中的H2 - 用于demo
配置文件,和Postgres - 用于prod
。 在每个模式中,都有一个reset_token
字段,其定义如下:
CREATE TABLE users(
...
reset_token CHAR(36)
);
问题是 Hibernate 期望使用两个不同的注释将我的User
实体中的 String 属性正确映射到相应的表列: @Column(columnDefinition = "char")
- 对于H2和@Column(columnDefinition = "bpchar")
-对于Postgres 。 我怎样才能做到这一点? 我的意思是,是否可以根据活动配置文件设置columnDefinition
属性的值,以免为每个配置文件创建两个不同的User
实体?
@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;
}
您可以尝试坚持@Column(columnDefinition = "bpchar")
并将;MODE=PostgreSQL
附加到 H2 JDBC 连接字符串。
如果那不起作用,也许这个答案会有所帮助。
如果这也不起作用,那么我建议在它下面给出答案。
我认为您不需要 columnDefinition,只需使用 @Column
在注释中,您可以使用 final var。 因此,您需要添加一个最终变量来保存您的 tokenType。 此变量将从活动配置文件中填充。 你可以使用这样的东西:
@Value("${tokenType}") // will take the value from active profile
private final String tokenType = "char";
@Column(columnDefinition = tokenType)
private final String resetToken;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.