Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to delete all rows in a table hibernate

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 
}
like image 425
Sanjay Kumar Avatar asked Aug 02 '14 16:08

Sanjay Kumar


People also ask

How can I delete multiple rows in hibernate?

class, new Long(temp[i])); if(i%50==0) { session. flush(); session. clear(); } session. delete(c); } //session.

What does Sess delete () do in Hibernate framework?

In JavaDoc of Session class the description of delete method is: Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving Session or a transient instance with an identifier associated with existing persistent state.

How do you fetch all the records in a given table using hibernate?

JPQL provides a simple and straightforward way to get all entities from a table. Our Hibernate session's createQuery() method receives a typed query string as the first argument and the entity's type as the second. We execute the query with a call to the getResultList() method which returns the results as a typed List.

How to perform delete operation in hibernate?

In Hibernate, an entity can be removed from a database by calling the Session. delete() or Session. remove(). Using these methods, we can remove a transient or persistent object from datastore.


2 Answers

try this:

sessionFactory.getCurrentSession().createQuery("delete from User_Role").executeUpdate();
like image 131
prashant thakre Avatar answered Sep 29 '22 14:09

prashant thakre


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);
like image 38
Stealth Rabbi Avatar answered Sep 29 '22 13:09

Stealth Rabbi