Search in sources :

Example 26 with SingularAttribute

use of javax.persistence.metamodel.SingularAttribute in project teiid by teiid.

the class JPAMetadataProcessor method addPrimaryKey.

private void addPrimaryKey(MetadataFactory mf, Metamodel model, EntityType<?> entity, Table entityTable) throws TranslatorException {
    // figure out the PK
    if (entity.hasSingleIdAttribute()) {
        if (entity.getIdType().getPersistenceType().equals(PersistenceType.BASIC)) {
            SingularAttribute<?, ?> pkattr = entity.getId(entity.getIdType().getJavaType());
            addColumn(mf, pkattr.getName(), TypeFacility.getDataTypeName(getJavaDataType(pkattr.getJavaType())), entityTable);
            // $NON-NLS-1$
            mf.addPrimaryKey("PK_" + entity.getName(), Arrays.asList(pkattr.getName()), entityTable);
        } else if (entity.getIdType().getPersistenceType().equals(PersistenceType.EMBEDDABLE)) {
            SingularAttribute<?, ?> pkattr = entity.getId(entity.getIdType().getJavaType());
            for (EmbeddableType<?> embeddable : model.getEmbeddables()) {
                if (embeddable.getJavaType().equals(pkattr.getJavaType())) {
                    addSingularAttributes(mf, model, embeddable, entityTable, Collections.singletonList(pkattr.getName()));
                    ArrayList<String> keys = new ArrayList<String>();
                    for (Attribute<?, ?> attr : embeddable.getAttributes()) {
                        if (isSimpleType(attr.getJavaType()) || attr.getJavaType().isEnum()) {
                            keys.add(String.join("_", pkattr.getName(), attr.getName()));
                        } else {
                            throw new TranslatorException(JPAPlugin.Util.gs(JPAPlugin.Event.TEIID14003, entityTable.getName()));
                        }
                    }
                    mf.addPrimaryKey("PK_" + pkattr.getName(), keys, entityTable);
                    break;
                }
            }
        }
    } else {
        // Composite PK. If the PK is specified with @IdClass then read its attributes,
        // if those attributes are not found, add them as columns then as composite PK
        ArrayList<String> keys = new ArrayList<String>();
        for (Object obj : entity.getIdClassAttributes()) {
            SingularAttribute<?, ?> attr = (SingularAttribute) obj;
            addColumn(mf, attr.getName(), TypeFacility.getDataTypeName(getJavaDataType(attr.getJavaType())), entityTable);
            keys.add(attr.getName());
        }
        mf.addPrimaryKey("PK_" + entity.getName(), keys, entityTable);
    }
}
Also used : EmbeddableType(javax.persistence.metamodel.EmbeddableType) SingularAttribute(javax.persistence.metamodel.SingularAttribute) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) ArrayList(java.util.ArrayList) TranslatorException(org.teiid.translator.TranslatorException)

Example 27 with SingularAttribute

use of javax.persistence.metamodel.SingularAttribute in project jbpm by kiegroup.

the class AuditQueryCriteriaUtil method variableInstanceLogSpecificCreatePredicateFromSingleCriteria.

@SuppressWarnings("unchecked")
public static <Q, T> Predicate variableInstanceLogSpecificCreatePredicateFromSingleCriteria(CriteriaQuery<Q> query, CriteriaBuilder builder, QueryCriteria criteria, Root<T> table) {
    Predicate predicate;
    if (LAST_VARIABLE_LIST.equals(criteria.getListId())) {
        Subquery<VariableInstanceLog> maxIdSubQuery = query.subquery(VariableInstanceLog.class);
        Root from = maxIdSubQuery.from(VariableInstanceLog.class);
        maxIdSubQuery.select(builder.max(from.get(VariableInstanceLog_.id)));
        maxIdSubQuery.groupBy(from.get(VariableInstanceLog_.variableId), from.get(VariableInstanceLog_.processInstanceId));
        Attribute varIdField = VariableInstanceLog_.id;
        // TODO: add the current group's criteria list to the subquery,
        // in order to make the subquery more efficient
        // -- but that requires making the criteria list available here as an argument.. :/
        Expression expr;
        if (varIdField instanceof SingularAttribute) {
            expr = table.get((SingularAttribute<T, ?>) varIdField);
        } else {
            throw new IllegalStateException("Unexpected " + varIdField.getClass().getName() + " when processing last variable query criteria!");
        }
        predicate = builder.in(expr).value(maxIdSubQuery);
    } else if (VAR_VALUE_ID_LIST.equals(criteria.getListId())) {
        assert criteria.getValues().size() == 1 : "Only 1 var id/value parameter expected!";
        // extract var/val information from criteria
        Object varVal = criteria.getValues().get(0);
        String[] parts = ((String) varVal).split(VAR_VAL_SEPARATOR, 2);
        String varId = parts[1].substring(0, Integer.parseInt(parts[0]));
        String val = parts[1].substring(Integer.parseInt(parts[0]) + 1);
        // create predicates
        SingularAttribute varVarIdField = VariableInstanceLog_.variableId;
        Path varVarIdPath = table.get(varVarIdField);
        SingularAttribute varValField = VariableInstanceLog_.value;
        Path varValIdPath = table.get(varValField);
        Predicate varIdPredicate = builder.equal(varVarIdPath, varId);
        Predicate valPredicate;
        if (QueryCriteriaType.REGEXP.equals(criteria.getType())) {
            val = convertRegexToJPALikeExpression(val);
            valPredicate = builder.like(varValIdPath, val);
        } else {
            valPredicate = builder.equal(varValIdPath, val);
        }
        // intersect predicates
        predicate = builder.and(varIdPredicate, valPredicate);
    } else {
        throw new IllegalStateException("List id [" + getQueryParameterIdNameMap().get(Integer.parseInt(criteria.getListId())) + "] is not supported for queries on " + table.getJavaType().getSimpleName() + ".");
    }
    return predicate;
}
Also used : Path(javax.persistence.criteria.Path) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Root(javax.persistence.criteria.Root) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) Expression(javax.persistence.criteria.Expression) Predicate(javax.persistence.criteria.Predicate)

Example 28 with SingularAttribute

use of javax.persistence.metamodel.SingularAttribute in project jbpm by kiegroup.

the class QueryCriteriaUtil method getOrderByExpression.

/**
 * @param orderByListId
 * @param queryType
 * @param query
 * @return
 */
protected <T, R> Expression getOrderByExpression(CriteriaQuery<R> query, Class<T> queryType, String orderByListId) {
    Attribute field = getCriteriaAttributes().get(queryType).get(orderByListId);
    assert field != null : "No Attribute found for order-by listId " + orderByListId + " for result type " + queryType.getSimpleName();
    Root table = getRoot(query, queryType);
    assert table != null : "Unable to find proper table (Root) instance in query for result type " + queryType.getSimpleName();
    Path orderByPath;
    if (field instanceof SingularAttribute) {
        orderByPath = table.get((SingularAttribute) field);
    } else {
        throw new UnsupportedOperationException("Ordering by a join field is not supported!");
    }
    return orderByPath;
}
Also used : Path(javax.persistence.criteria.Path) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Root(javax.persistence.criteria.Root) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute)

Example 29 with SingularAttribute

use of javax.persistence.metamodel.SingularAttribute in project jbpm by kiegroup.

the class TaskSummaryQueryCriteriaUtil method taskImplSpecificGetEntityField.

@SuppressWarnings("unchecked")
public static <T> Expression taskImplSpecificGetEntityField(CriteriaQuery<T> query, Root<TaskImpl> taskRoot, Join<TaskImpl, TaskDataImpl> taskDataJoin, Join<TaskImpl, PeopleAssignmentsImpl> peopleAssignJoin, String listId, Attribute attr) {
    Expression entityField = null;
    if (attr != null) {
        if (listId.equals(TASK_DESCRIPTION_LIST) || listId.equals(TASK_NAME_LIST) || listId.equals(TASK_SUBJECT_LIST)) {
            // we can *not* query on @LOB annotated fields (and it would be inefficient for a query api to do this?)
            // so we query on the (max 255 char length) string equivalent fields
            entityField = getJoinedEntityField(taskRoot, (Attribute<TaskImpl, I18NTextImpl>) attr, I18NTextImpl_.shortText);
        } else if (listId.equals(ACTUAL_OWNER_ID_LIST) || listId.equals(CREATED_BY_LIST)) {
            if (taskDataJoin == null) {
                taskDataJoin = taskRoot.join(TaskImpl_.taskData);
            }
            // task -> taskData -> (actualOwn/createdBy) UserImpl ->  id
            entityField = getJoinedEntityField(taskDataJoin, (Attribute<TaskDataImpl, UserImpl>) attr, UserImpl_.id);
        } else if (listId.equals(BUSINESS_ADMIN_ID_LIST) || listId.equals(POTENTIAL_OWNER_ID_LIST) || listId.equals(STAKEHOLDER_ID_LIST) || listId.equals(EXCLUDED_OWNER_ID_LIST)) {
            if (peopleAssignJoin == null) {
                peopleAssignJoin = taskRoot.join(TaskImpl_.peopleAssignments);
            }
            // task -> peopleAssignments -> (bus admin/pot owner/stake holder/excl user) OrganizationalEntityImpl ->  id
            entityField = getJoinedEntityField(peopleAssignJoin, (Attribute<PeopleAssignmentsImpl, OrganizationalEntityImpl>) attr, OrganizationalEntityImpl_.id);
        } else {
            if (taskDataJoin == null) {
                taskDataJoin = taskRoot.join(TaskImpl_.taskData);
            }
            Class attrType = attr.getDeclaringType().getJavaType();
            From[] taskRoots = { taskRoot, taskDataJoin };
            for (From from : taskRoots) {
                if (from.getJavaType().equals(attrType)) {
                    if (attr != null) {
                        if (attr instanceof SingularAttribute) {
                            entityField = from.get((SingularAttribute) attr);
                        } else if (attr instanceof PluralAttribute) {
                            entityField = from.get((PluralAttribute) attr);
                        } else {
                            throw new IllegalStateException("Unexpected attribute type when processing criteria with list id " + listId + ": " + attr.getClass().getName());
                        }
                        break;
                    }
                }
            }
        }
    }
    return entityField;
}
Also used : SingularAttribute(javax.persistence.metamodel.SingularAttribute) Expression(javax.persistence.criteria.Expression) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) ListAttribute(javax.persistence.metamodel.ListAttribute) CollectionAttribute(javax.persistence.metamodel.CollectionAttribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute) SetAttribute(javax.persistence.metamodel.SetAttribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute) UserImpl(org.jbpm.services.task.impl.model.UserImpl) From(javax.persistence.criteria.From) TaskDataImpl(org.jbpm.services.task.impl.model.TaskDataImpl)

Example 30 with SingularAttribute

use of javax.persistence.metamodel.SingularAttribute in project tests by datanucleus.

the class MetamodelTest method testBasic.

/**
 * Test for the list of classes and their basic model info
 */
public void testBasic() {
    Metamodel model = emf.getMetamodel();
    try {
        EntityType<?> animalType = model.entity(Animal.class);
        assertNotNull(animalType);
        assertEquals("Number of Animal attributes is wrong", 2, animalType.getAttributes().size());
        Class idType = animalType.getIdType().getJavaType();
        assertEquals(String.class, idType);
        try {
            // String field (Id)
            Attribute attr = animalType.getAttribute("name");
            assertNotNull(attr);
            assertEquals(attr.getName(), "name");
            assertEquals(attr.getJavaType(), String.class);
            assertEquals(attr.getJavaMember().getName(), "name");
            assertFalse(attr.isCollection());
            assertFalse(attr.isAssociation());
            assertTrue(attr instanceof SingularAttribute);
            // PK is not optional
            assertFalse(((SingularAttribute) attr).isOptional());
            assertFalse(((SingularAttribute) attr).isVersion());
        } catch (IllegalArgumentException iae) {
            fail("Didnt find Attribute for \"name\" field of " + Animal.class.getName());
        }
        try {
            // N-1 field
            Attribute attr = animalType.getAttribute("farm");
            assertNotNull(attr);
            assertEquals(attr.getName(), "farm");
            assertEquals(attr.getJavaType(), Farm.class);
            assertEquals(attr.getJavaMember().getName(), "farm");
            assertFalse(attr.isCollection());
            assertTrue(attr.isAssociation());
            assertTrue(attr instanceof SingularAttribute);
            assertTrue(((SingularAttribute) attr).isOptional());
        } catch (IllegalArgumentException iae) {
            fail("Didnt find Attribute for \"farm\" field of " + Animal.class.getName());
        }
        // Supertype should be null
        assertNull(animalType.getSupertype());
    } catch (IllegalArgumentException iae) {
        fail("Didnt find EntityType for " + Animal.class.getName());
    }
    try {
        EntityType<?> farmType = model.entity(Farm.class);
        assertNotNull(farmType);
        assertEquals("Number of Farm attributes is wrong", 2, farmType.getAttributes().size());
        try {
            // String field
            Attribute attr = farmType.getAttribute("name");
            assertNotNull(attr);
            assertEquals(attr.getName(), "name");
            assertEquals(attr.getJavaType(), String.class);
            assertEquals(attr.getJavaMember().getName(), "name");
            assertFalse(attr.isCollection());
            assertFalse(attr.isAssociation());
        } catch (IllegalArgumentException iae) {
            fail("Didnt find Attribute for \"name\" field of " + Farm.class.getName());
        }
        try {
            // N-1 field
            Attribute attr = farmType.getAttribute("animals");
            assertNotNull(attr);
            assertEquals(attr.getName(), "animals");
            assertEquals(attr.getJavaType(), ArrayList.class);
            assertEquals(attr.getJavaMember().getName(), "animals");
            assertTrue(attr.isCollection());
            assertTrue(attr.isAssociation());
            assertTrue("Attribute for animals is not castable to ListAttribute!", attr instanceof ListAttribute);
            ListAttribute listAttr = (ListAttribute) attr;
            Type elemType = listAttr.getElementType();
            assertEquals("Element type is wrong", Animal.class, elemType.getJavaType());
        } catch (IllegalArgumentException iae) {
            fail("Didnt find Attribute for \"animals\" field of " + Farm.class.getName());
        }
    } catch (IllegalArgumentException iae) {
        fail("Didnt find EntityType for " + Farm.class.getName());
    }
    try {
        EntityType<?> personType = model.entity(Person.class);
        assertNotNull(personType);
        assertEquals("Number of Person attributes is wrong", 8, personType.getAttributes().size());
        try {
            // String field
            Attribute attr = personType.getAttribute("firstName");
            assertNotNull(attr);
            assertEquals(attr.getName(), "firstName");
            assertEquals(attr.getJavaType(), String.class);
            assertEquals(attr.getJavaMember().getName(), "firstName");
            assertFalse(attr.isCollection());
            assertFalse(attr.isAssociation());
        } catch (IllegalArgumentException iae) {
            fail("Didnt find Attribute for \"firstName\" field of " + Person.class.getName());
        }
        try {
            // int field
            Attribute attr = personType.getAttribute("age");
            assertNotNull(attr);
            assertEquals(attr.getName(), "age");
            assertEquals(attr.getJavaType(), int.class);
            assertEquals(attr.getJavaMember().getName(), "age");
            assertFalse(attr.isCollection());
            assertFalse(attr.isAssociation());
            assertTrue(attr instanceof SingularAttribute);
            assertFalse(((SingularAttribute) attr).isOptional());
        } catch (IllegalArgumentException iae) {
            fail("Didnt find Attribute for \"age\" field of " + Person.class.getName());
        }
    } catch (IllegalArgumentException iae) {
        fail("Didnt find EntityType for " + Person.class.getName());
    }
}
Also used : SingularAttribute(javax.persistence.metamodel.SingularAttribute) EntityType(javax.persistence.metamodel.EntityType) Type(javax.persistence.metamodel.Type) BindableType(javax.persistence.metamodel.Bindable.BindableType) IdentifiableType(javax.persistence.metamodel.IdentifiableType) MapAttribute(javax.persistence.metamodel.MapAttribute) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) ListAttribute(javax.persistence.metamodel.ListAttribute) Animal(org.datanucleus.samples.annotations.one_many.bidir.Animal) Farm(org.datanucleus.samples.annotations.one_many.bidir.Farm) Metamodel(javax.persistence.metamodel.Metamodel) VersionedPerson(org.datanucleus.samples.annotations.versioned.VersionedPerson) Person(org.datanucleus.samples.annotations.models.company.Person) ListAttribute(javax.persistence.metamodel.ListAttribute)

Aggregations

SingularAttribute (javax.persistence.metamodel.SingularAttribute)38 Attribute (javax.persistence.metamodel.Attribute)13 Metamodel (javax.persistence.metamodel.Metamodel)13 ListAttribute (javax.persistence.metamodel.ListAttribute)8 ArrayList (java.util.ArrayList)7 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)7 MapAttribute (javax.persistence.metamodel.MapAttribute)7 Test (org.junit.Test)7 Predicate (javax.persistence.criteria.Predicate)5 EntityType (javax.persistence.metamodel.EntityType)5 Root (javax.persistence.criteria.Root)4 PluralAttribute (javax.persistence.metamodel.PluralAttribute)4 EntityManager (javax.persistence.EntityManager)3 Path (javax.persistence.criteria.Path)3 IdentifiableType (javax.persistence.metamodel.IdentifiableType)3 Type (javax.persistence.metamodel.Type)3 VersionedPerson (org.datanucleus.samples.annotations.versioned.VersionedPerson)3 EntityTransaction (javax.persistence.EntityTransaction)2 Query (javax.persistence.Query)2 TypedQuery (javax.persistence.TypedQuery)2