【问题标题】:Discover JPA primary key generation strategy at runtime在运行时发现 JPA 主键生成策略
【发布时间】:2019-03-01 07:18:09
【问题描述】:

鉴于下面的缩写 JPA 实体,我如何发现持久性提供程序在运行时选择的 GenerationType

@Entity
@Table(name = "book")
public class Book {

    @Id
    @Column(name = "id")
    @GeneratedValue
    private Long id;
}

GeneratedValue.strategy 没有像示例中那样明确指定时,它默认为AUTOdocs for GenerationType.AUTO 声明如下:

表示持久性提供者应该为特定数据库选择合适的策略...

我想看看它在运行时实际选择了什么策略。

【问题讨论】:

  • enable the hibernate and jpa logs to trace level,可以看到它选择了什么策略。它完全取决于 DB 和 JPA。
  • @AshraffAliWahab 为什么不将其发布为答案?检查已经回答的问题很烦人。谢谢
  • @Simon 这是一个建议,不是一个完整的答案,这就是它没有发布的原因。

标签: java hibernate jpa jpa-2.0


【解决方案1】:

我会开始使用一些反射代码,例如:

// setup code, it's just my code for this test...
Book b = new Book();
PersistenceProvider pp = new HibernatePersistenceProvider();
Map<String,String> m = new HashMap<>();
BookJpaController bc = new BookJpaController( pp.createEntityManagerFactory( "myPP", m ) );
bc.create( b );

// reflective code to introspect the Entity and the PersistenceProvider
for ( Field f : b.getClass().getDeclaredFields() ) {
    if ( f.isAnnotationPresent( GeneratedValue.class ) ) {
        GeneratedValue gv = f.getAnnotation( GeneratedValue.class );
        System.out.println( gv.generator() );
        System.out.println( gv.strategy() );
        System.out.println( gv );
    }
}

for ( Field f : pp.getClass().getDeclaredFields() ) {
    try {
        f.setAccessible( true );
        System.out.println( f.getName() + " " + f.get( pp ) );
    } catch ( IllegalAccessException exc ) {
        exc.printStackTrace();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2010-12-21
    • 2016-03-23
    • 1970-01-01
    相关资源
    最近更新 更多