How can I replicate “SHOW TABLES” in Hibernate?

前端 未结 3 607
感动是毒
感动是毒 2021-01-14 05:14

I\'m trying to iterate over all of my tables so I can truncate each one (at the beginning of each of my JBehave tests).

I thought I would be able to:



        
相关标签:
3条回答
  • 2021-01-14 06:02

    Try something like this:

    SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE();
    

    For columns (same situation with Hibernate) try:

    SELECT column_name FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=YOUR_TABLE_NAME
    
    0 讨论(0)
  • 2021-01-14 06:19

    if you want truncate all of your table you can set hibernate.hbm2ddl.auto in hibernate.cfg.xml by value Create.

    <property name="hbm2ddl.auto">create</property>
    

    but if you want just get all table name and truncate some of them this method don't work.

    0 讨论(0)
  • 2021-01-14 06:20

    If you still have access to the Hibernate Configuration object, you can do this:

    for (Iterator iter=configuration.getClassMappings(); iter.hasNext();) {
      PersistentClass persistentClass = (PersistentClass)iter.next();
      String table = persistentClass.getTable().getName();
      // Code to truncate table (or just use a query with session.executeUpdate)
    }
    

    That assumes you have one table per entity and you only care about the tables that are mapped. Otherwise, you probably need to do something with the underlying connection and the DatabaseMetaData, e.g.:

    session.connection().getMetaData().getTables(catalog, schemaPattern, tableNamePattern, types)
    
    0 讨论(0)
提交回复
热议问题