下面列出了怎么用javax.persistence.MappedSuperclass的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public String getResourceType(Class<?> entityClass) {
JsonApiResource annotation1 = entityClass.getAnnotation(JsonApiResource.class);
if (annotation1 != null) {
return annotation1.type();
}
if (entityClass.getAnnotation(MappedSuperclass.class) != null) {
return null; // super classes do not have a document type
}
String name = entityClass.getSimpleName();
if (name.endsWith(ENTITY_NAME_SUFFIX)) {
name = name.substring(0, name.length() - ENTITY_NAME_SUFFIX.length());
}
return Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
private ClassDescriptor toClassDescriptor(ClassFile classFile, ArchiveEntry entry) {
ClassDescriptor.Categorization categorization = ClassDescriptor.Categorization.OTHER;;
final AnnotationsAttribute visibleAnnotations = (AnnotationsAttribute) classFile.getAttribute( AnnotationsAttribute.visibleTag );
if ( visibleAnnotations != null ) {
if ( visibleAnnotations.getAnnotation( Entity.class.getName() ) != null
|| visibleAnnotations.getAnnotation( MappedSuperclass.class.getName() ) != null
|| visibleAnnotations.getAnnotation( Embeddable.class.getName() ) != null ) {
categorization = ClassDescriptor.Categorization.MODEL;
}
else if ( visibleAnnotations.getAnnotation( Converter.class.getName() ) != null ) {
categorization = ClassDescriptor.Categorization.CONVERTER;
}
}
return new ClassDescriptorImpl( classFile.getName(), categorization, entry.getStreamAccess() );
}
private void categorizeAnnotatedClass(Class annotatedClass, AttributeConverterManager attributeConverterManager) {
final XClass xClass = reflectionManager.toXClass( annotatedClass );
// categorize it, based on assumption it does not fall into multiple categories
if ( xClass.isAnnotationPresent( Converter.class ) ) {
//noinspection unchecked
attributeConverterManager.addAttributeConverter( annotatedClass );
}
else if ( xClass.isAnnotationPresent( Entity.class )
|| xClass.isAnnotationPresent( MappedSuperclass.class ) ) {
xClasses.add( xClass );
}
else if ( xClass.isAnnotationPresent( Embeddable.class ) ) {
xClasses.add( xClass );
}
else {
log.debugf( "Encountered a non-categorized annotated class [%s]; ignoring", annotatedClass.getName() );
}
}
protected List<String> getClasses(Resource[] resources) {
List<String> classNames = new ArrayList<>();
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader metadataReader;
try {
metadataReader = metadataReaderFactory.getMetadataReader(resource);
} catch (IOException e) {
throw new RuntimeException("Unable to read metadata resource", e);
}
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
if (annotationMetadata.isAnnotated(com.haulmont.chile.core.annotations.MetaClass.class.getName())
|| annotationMetadata.isAnnotated(MappedSuperclass.class.getName())
|| annotationMetadata.isAnnotated(Entity.class.getName())) {
ClassMetadata classMetadata = metadataReader.getClassMetadata();
classNames.add(classMetadata.getClassName());
}
}
}
return classNames;
}
/**
* Executes eligible callbacks in {@link Embedded} properties recursively.
*
* @param entity the Java object of the entity class
* @param entityType either the type of the entity or an ancestor type
*/
private void execute(Object entity, Class<?> entityType) {
Class<?> parentType = entityType.getSuperclass();
if (parentType != null && parentType.isAnnotationPresent(MappedSuperclass.class)) {
execute(entity, parentType);
}
findEmbeddedProperties(entity, entityType)
.forEach(
normalEmbedded -> {
// For each normal embedded property, we don't execute its callback method because
// it is handled by Hibernate. However, for the embedded property defined in the
// entity's parent class, we need to treat it as a nested embedded property and
// invoke its callback function.
if (entity.getClass().equals(entityType)) {
executeCallbackForNormalEmbeddedProperty(
normalEmbedded, normalEmbedded.getClass());
} else {
executeCallbackForNestedEmbeddedProperty(
normalEmbedded, normalEmbedded.getClass());
}
});
}
private void executeCallbackForNestedEmbeddedProperty(
Object nestedEmbeddedObject, Class<?> nestedEmbeddedType) {
Class<?> parentType = nestedEmbeddedType.getSuperclass();
if (parentType != null && parentType.isAnnotationPresent(MappedSuperclass.class)) {
executeCallbackForNestedEmbeddedProperty(nestedEmbeddedObject, parentType);
}
findEmbeddedProperties(nestedEmbeddedObject, nestedEmbeddedType)
.forEach(
embeddedProperty ->
executeCallbackForNestedEmbeddedProperty(
embeddedProperty, embeddedProperty.getClass()));
for (Method method : nestedEmbeddedType.getDeclaredMethods()) {
if (method.isAnnotationPresent(callbackType)) {
invokeMethod(method, nestedEmbeddedObject);
}
}
}
private static Set<Class<?>> scanMappedSuperclass(Class<?> clz) throws Exception {
Set<Class<?>> set = new HashSet<Class<?>>();
set.add(clz);
Class<?> s = clz.getSuperclass();
while (null != s) {
if (null != s.getAnnotation(MappedSuperclass.class)) {
set.add(s);
}
s = s.getSuperclass();
}
return set;
}
private static Set<Class<?>> scanMappedSuperclass(Class<?> clz) throws Exception {
Set<Class<?>> set = new HashSet<Class<?>>();
set.add(clz);
Class<?> s = clz.getSuperclass();
while (null != s) {
if (null != s.getAnnotation(MappedSuperclass.class)) {
set.add(s);
}
s = s.getSuperclass();
}
return set;
}
public static Set<Class<?>> scanMappedSuperclass(Class<?> clz) throws Exception {
Set<Class<?>> set = new HashSet<Class<?>>();
set.add(clz);
Class<?> s = clz.getSuperclass();
while (null != s) {
if (null != s.getAnnotation(MappedSuperclass.class)) {
set.add(s);
}
s = s.getSuperclass();
}
return set;
}
private static Set<Class<?>> scanMappedSuperclass(Class<?> clz) throws Exception {
Set<Class<?>> set = new HashSet<Class<?>>();
set.add(clz);
Class<?> s = clz.getSuperclass();
while (null != s) {
if (null != s.getAnnotation(MappedSuperclass.class)) {
set.add(s);
}
s = s.getSuperclass();
}
return set;
}
private MetadataSources mapAnnotatedClasses(ServiceRegistry serviceRegistry) {
MetadataSources sources = new MetadataSources(serviceRegistry);
final Reflections reflections = new Reflections();
for (final Class<?> mappedSuperClass : reflections.getTypesAnnotatedWith(MappedSuperclass.class)) {
sources.addAnnotatedClass(mappedSuperClass);
System.out.println("Mapped = " + mappedSuperClass.getName());
}
for (final Class<?> entityClasses : reflections.getTypesAnnotatedWith(Entity.class)) {
sources.addAnnotatedClass(entityClasses);
System.out.println("Mapped = " + entityClasses.getName());
}
return sources;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public ResourceInformation build(final Class<?> resourceClass) {
String resourceType = getResourceType(resourceClass);
String resourcePath = getResourcePath(resourceClass);
MetaDataObject meta = metaProvider.discoverMeta(resourceClass).asDataObject();
DefaultResourceInstanceBuilder instanceBuilder = new DefaultResourceInstanceBuilder(resourceClass);
BeanInformation beanInformation = BeanInformation.get(resourceClass);
ResourceFieldAccess resourceAccess = getResourceAccess(resourceClass);
List<ResourceField> fields = getResourceFields(resourceClass, resourceAccess, false);
handleIdOverride(resourceClass, fields);
Class<?> superclass = resourceClass.getSuperclass();
String superResourceType = superclass != Object.class
&& superclass.getAnnotation(MappedSuperclass.class) == null ? context.getResourceType(superclass)
: null;
TypeParser typeParser = context.getTypeParser();
ResourceInformation information =
new ResourceInformation(typeParser, resourceClass, resourceType, resourcePath, superResourceType,
instanceBuilder, fields, OffsetLimitPagingSpec.class);
information.setValidator(new JpaOptimisticLockingValidator(meta));
information.setAccess(resourceAccess);
information.setVersionRange(getVersionRange(resourceClass));
ResourceField idField = information.getIdField();
BeanAttributeInformation idAttr = beanInformation.getAttribute(idField.getUnderlyingName());
if (idAttr.getAnnotation(EmbeddedId.class).isPresent()) {
information.setIdStringMapper(new JpaIdMapper(meta));
}
return information;
}
private void extractInheritanceType() {
XAnnotatedElement element = getClazz();
Inheritance inhAnn = element.getAnnotation( Inheritance.class );
MappedSuperclass mappedSuperClass = element.getAnnotation( MappedSuperclass.class );
if ( mappedSuperClass != null ) {
setEmbeddableSuperclass( true );
setType( inhAnn == null ? null : inhAnn.strategy() );
}
else {
setType( inhAnn == null ? InheritanceType.SINGLE_TABLE : inhAnn.strategy() );
}
}
private void addMappedSuperClassInMetadata(PersistentClass persistentClass) {
//add @MappedSuperclass in the metadata
// classes from 0 to n-1 are @MappedSuperclass and should be linked
org.hibernate.mapping.MappedSuperclass mappedSuperclass = null;
final InheritanceState superEntityState =
InheritanceState.getInheritanceStateOfSuperEntity( clazz, inheritanceStatePerClass );
PersistentClass superEntity =
superEntityState != null ?
buildingContext.getMetadataCollector().getEntityBinding( superEntityState.getClazz().getName() ) :
null;
final int lastMappedSuperclass = classesToProcessForMappedSuperclass.size() - 1;
for ( int index = 0; index < lastMappedSuperclass; index++ ) {
org.hibernate.mapping.MappedSuperclass parentSuperclass = mappedSuperclass;
final Class<?> type = buildingContext.getBootstrapContext().getReflectionManager()
.toClass( classesToProcessForMappedSuperclass.get( index ) );
//add MAppedSuperclass if not already there
mappedSuperclass = buildingContext.getMetadataCollector().getMappedSuperclass( type );
if ( mappedSuperclass == null ) {
mappedSuperclass = new org.hibernate.mapping.MappedSuperclass( parentSuperclass, superEntity );
mappedSuperclass.setMappedClass( type );
buildingContext.getMetadataCollector().addMappedSuperclass( type, mappedSuperclass );
}
}
if ( mappedSuperclass != null ) {
persistentClass.setSuperMappedSuperclass( mappedSuperclass );
}
}
private void buildHierarchyColumnOverride(XClass element) {
XClass current = element;
Map<String, Column[]> columnOverride = new HashMap<String, Column[]>();
Map<String, JoinColumn[]> joinColumnOverride = new HashMap<String, JoinColumn[]>();
Map<String, JoinTable> joinTableOverride = new HashMap<String, JoinTable>();
Map<String, ForeignKey> foreignKeyOverride = new HashMap<String, ForeignKey>();
while ( current != null && !context.getBootstrapContext().getReflectionManager().toXClass( Object.class ).equals( current ) ) {
if ( current.isAnnotationPresent( Entity.class ) || current.isAnnotationPresent( MappedSuperclass.class )
|| current.isAnnotationPresent( Embeddable.class ) ) {
//FIXME is embeddable override?
Map<String, Column[]> currentOverride = buildColumnOverride( current, getPath() );
Map<String, JoinColumn[]> currentJoinOverride = buildJoinColumnOverride( current, getPath() );
Map<String, JoinTable> currentJoinTableOverride = buildJoinTableOverride( current, getPath() );
Map<String, ForeignKey> currentForeignKeyOverride = buildForeignKeyOverride( current, getPath() );
currentOverride.putAll( columnOverride ); //subclasses have precedence over superclasses
currentJoinOverride.putAll( joinColumnOverride ); //subclasses have precedence over superclasses
currentJoinTableOverride.putAll( joinTableOverride ); //subclasses have precedence over superclasses
currentForeignKeyOverride.putAll( foreignKeyOverride ); //subclasses have precedence over superclasses
columnOverride = currentOverride;
joinColumnOverride = currentJoinOverride;
joinTableOverride = currentJoinTableOverride;
foreignKeyOverride = currentForeignKeyOverride;
}
current = current.getSuperclass();
}
holderColumnOverride = columnOverride.size() > 0 ? columnOverride : null;
holderJoinColumnOverride = joinColumnOverride.size() > 0 ? joinColumnOverride : null;
holderJoinTableOverride = joinTableOverride.size() > 0 ? joinTableOverride : null;
holderForeignKeyOverride = foreignKeyOverride.size() > 0 ? foreignKeyOverride : null;
}
private MappedSuperclass getMappedSuperclass(Element tree, XMLContext.Default defaults) {
if ( tree == null ) {
return defaults.canUseJavaAnnotations() ? getPhysicalAnnotation( MappedSuperclass.class ) : null;
}
else {
if ( "mapped-superclass".equals( tree.getName() ) ) {
AnnotationDescriptor entity = new AnnotationDescriptor( MappedSuperclass.class );
return AnnotationFactory.create( entity );
}
else {
return null; //this is not an entity
}
}
}
private void insertMappedSuperclasses(List<XClass> original, List<XClass> copy) {
for ( XClass clazz : original ) {
XClass superClass = clazz.getSuperclass();
while ( superClass != null
&& !reflectionManager.equals( superClass, Object.class )
&& !copy.contains( superClass ) ) {
if ( superClass.isAnnotationPresent( Entity.class )
|| superClass.isAnnotationPresent( javax.persistence.MappedSuperclass.class ) ) {
copy.add( superClass );
}
superClass = superClass.getSuperclass();
}
}
}
private Class<?> getJpaSuperclass(Class<?> resourceClass) {
Class<?> superclass = resourceClass.getSuperclass();
while(superclass != Object.class){
if(superclass.getAnnotation(Entity.class) != null || superclass.getAnnotation(MappedSuperclass.class) != null){
return superclass;
}
superclass = superclass.getSuperclass();
}
return null;
}
public String getParent() {
MetaClass ancestor = meta.getAncestor();
if (ancestor == null ||
!ancestor.getName().contains("$") && !ancestor.getName().contains("_") ||
ancestor.getJavaClass().isAnnotationPresent(MappedSuperclass.class))
return "";
if (!readPermitted(ancestor)) {
return null;
}
return "Parent is " + asHref(ancestor.getName());
}
protected Set<String> getDescendants(Set<String> relatedTypes) {
if (relatedTypes == null) return null;
Set<String> newRelatedTypes = new HashSet<>();
relatedTypes.forEach(type -> {
newRelatedTypes.add(type);
MetaClass metaClass = metadata.getClassNN(type);
if (metaClass.getDescendants() != null) {
Set<String> descendants = metaClass.getDescendants().stream()
.filter(it -> it.getJavaClass() != null && !it.getJavaClass().isAnnotationPresent(MappedSuperclass.class))
.map(MetadataObject::getName).collect(Collectors.toSet());
newRelatedTypes.addAll(descendants);
}
});
return newRelatedTypes;
}
private void executeCallbackForNormalEmbeddedProperty(
Object normalEmbeddedObject, Class<?> normalEmbeddedType) {
Class<?> parentType = normalEmbeddedType.getSuperclass();
if (parentType != null && parentType.isAnnotationPresent(MappedSuperclass.class)) {
executeCallbackForNormalEmbeddedProperty(normalEmbeddedObject, parentType);
}
findEmbeddedProperties(normalEmbeddedObject, normalEmbeddedType)
.forEach(
embeddedProperty ->
executeCallbackForNestedEmbeddedProperty(
embeddedProperty, embeddedProperty.getClass()));
}
private static boolean hasMethodAnnotatedWithEmbedded(Class<?> entityType) {
boolean result = false;
Class<?> parentType = entityType.getSuperclass();
if (parentType != null && parentType.isAnnotationPresent(MappedSuperclass.class)) {
result = hasMethodAnnotatedWithEmbedded(parentType);
}
for (Method method : entityType.getDeclaredMethods()) {
if (method.isAnnotationPresent(Embedded.class)) {
result = true;
break;
}
}
return result;
}
public boolean isRootClass(Class<?> theClass) {
final boolean notMappedSuperclassAndNotEmbeddable = theClass
.getAnnotation(MappedSuperclass.class) == null
&& theClass.getAnnotation(Embeddable.class) == null;
if (theClass.getSuperclass() != null) {
return notMappedSuperclassAndNotEmbeddable
&& !isSelfOrAncestorRootClass(theClass.getSuperclass());
} else {
return notMappedSuperclassAndNotEmbeddable;
}
}
public boolean isSelfOrAncestorRootClass(Class<?> theClass) {
if (isRootClass(theClass)) {
return true;
} else if (theClass.getSuperclass() != null) {
return isSelfOrAncestorRootClass(theClass.getSuperclass());
} else {
return theClass.getAnnotation(MappedSuperclass.class) == null
&& theClass.getAnnotation(Embeddable.class) == null;
}
}
/**
* Scans for *.orm.xml and adds Entites from classpath.
*
* @param pui
* the pui
*/
@Override
public void postProcessPersistenceUnitInfo( MutablePersistenceUnitInfo pui )
{
_Log.info( "Scanning for JPA orm.xml files" );
for ( File ormFile : getListORMFiles( ) )
{
String ormAbsolutePath = ormFile.getAbsolutePath( );
_Log.info( "Found ORM file : " + ormAbsolutePath );
pui.addMappingFileName( ormAbsolutePath.substring( ormAbsolutePath.indexOf( CLASSPATH_PATH_IDENTIFIER ) ) );
}
_Log.info( "Scanning for JPA entities..." );
Set<String> entityClasses = AnnotationUtil.find( Entity.class.getName( ) );
entityClasses.addAll( AnnotationUtil.find( Embeddable.class.getName( ) ) );
entityClasses.addAll( AnnotationUtil.find( MappedSuperclass.class.getName( ) ) );
for ( String strClass : entityClasses )
{
_Log.info( "Found entity class : " + strClass );
if ( !pui.getManagedClassNames( ).contains( strClass ) )
{
pui.addManagedClassName( strClass );
}
}
if ( _Log.isDebugEnabled( ) )
{
dumpPersistenceUnitInfo( pui );
}
}
@Test
public void testStaticWeaving() {
// first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
Reflections reflections = new Reflections(
DocumentAttachment.class.getPackage().getName(),
DocumentBase.class.getPackage().getName(),
MaintenanceLock.class.getPackage().getName(),
Message.class.getPackage().getName());
Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);
// next, let's assert that they have been statically weaved
assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}
@Test
public void testStaticWeaving() {
// first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
Reflections reflections = new Reflections("org.kuali.rice.krad");
Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);
// next, let's assert that they have been statically weaved
assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}
@Test
public void testStaticWeaving() {
// first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
Reflections reflections = new Reflections(getClass().getPackage().getName());
Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);
// next, let's assert that they have been statically weaved
assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}
@Test
public void testStaticWeaving() {
// first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
Reflections reflections = new Reflections(
PersistableBusinessObjectBase.class.getPackage().getName());
Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);
// next, let's assert that they have been statically weaved
assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}
@Test
public void testStaticWeaving() {
// first, scan for all files on the classpath with an @Entity or @MappedSuperClass annotation
Reflections reflections = new Reflections(getClass().getPackage().getName());
Set<Class<?>> entityTypes = reflections.getTypesAnnotatedWith(Entity.class);
Set<Class<?>> superTypes = reflections.getTypesAnnotatedWith(MappedSuperclass.class);
Set<Class<?>> embeddableTypes = reflections.getTypesAnnotatedWith(Embeddable.class);
// next, let's assert that they have been statically weaved
assertStaticWeaved(entityTypes, superTypes, embeddableTypes);
}