使用JPA自动建表时优雅的添加注释 |
您所在的位置:网站首页 › @columntype › 使用JPA自动建表时优雅的添加注释 |
在使用JPA自动建表时,如果需要添加注释,一般需要这样使用Column注解的columnDefinition属性。 @Column(columnDefinition="INT COMMENT '...'") private int foo;这种方式可以添加注释,但是需要把SQL片段写入注解中。不仅编写麻烦,而且当更换数据库时,因为不同的SQL方言,很有可能遇到不兼容的问题。本文介绍一种通过Hibernate的Integrator实现,且不需要修改columnDefinition的方法。 首先定义Comment注解: @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) public @interface Comment { String value() default ""; }将CommentIntegrator.java添加到项目中,并添加Hibernate配置: @Component public class HibernateConfig implements HibernatePropertiesCustomizer { @Override public void customize(Map hibernateProperties) { hibernateProperties.put("hibernate.use_sql_comments", true); hibernateProperties.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(CommentIntegrator.INSTANCE)); } }完成以上步骤之后,就可以直接使用Column注解了: @Table @Entity @Comment("Table comment") public class DemoTable { @Id @GeneratedValue @Column @Comment("Identifier comment") private Integer id; @Column @Comment("Field comment") private String field; getter setter ... }完整的代码: github.com/elyar-adil/… |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |