Query to delete all rows in a table hibernate

☆樱花仙子☆ 提交于 2019-12-10 13:06:26

问题


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 
}

回答1:


try this:

sessionFactory.getCurrentSession().createQuery("delete from User_Role").executeUpdate();



回答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);


来源:https://stackoverflow.com/questions/25097385/query-to-delete-all-rows-in-a-table-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!