在运行时发现JPA主键生成策略

时间:2018-09-25 15:39:58

标签: java hibernate jpa jpa-2.0

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

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

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

如示例中未明确指定GeneratedValue.strategy时,它默认为AUTO,并且docs for GenerationType.AUTO声明为:

  

指示持久性提供程序应为特定数据库选择适当的策略...

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

1 个答案:

答案 0 :(得分:0)

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

// 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();
    }
}