截断/删除给定的实体类 [英] truncate/delete from given the entity class

查看:131
本文介绍了截断/删除给定的实体类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过方法获得了我的实体类。我试图找出,如何通过JPA JPQL或Criteria API我可以发出截断或删除。我认为标准api对于使用类更自然,而截断是一个更快的操作,所以这些是首选。这是我到目前为止所写的内容,但不确定添加/更改内容。

I have my entity class available via a method. I'm trying to figure out, how via the JPA JPQL or Criteria API's I could issue a truncate or delete from. I think that the criteria api is more natural for working with classes, and truncate is a faster operation so these are prefered. This is what I put together so far, but not sure what to add/change about it.

    CriteriaBuilder cb = this._em().getCriteriaBuilder();
    cb.createQuery( _entityClass() ).from( _entityClass() );

注意: _entityClass 返回 MyEntity.class ,我没有其他对 MyEntity 的引用这是一个更通用的实现。

note: _entityClass returns MyEntity.class, I have no other references to MyEntity this is a more generalized implementation.

推荐答案

假设 MyEntity 引用您要删除的表,您可以按以下步骤操作:

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();
}



类似于JPQL / SQL查询:


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();
}

使用Criteria API,您只能使用SELECT,UPDATE,DELETE语句,因此TRUNCATE是不可能。

With Criteria API you can only use SELECT, UPDATE, DELETE statements therefore TRUNCATE is not possible.

这篇关于截断/删除给定的实体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆