Hiberante reverse-generates database tables

Keywords: Database Session Hibernate xml

1,hibernate.cfg.xml

Comment out this section of configuration

<!--Update database level automatically-->
<!--<property name="hbm2ddl.auto">create</property>-->

2. New Generate Database Table Tool Class

public class HibernateSchemaExport {
    static Session session;
    static Configuration config = null;
    static Transaction tx = null;
    public static void main(String[] args) {
        try {
            config = new Configuration().configure(new File(
                    "src/main/resources/hibernate.cfg.xml"));
            System.out.println("Creating tables...");
            SessionFactory sessionFactory = config.buildSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .configure().build();
            Metadata metadata = new MetadataSources(serviceRegistry)
                    .buildMetadata();
            SchemaExport schemaExport = new SchemaExport();
            schemaExport.create(EnumSet.of(TargetType.DATABASE), metadata);
            System.out.println("Table created.");
            tx.commit();
        } catch (HibernateException e) {
            e.printStackTrace();
            try {
                tx.rollback();
            } catch (HibernateException e1) {
                e1.printStackTrace();
            }
        } finally {
        }
    }
}

3. Create the database configured in the JDBC link in the database

4. Execute tool class code main

Appendix: Solutions for not generating tables after program execution

(1) No error status: checkHibernate.cfg.xmlWith regard to the configuration of dialects in the file, the author initially configured the dialect of MySQL57Dialect. The database tables were not generated successfully and were replaced with 55 dialects to solve this problem.

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL55Dialect</property>

(2) The error message is as follows:

Check the JDBC configuration information about whether the database name matches the manually created database name.

Posted by rigi2 on Sat, 18 Jul 2020 08:49:13 -0700