8

I am trying to delete all rows in table 'user_role' with hibernate query. But every time i am getting errors. Can someone please help me with it.

DaoImpl

@Override
public void deleteAll() {
    session.getCurrentSession().delete(/*delete all query*/);
}

model class

@Entity @Table(name="user_role")
public class User_Role {

    @Id @Column @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    @Column(name="role_name")
    private String name;

    //setter and getter 
}
Sanjay Kumar
  • 415
  • 4
  • 9
  • 19

2 Answers2

12

try this:

sessionFactory.getCurrentSession().createQuery("delete from User_Role").executeUpdate();
prashant thakre
  • 5,061
  • 3
  • 26
  • 39
  • You changed the capitalization of the table, which won't work in some DB engines. This shows that repeating the table name is not a good idea (difficult maintenance item). – Stealth Rabbi Oct 29 '15 at 16:30
2

You can remove all instances of a class, one at a time, using this method. It's slower if you have many records, however, you're not duplicating the literal string for the table name.

public static void removeAllInstances(final Class<?> clazz) {
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.getCurrentSession();       
    session.beginTransaction();
    final List<?> instances = session.createCriteria(clazz).list();
    for (Object obj : instances) {
        session.delete(obj);
    }
    session.getTransaction().commit();
}

usage:

removeAllInstances(User_Role.class);
Pehmolelu
  • 3,534
  • 2
  • 26
  • 31
Stealth Rabbi
  • 10,156
  • 22
  • 100
  • 176