Search code examples
javasqlhibernatehql

Hibernate delete all rows and start indexing from 1


I want to update my database every night for new values. Simply speaking 'start over' by deleting all rows and store new data.

So far I'm doing it using these two queries:

public void deleteProduct() {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            session.createQuery("DELETE FROM Product").executeUpdate();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

And

public void saveProduct(Product student) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            // save the student object
            session.save(student);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

For each element.

The problem I'm dealing with is that after deletion and insertion of new values. The indexes of my records are started not from zero but from the number of the last row before deletion.


Solution

  • You could delete the tables, and rebuild them with an equally simple sql statement. Or, you could ignore your key value, so long as it's unique and doing it's job. Make your own column as a counter and let the key be the key. That's several alternatives right there. But I would rebuild the table if you really are liking that key to start over at 1 again.