javax.persistence.DiscriminatorValue Java Examples

The following examples show how to use javax.persistence.DiscriminatorValue. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JPAOverriddenAnnotationReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private DiscriminatorValue getDiscriminatorValue(Element tree, XMLContext.Default defaults) {
	Element element = tree != null ? tree.element( "discriminator-value" ) : null;
	if ( element != null ) {
		AnnotationDescriptor ad = new AnnotationDescriptor( DiscriminatorValue.class );
		copyStringElement( element, ad, "value" );
		return AnnotationFactory.create( ad );
	}
	else if ( defaults.canUseJavaAnnotations() ) {
		return getPhysicalAnnotation( DiscriminatorValue.class );
	}
	else {
		return null;
	}
}
 
Example #2
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheClassNameWithSingleTableInheritance() throws Exception {
    final String simpleClassNameBase = "EntityClass";
    final String simpleClassNameA = "SubEntityClassA";
    final String simpleClassNameB = "SubEntityClassB";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jBaseClass = jp._class(JMod.PUBLIC, simpleClassNameBase);
    jBaseClass.annotate(Entity.class);
    jBaseClass.annotate(Inheritance.class).param("strategy", InheritanceType.SINGLE_TABLE);
    jBaseClass.annotate(DiscriminatorColumn.class).param("name", "TYPE");

    final JDefinedClass jSubclassA = jp._class(JMod.PUBLIC, simpleClassNameA)._extends(jBaseClass);
    jSubclassA.annotate(Entity.class);
    jSubclassA.annotate(DiscriminatorValue.class).param("value", "A");

    final JDefinedClass jSubclassB = jp._class(JMod.PUBLIC, simpleClassNameB)._extends(jBaseClass);
    jSubclassB.annotate(Entity.class);
    jSubclassB.annotate(DiscriminatorValue.class).param("value", "B");

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> baseClass = loadClass(testFolder.getRoot(), jBaseClass.name());
    final Class<?> subClassA = loadClass(testFolder.getRoot(), jSubclassA.name());
    final Class<?> subClassB = loadClass(testFolder.getRoot(), jSubclassB.name());

    final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(simpleClassNameBase),
            Arrays.asList(baseClass, subClassA, subClassB));

    assertThat(clazz, equalTo(baseClass));
}
 
Example #3
Source File: EntityUtilsTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheTableAnnotationWithSingleTableInheritance() throws Exception {
    final String simpleClassNameBase = "EntityClass";
    final String simpleClassNameA = "SubEntityClassA";
    final String simpleClassNameB = "SubEntityClassB";

    final String nodeLabel = "ENTITY_CLASS";

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jBaseClass = jp._class(JMod.PUBLIC, simpleClassNameBase);
    jBaseClass.annotate(Entity.class);
    jBaseClass.annotate(Table.class).param("name", nodeLabel);
    jBaseClass.annotate(Inheritance.class).param("strategy", InheritanceType.SINGLE_TABLE);
    jBaseClass.annotate(DiscriminatorColumn.class).param("name", "TYPE");

    final JDefinedClass jSubclassA = jp._class(JMod.PUBLIC, simpleClassNameA)._extends(jBaseClass);
    jSubclassA.annotate(Entity.class);
    jSubclassA.annotate(DiscriminatorValue.class).param("value", "A");

    final JDefinedClass jSubclassB = jp._class(JMod.PUBLIC, simpleClassNameB)._extends(jBaseClass);
    jSubclassB.annotate(Entity.class);
    jSubclassB.annotate(DiscriminatorValue.class).param("value", "B");

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    final Class<?> baseClass = loadClass(testFolder.getRoot(), jBaseClass.name());
    final Class<?> subClassA = loadClass(testFolder.getRoot(), jSubclassA.name());
    final Class<?> subClassB = loadClass(testFolder.getRoot(), jSubclassB.name());

    final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(nodeLabel),
            Arrays.asList(baseClass, subClassA, subClassB));

    assertThat(clazz, equalTo(baseClass));
}
 
Example #4
Source File: IntegerDiscriminatorDescriptionTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Override
protected void afterInit() {
    doInJPA(this::addConsistencyTriggers);

    doInJPA(entityManager -> {
        for (Class entityClass : entities()) {
            if (Topic.class.isAssignableFrom(entityClass)) {

                DiscriminatorValue discriminatorValue = (DiscriminatorValue)
                    entityClass.getAnnotation(DiscriminatorValue.class);

                TopicType topicType = new TopicType();
                topicType.setId(Byte.valueOf(discriminatorValue.value()));
                topicType.setName(entityClass.getName());
                topicType.setDescription(
                    Topic.class.equals(entityClass) ?
                        "Topic is the base class of the Topic entity hierarchy" :
                        String.format(
                            "%s is a subclass of the Topic base class",
                            entityClass.getSimpleName()
                        )
                );

                entityManager.persist(topicType);
            }
        }
    });
}
 
Example #5
Source File: JPATaskDAO.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static String getEntityTableName(final TaskType type) {
    String result = null;

    switch (type) {
        case NOTIFICATION:
            result = JPANotificationTask.class.getAnnotation(DiscriminatorValue.class).value();
            break;

        case PROPAGATION:
            result = JPAPropagationTask.class.getAnnotation(DiscriminatorValue.class).value();
            break;

        case PUSH:
            result = JPAPushTask.class.getAnnotation(DiscriminatorValue.class).value();
            break;

        case SCHEDULED:
            result = JPASchedTask.class.getAnnotation(DiscriminatorValue.class).value();
            break;

        case PULL:
            result = JPAPullTask.class.getAnnotation(DiscriminatorValue.class).value();
            break;

        default:
    }

    return result;
}
 
Example #6
Source File: ImageProfile.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gets the image type value as specified in {@code @DiscriminatorValue} annotation
 * @return the image type
 */
@Transient
public String getImageType() {
    return this.getClass().getAnnotation(DiscriminatorValue.class).value();
}
 
Example #7
Source File: AnnotationBinder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Process all discriminator-related metadata per rules for "single table" inheritance
 */
private static Ejb3DiscriminatorColumn processSingleTableDiscriminatorProperties(
		XClass clazzToProcess,
		MetadataBuildingContext context,
		InheritanceState inheritanceState,
		EntityBinder entityBinder) {
	final boolean isRoot = !inheritanceState.hasParents();

	Ejb3DiscriminatorColumn discriminatorColumn = null;
	javax.persistence.DiscriminatorColumn discAnn = clazzToProcess.getAnnotation(
			javax.persistence.DiscriminatorColumn.class
	);
	DiscriminatorType discriminatorType = discAnn != null
			? discAnn.discriminatorType()
			: DiscriminatorType.STRING;

	org.hibernate.annotations.DiscriminatorFormula discFormulaAnn = clazzToProcess.getAnnotation(
			org.hibernate.annotations.DiscriminatorFormula.class
	);
	if ( isRoot ) {
		discriminatorColumn = Ejb3DiscriminatorColumn.buildDiscriminatorColumn(
				discriminatorType,
				discAnn,
				discFormulaAnn,
				context
		);
	}
	if ( discAnn != null && !isRoot ) {
		LOG.invalidDiscriminatorAnnotation( clazzToProcess.getName() );
	}

	final String discriminatorValue = clazzToProcess.isAnnotationPresent( DiscriminatorValue.class )
			? clazzToProcess.getAnnotation( DiscriminatorValue.class ).value()
			: null;
	entityBinder.setDiscriminatorValue( discriminatorValue );

	DiscriminatorOptions discriminatorOptions = clazzToProcess.getAnnotation( DiscriminatorOptions.class );
	if ( discriminatorOptions != null) {
		entityBinder.setForceDiscriminator( discriminatorOptions.force() );
		entityBinder.setInsertableDiscriminator( discriminatorOptions.insert() );
	}

	return discriminatorColumn;
}
 
Example #8
Source File: AnnotationBinder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Process all discriminator-related metadata per rules for "joined" inheritance
 */
private static Ejb3DiscriminatorColumn processJoinedDiscriminatorProperties(
		XClass clazzToProcess,
		MetadataBuildingContext context,
		InheritanceState inheritanceState,
		EntityBinder entityBinder) {
	if ( clazzToProcess.isAnnotationPresent( DiscriminatorFormula.class ) ) {
		throw new MappingException( "@DiscriminatorFormula on joined inheritance not supported at this time" );
	}


	// DiscriminatorValue handling ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	final DiscriminatorValue discriminatorValueAnnotation = clazzToProcess.getAnnotation( DiscriminatorValue.class );
	final String discriminatorValue = discriminatorValueAnnotation != null
			? clazzToProcess.getAnnotation( DiscriminatorValue.class ).value()
			: null;
	entityBinder.setDiscriminatorValue( discriminatorValue );


	// DiscriminatorColumn handling ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	final DiscriminatorColumn discriminatorColumnAnnotation = clazzToProcess.getAnnotation( DiscriminatorColumn.class );
	if ( !inheritanceState.hasParents() ) {
		// we want to process the discriminator column if either:
		//		1) There is an explicit DiscriminatorColumn annotation && we are not told to ignore them
		//		2) There is not an explicit DiscriminatorColumn annotation && we are told to create them implicitly
		final boolean generateDiscriminatorColumn;
		if ( discriminatorColumnAnnotation != null ) {
			if ( context.getBuildingOptions().ignoreExplicitDiscriminatorsForJoinedInheritance() ) {
				LOG.debugf( "Ignoring explicit DiscriminatorColumn annotation on ", clazzToProcess.getName() );
				generateDiscriminatorColumn = false;
			}
			else {
				LOG.applyingExplicitDiscriminatorColumnForJoined(
						clazzToProcess.getName(),
						AvailableSettings.IGNORE_EXPLICIT_DISCRIMINATOR_COLUMNS_FOR_JOINED_SUBCLASS
				);
				generateDiscriminatorColumn = true;
			}
		}
		else {
			if ( context.getBuildingOptions().createImplicitDiscriminatorsForJoinedInheritance() ) {
				LOG.debug( "Applying implicit DiscriminatorColumn using DiscriminatorColumn defaults" );
				generateDiscriminatorColumn = true;
			}
			else {
				LOG.debug( "Ignoring implicit (absent) DiscriminatorColumn" );
				generateDiscriminatorColumn = false;
			}
		}

		if ( generateDiscriminatorColumn ) {
			final DiscriminatorType discriminatorType = discriminatorColumnAnnotation != null
					? discriminatorColumnAnnotation.discriminatorType()
					: DiscriminatorType.STRING;
			return Ejb3DiscriminatorColumn.buildDiscriminatorColumn(
					discriminatorType,
					discriminatorColumnAnnotation,
					null,
					context
			);
		}
	}
	else {
		if ( discriminatorColumnAnnotation != null ) {
			LOG.invalidDiscriminatorAnnotation( clazzToProcess.getName() );
		}
	}

	return null;
}
 
Example #9
Source File: JPATaskDAO.java    From syncope with Apache License 2.0 4 votes vote down vote up
private static StringBuilder buildFindAllQuery(
    final TaskType type,
    final ExternalResource resource,
    final Notification notification,
    final AnyTypeKind anyTypeKind,
    final String entityKey,
    final boolean orderByTaskExecInfo,
    final List<Object> queryParameters) {

    if (resource != null
            && type != TaskType.PROPAGATION && type != TaskType.PUSH && type != TaskType.PULL) {

        throw new IllegalArgumentException(type + " is not related to " + ExternalResource.class.getSimpleName());
    }

    if ((anyTypeKind != null || entityKey != null)
            && type != TaskType.PROPAGATION && type != TaskType.NOTIFICATION) {

        throw new IllegalArgumentException(type + " is not related to users, groups or any objects");
    }

    if (notification != null && type != TaskType.NOTIFICATION) {
        throw new IllegalArgumentException(type + " is not related to notifications");
    }

    StringBuilder queryString = new StringBuilder("SELECT ").append(AbstractTask.TABLE).append(".*");

    if (orderByTaskExecInfo) {
        queryString.append(',').append(JPATaskExec.TABLE).append(".startDate AS startDate").
                append(',').append(JPATaskExec.TABLE).append(".endDate AS endDate").
                append(',').append(JPATaskExec.TABLE).append(".status AS status").
                append(" FROM ").append(AbstractTask.TABLE).
                append(',').append(JPATaskExec.TABLE).append(',').append("(SELECT ").
                append(JPATaskExec.TABLE).append(".task_id, ").
                append("MAX(").append(JPATaskExec.TABLE).append(".startDate) AS startDate").
                append(" FROM ").append(JPATaskExec.TABLE).
                append(" GROUP BY ").append(JPATaskExec.TABLE).append(".task_id) GRP").
                append(" WHERE ").
                append(AbstractTask.TABLE).append(".id=").append(JPATaskExec.TABLE).append(".task_id").
                append(" AND ").append(AbstractTask.TABLE).append(".id=").append("GRP.task_id").
                append(" AND ").append(JPATaskExec.TABLE).append(".startDate=").append("GRP.startDate").
                append(" AND ").append(AbstractTask.TABLE).append(".DTYPE = ?1");
    } else {
        queryString.append(", null AS startDate, null AS endDate, null AS status FROM ").append(AbstractTask.TABLE).
                append(" WHERE ").append(AbstractTask.TABLE).append(".DTYPE = ?1");
    }

    queryParameters.add(getEntityTableName(type));
    if (type == TaskType.SCHEDULED) {
        queryString.append(" AND ").
                append(AbstractTask.TABLE).
                append(".id NOT IN (SELECT ").append(AbstractTask.TABLE).append(".id FROM ").
                append(AbstractTask.TABLE).append(" WHERE ").
                append(AbstractTask.TABLE).append(".DTYPE = ?2)").
                append(" AND ").
                append(AbstractTask.TABLE).
                append(".id NOT IN (SELECT id FROM ").
                append(AbstractTask.TABLE).append(" WHERE ").
                append(AbstractTask.TABLE).append(".DTYPE = ?3)");

        queryParameters.add(JPAPushTask.class.getAnnotation(DiscriminatorValue.class).value());
        queryParameters.add(JPAPullTask.class.getAnnotation(DiscriminatorValue.class).value());
    }
    queryString.append(' ');

    if (resource != null) {
        queryParameters.add(resource.getKey());

        queryString.append(" AND ").
                append(AbstractTask.TABLE).
                append(".resource_id=?").append(queryParameters.size());
    }
    if (notification != null) {
        queryParameters.add(notification.getKey());

        queryString.append(" AND ").
                append(AbstractTask.TABLE).
                append(".notification_id=?").append(queryParameters.size());
    }
    if (anyTypeKind != null && entityKey != null) {
        queryParameters.add(anyTypeKind.name());
        queryParameters.add(entityKey);

        queryString.append(" AND ").
                append(AbstractTask.TABLE).
                append(".anyTypeKind=?").append(queryParameters.size() - 1).
                append(" AND ").
                append(AbstractTask.TABLE).
                append(".entityKey=?").append(queryParameters.size());
    }

    return queryString;
}