How to make Hibernate not drop tables
<property name="hibernate.hbm2ddl.auto">update</property>
tells hibernate to update the database schema each time the session factory is created.
And
SessionFactory factory = new Configuration().configure().buildSessionFactory();
builds a new session factory.
A SessionFactory
should be built only once during the wole application lifetime. It should be created once and then reused. Have you read the hibernate reference manual?
I had
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.hbm2ddl.import_files" value="META-INF/import.sql" />
the first time I deployed. This created my desired schema and populate it with data. The second time I changed to
<property name="hibernate.hbm2ddl.auto" value="update" />
and redeployed. Obviously the tables were dropped. I switched to create
for the first deployment and stayed with update
with the redeployments. This time tables were not dropped and data stayed untouched.
Are you sure it gets overwritten or does it not commit? I mean are you commiting your transactions?
Maybe try something in the lines of:
try {
factory.getCurrentSession().beginTransaction();
// Do some work
factory.getCurrentSession().load(...);
factory.getCurrentSession().persist(...);
factory.getCurrentSession().getTransaction().commit();
}
catch (RuntimeException e) {
factory.getCurrentSession().getTransaction().rollback();
throw e; // or display error message
}
Hope this can help you
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
config.configure("hibernate.cfg.xml");
new SchemaExport(config).drop(false, false);