Assuming that MyEntity
refers to the table you want to drop you can proceed as follows:
// Criteria API (JPA 2.1 and above)
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaDelete<MyEntity> query = builder.createCriteriaDelete(MyEntity.class);
query.from(MyEntity.class);
em.createQuery(query).executeUpdate();
or with a generalized approach:
public <T> int deleteAllEntities(Class<T> entityType) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaDelete<T> query = builder.createCriteriaDelete(entityType);
query.from(entityType);
return em.createQuery(query).executeUpdate();
}
Similarly for JPQL/SQL queries:
// JPQL
em.createQuery("DELETE FROM MyEntity e").executeUpdate();
// SQL
em.createNativeQuery("TRUNCATE TABLE MyEntity").executeUpdate();
or with a generalized approach:
public static <T> int deleteAllEntities(Class<T> entityType) {
String query = new StringBuilder("DELETE FROM ")
.append(entityType.getSimpleName())
.append(" e")
.toString();
return em.createQuery(query).executeUpdate();
}
public static <T> int truncateTable(Class<T> entityType) {
String query = new StringBuilder("TRUNCATE TABLE ")
.append(entityType.getSimpleName())
.toString();
return em.createNativeQuery(query).executeUpdate();
}
With Criteria API you can only use SELECT, UPDATE, DELETE statements therefore TRUNCATE is not possible.
truncate
in JPQL, you can write a native query for that or use JPQL "delete". – Automatic