Java Examples for com.mysema.query.jpa.impl.JPADeleteClause

The following java examples will help you to understand the usage of com.mysema.query.jpa.impl.JPADeleteClause. These source code samples are taken from different open source projects.

Example 1
Project: opencast-master  File: AbstractADeleteQuery.java View source code
/** Run this in a transaction. */
private DeletionResult runQueries(JPAQueryFactory jpa, DeleteQueryContribution c) {
    // # create Querydsl delete clause
    // # from
    // put into a set to remove duplicates
    final EntityPath<?> from;
    {
        final Set<EntityPath<?>> f = c.from.toSet(SetB.MH);
        if (f.size() == 1) {
            from = $(f).head2();
        } else {
            throw new RuntimeException("Only one entity is allowed in the from clause");
        }
    }
    //
    if (from instanceof QSnapshotDto) {
        // from Snapshot
        //
        final BooleanExpression where = Expressions.allOf(c.targetPredicate.orNull(), c.where.apply(Q_SNAPSHOT));
        // get snapshots to delete
        // TODO ATTENTION: this query has the potential to yield a massive amount of elements
        // return the list of snapshots to delete them outside the transaction since
        // it may take a while.
        final List<Tuple> deletedSnapshots = jpa.query().from(Q_SNAPSHOT).where(where).list(Q_SNAPSHOT.organizationId, Q_SNAPSHOT.mediaPackageId, Q_SNAPSHOT.version);
        // <BLOCK>
        // TODO database only approach to determine deleted episodes
        // TODO does not run with H2 so unit tests break
        /*
SELECT
  e.mediapackage_id,
  count(*) AS v
FROM mh_assets_snapshot e
GROUP BY e.mediapackage_id
HAVING v = (SELECT count(*)
            FROM mh_assets_snapshot e2
            WHERE e.mediapackage_id = e2.mediapackage_id
                  AND
                  -- delete where clause
                  (e2.version = 2 OR e2.mediapackage_id = '24ec925e-ea57-43a5-a7bb-58dc5aae54dd')
            GROUP BY mediapackage_id);
       */
        //      final QSnapshotDto e2 = new QSnapshotDto("eee");
        //      final List<String> deletedSnapshots = jpa.query()
        //              .from(e2)
        //              .groupBy(e2.mediaPackageId)
        //              .having(e2.count().eq(
        //                      jpa.subQuery()
        //                              .from(Q_SNAPSHOT)
        //                              .where(Q_SNAPSHOT.mediaPackageId.eq(e2.mediaPackageId).and(where))
        //                              .groupBy(Q_SNAPSHOT.mediaPackageId)
        //                              .count()))
        //              .list(e2.mediaPackageId);
        // </BLOCK>
        // delete assets from database
        final JPADeleteClause qAssets = jpa.delete(Q_ASSET).where(Q_ASSET.snapshotId.in(new JPASubQuery().from(Q_SNAPSHOT).where(where).list(Q_SNAPSHOT.id)));
        am.getDb().logDelete(formatQueryName(c.name, "delete assets"), qAssets);
        qAssets.execute();
        // main delete query
        final JPADeleteClause qMain = jpa.delete(Q_SNAPSHOT).where(where);
        am.getDb().logDelete(formatQueryName(c.name, "main"), qMain);
        final long deletedItems = qMain.execute();
        // delete orphaned properties
        deleteOrphanedProperties();
        // <BLOCK>
        // TODO Bad solution. Yields all media package IDs which can easily be thousands
        // TODO The above SQL solution does not work with H2 so I suspect the query is not 100% clean
        // TODO Rework the query and replace this code.
        // calculate deleted episodes, i.e. where all snapshots have been deleted
        final Set<String> deletedEpisodes;
        {
            final List<String> remainingSnapshots = jpa.query().from(Q_SNAPSHOT).distinct().list(Q_SNAPSHOT.mediaPackageId);
            final Set<String> d = $(deletedSnapshots).map(new Fn<Tuple, String>() {

                @Override
                public String apply(Tuple tuple) {
                    return tuple.get(Q_SNAPSHOT.mediaPackageId);
                }
            }).toSet(SetB.MH);
            d.removeAll(remainingSnapshots);
            deletedEpisodes = Collections.unmodifiableSet(d);
        }
        // </BLOCK>
        return new DeletionResult(deletedItems, deletedSnapshots, deletedEpisodes);
    } else if (from instanceof QPropertyDto) {
        // from Property
        //
        final BooleanExpression where;
        {
            final BooleanExpression w = c.where.apply(Q_PROPERTY);
            if (w != null) {
                /* The original sub query used an "ON" clause to filter the join by mediapackage id [1].
             Unfortunately Eclipse link drops this clause completely when transforming the query
             into SQL. It creates a cross join instead of the inner join, which is perfectly legal
             if the "ON" clause would be moved to the "WHERE" clause.
             The example [2] shows that neither an "ON" clause nor an additional "WHERE" predicate is generated.

             [1]
             new JPASubQuery()
                .from(Q_PROPERTY)
                .join(Q_SNAPSHOT) <- inner join
                .on(Q_PROPERTY.mediaPackageId.eq(Q_SNAPSHOT.mediaPackageId)) <- dropped by Eclipse link
                .where(Q_PROPERTY.mediaPackageId.eq(Q_SNAPSHOT.mediaPackageId).and(w))
                .distinct()
                .list(Q_PROPERTY.mediaPackageId)

             [2]
             SELECT DISTINCT t1.mediapackage_id FROM mh_assets_snapshot t2, mh_assets_properties t1 WHERE (t2.organization_id = ?)
           */
                where = Q_PROPERTY.mediaPackageId.in(new JPASubQuery().from(Q_PROPERTY).join(Q_SNAPSHOT).where(// move the join condition from the "ON" clause (mediapackage_id) to the where clause. Find an explanation above. */
                Q_PROPERTY.mediaPackageId.eq(Q_SNAPSHOT.mediaPackageId).and(w)).distinct().list(Q_PROPERTY.mediaPackageId));
            } else {
                where = null;
            }
        }
        final JPADeleteClause qProperties = jpa.delete(from).where(Expressions.allOf(c.targetPredicate.orNull(), where));
        am.getDb().logDelete(formatQueryName(c.name, "main"), qProperties);
        final long deletedItems = qProperties.execute();
        return new DeletionResult(deletedItems, Collections.<Tuple>emptyList(), Collections.<String>emptySet());
    } else {
        // from contains an unsupported entity
        throw new RuntimeException("[Bug]");
    }
}
Example 2
Project: gvnix-master  File: JpaBatchMetadata.java View source code
/**
     * Builds body method for <code>deleteByValues</code> method. <br>
     * This method performs a delete base on property values condition (value
     * equal and concatenates conditions using "and" operator)
     * 
     * @param bodyBuilder
     */
private void buildDeleteByValuesMethodBody(InvocableMemberBodyBuilder bodyBuilder) {
    if (useBulkStatements) {
        //
        bodyBuilder.appendFormalLine("");
        //
        // // if there no is a filter
        bodyBuilder.appendFormalLine("// if there no is a filter");
        // if (propertyValues == null || propertyValues.isEmpty()) {
        bodyBuilder.appendFormalLine("if (propertyValues == null || propertyValues.isEmpty()) {");
        bodyBuilder.indent();
        // throw new IllegalArgumentException("Missing property values");
        bodyBuilder.appendFormalLine("throw new IllegalArgumentException(\"Missing property values\");");
        bodyBuilder.indentRemove();
        bodyBuilder.appendFormalLine("}");
        // // Prepare a predicate
        bodyBuilder.appendFormalLine("// Prepare a predicate");
        // BooleanBuilder baseFilterPredicate = new BooleanBuilder();
        bodyBuilder.appendFormalLine(String.format("%s baseFilterPredicate = new %s();", helper.getFinalTypeName(QDSL_BOOLEAN_BUILDER), helper.getFinalTypeName(QDSL_BOOLEAN_BUILDER)));
        bodyBuilder.appendFormalLine("");
        // // Base filter. Using BooleanBuilder, a cascading builder for
        bodyBuilder.appendFormalLine("// Base filter. Using BooleanBuilder, a cascading builder for");
        // // Predicate expressions
        bodyBuilder.appendFormalLine("// Predicate expressions");
        // PathBuilder<Visit> entity = new PathBuilder<Visit>(Visit.class,
        // "entity");
        bodyBuilder.appendFormalLine(String.format("%s<%s> entity = new %s<%s>(%s.class, \"entity\");", helper.getFinalTypeName(QDSL_PATH_BUILDER), helper.getFinalTypeName(entity), helper.getFinalTypeName(QDSL_PATH_BUILDER), helper.getFinalTypeName(entity), helper.getFinalTypeName(entity)));
        bodyBuilder.appendFormalLine("");
        //
        // // Build base filter
        bodyBuilder.appendFormalLine("// Build base filter");
        // for (String key : propertyMap.keySet()) {
        bodyBuilder.appendFormalLine("for (String key : propertyValues.keySet()) {");
        bodyBuilder.indent();
        // baseFilterPredicate.and(entity.get(key).eq(propertyMap.get(key)));
        bodyBuilder.appendFormalLine("baseFilterPredicate.and(entity.get(key).eq(propertyValues.get(key)));");
        // }
        bodyBuilder.indentRemove();
        bodyBuilder.appendFormalLine("}");
        bodyBuilder.appendFormalLine("");
        //
        // // Create a query with filter
        bodyBuilder.appendFormalLine("// Create a query with filter");
        // JPADeleteClause delete = new
        // JPADeleteClause(Visit.entityManager(),entity);
        bodyBuilder.appendFormalLine(String.format("%s delete = new %s(%s.entityManager(),entity);", helper.getFinalTypeName(QDSL_JPA_DELETE_CLAUSE), helper.getFinalTypeName(QDSL_JPA_DELETE_CLAUSE), helper.getFinalTypeName(entity)));
        //
        bodyBuilder.appendFormalLine("");
        // // execute delete
        bodyBuilder.appendFormalLine("// execute delete");
        // return delete.where(baseFilterPredicate).execute();
        bodyBuilder.appendFormalLine("return delete.where(baseFilterPredicate).execute();");
    } else {
        // List<Visit> visits = findByValues(propertyValues);
        bodyBuilder.appendFormalLine(String.format("%s %s = %s(propertyValues);", helper.getFinalTypeName(listOfEntitiesType), StringUtils.uncapitalize(entityPlural), FIND_BY_VALUES_METHOD));
        // delete(visits);
        bodyBuilder.appendFormalLine(String.format("%s(%s);", DELETE_METHOD, StringUtils.uncapitalize(entityPlural)));
        // return (long)visits.size();
        bodyBuilder.appendFormalLine(String.format("return (long)%s.size();", StringUtils.uncapitalize(entityPlural)));
    }
}
Example 3
Project: knorxx-master  File: InitializeDatabase.java View source code
@PostConstruct
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void initializeDatabase() {
    new JPADeleteClause(entityManager, QTestEntity.testEntity).execute();
    TestEntity testEntity = new TestEntity();
    testEntity.setName("Darkwing Duck");
    entityManager.persist(testEntity);
}
Example 4
Project: brainslug-master  File: Database.java View source code
public JPADeleteClause delete(EntityPath<?> path) {
    return new JPADeleteClause(entityManager, path, jpqlDialect);
}
Example 5
Project: Polyforms-master  File: Delete.java View source code
@Override
protected Object getResult(final EntityPath<?> entityPath, final Method method, final Object... arguments) {
    final JPADeleteClause deleteClause = new JPADeleteClause(entityManager, entityPath).where((Predicate) arguments[0]);
    return deleteClause.execute();
}