/** * Sets up relationship repositories for the given document class. In case * of a mapper the resource class might not correspond to the entity class. */ private void setupRelationshipRepositories(Class<?> resourceClass, boolean mapped) { if (context.getResourceInformationBuilder().accept(resourceClass)) { ResourceInformation information = context.getResourceInformationBuilder().build(resourceClass); for (ResourceField field : information.getFields()) { if (field.getResourceFieldType() != ResourceFieldType.RELATIONSHIP) { continue; } Class<?> attrType = field.getElementType(); boolean isEntity = attrType.getAnnotation(Entity.class) != null; if (isEntity) { setupRelationshipRepositoryForEntity(resourceClass, field); } else { setupRelationshipRepositoryForResource(resourceClass, field); } } } }
@Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { //config.setBasePath("api"); try { config.exposeIdsFor(UserEntity.class); ClassPathUtils.streamClassesAnnotatedWith(UserEntity.class, Entity.class) .peek(clazz -> log.debug("enable @Id json mapping for entity {}", clazz.getSimpleName())) .forEach(config::exposeIdsFor); } catch (IOException e) { throw new IllegalStateException("Could not exposeIds for @Entity classes"); } }
/** * Retourne les classes d'une package * * @param packageName * @return * @throws Exception */ public static List<Class> getClasses(String packageName) { final List<Class> list = new ArrayList<>(); final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true); scanner.addIncludeFilter(new AssignableTypeFilter(Object.class)); final Set<BeanDefinition> bds = scanner.findCandidateComponents(packageName); try { for (BeanDefinition bd : bds) { final Class<?> tc = Class.forName(bd.getBeanClassName()); if (tc.getAnnotation(Entity.class) != null) { list.add(tc); } } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } return list; }
@Override public void weave(WovenClass wovenClass) { BundleWiring wiring = wovenClass.getBundleWiring(); Bundle bundle = wiring.getBundle(); ClassLoader cl = wiring.getClassLoader(); Collection<ClassTransformer> transformersToTry = getTransformers(bundle); for (ClassTransformer transformer : transformersToTry) { if (transformClass(wovenClass, cl, transformer)) { LOGGER.info("Weaving " + wovenClass.getClassName() + " using " + transformer.getClass().getName()); break; } } Class<?> dClass = wovenClass.getDefinedClass(); if (transformersToTry.isEmpty() && dClass != null && dClass.getAnnotation(Entity.class) != null) { LOGGER.warn("Loading " + wovenClass.getClassName() + " before transformer is present"); } }
public void deleteEntities(Class<?> entity){ if(entity == null || entity.getAnnotation(Entity.class) == null){ throw new IllegalArgumentException("Invalid non-entity class"); } String name = entity.getSimpleName(); /* Note: we passed as input a Class<?> instead of a String to avoid SQL injection. However, being here just test code, it should not be a problem. But, as a good habit, always be paranoiac about security, above all when you have code that can delete the whole database... */ Query query = em.createQuery("delete from " + name); query.executeUpdate(); }
private void deleteEntities(Class<?> entity){ if(entity == null || entity.getAnnotation(Entity.class) == null){ throw new IllegalArgumentException("Invalid non-entity class"); } String name = entity.getSimpleName(); /* Note: we passed as input a Class<?> instead of a String to avoid SQL injection. However, being here just test code, it should not be a problem. But, as a good habit, always be paranoiac about security, above all when you have code that can delete the whole database... */ Query query = em.createQuery("delete from " + name); query.executeUpdate(); }
public AnnotatedClassType addClassType(XClass clazz) { AnnotatedClassType type; if ( clazz.isAnnotationPresent( Entity.class ) ) { type = AnnotatedClassType.ENTITY; } else if ( clazz.isAnnotationPresent( Embeddable.class ) ) { type = AnnotatedClassType.EMBEDDABLE; } else if ( clazz.isAnnotationPresent( javax.persistence.MappedSuperclass.class ) ) { type = AnnotatedClassType.EMBEDDABLE_SUPERCLASS; } else { type = AnnotatedClassType.NONE; } classTypes.put( clazz.getName(), type ); return type; }
private static boolean isEntityClassType(XClass clazzToProcess, AnnotatedClassType classType) { if ( AnnotatedClassType.EMBEDDABLE_SUPERCLASS.equals( classType ) //will be processed by their subentities || AnnotatedClassType.NONE.equals( classType ) //to be ignored || AnnotatedClassType.EMBEDDABLE.equals( classType ) //allow embeddable element declaration ) { if ( AnnotatedClassType.NONE.equals( classType ) && clazzToProcess.isAnnotationPresent( org.hibernate.annotations.Entity.class ) ) { LOG.missingEntityAnnotation( clazzToProcess.getName() ); } return false; } if ( !classType.equals( AnnotatedClassType.ENTITY ) ) { throw new AnnotationException( "Annotated class should have a @javax.persistence.Entity, @javax.persistence.Embeddable or @javax.persistence.EmbeddedSuperclass annotation: " + clazzToProcess .getName() ); } return true; }
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>(); while ( current != null && !mappings.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() ); currentOverride.putAll( columnOverride ); //subclasses have precedence over superclasses currentJoinOverride.putAll( joinColumnOverride ); //subclasses have precedence over superclasses currentJoinTableOverride.putAll( joinTableOverride ); //subclasses have precedence over superclasses columnOverride = currentOverride; joinColumnOverride = currentJoinOverride; joinTableOverride = currentJoinTableOverride; } current = current.getSuperclass(); } holderColumnOverride = columnOverride.size() > 0 ? columnOverride : null; holderJoinColumnOverride = joinColumnOverride.size() > 0 ? joinColumnOverride : null; holderJoinTableOverride = joinTableOverride.size() > 0 ? joinTableOverride : null; }
private Entity getEntity(Element tree, XMLContext.Default defaults) { if ( tree == null ) { return defaults.canUseJavaAnnotations() ? getPhysicalAnnotation( Entity.class ) : null; } else { if ( "entity".equals( tree.getName() ) ) { AnnotationDescriptor entity = new AnnotationDescriptor( Entity.class ); copyStringAttribute( entity, tree, "name", false ); if ( defaults.canUseJavaAnnotations() && StringHelper.isEmpty( (String) entity.valueOf( "name" ) ) ) { Entity javaAnn = getPhysicalAnnotation( Entity.class ); if ( javaAnn != null ) { entity.setValue( "name", javaAnn.name() ); } } return AnnotationFactory.create( entity ); } else { return null; //this is not an entity } } }
public EntityManagerFactory build() { Properties properties = createProperties(); DefaultPersistenceUnitInfoImpl persistenceUnitInfo = new DefaultPersistenceUnitInfoImpl(JSPARE_GATEWAY_DATASOURCE); persistenceUnitInfo.setProperties(properties); // Using RESOURCE_LOCAL for manage transactions on DAO side. persistenceUnitInfo.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL); // Add all entities to configuration ClassAnnotationMatchProcessor processor = (c) -> persistenceUnitInfo.addAnnotatedClassName(c); ClasspathScannerUtils.scanner(ALL_SCAN_QUOTE).matchClassesWithAnnotation(Entity.class, processor) .scan(NUMBER_CLASSPATH_SCANNER_THREADS); Map<String, Object> configuration = new HashMap<>(); properties.forEach((k, v) -> configuration.put((String) k, v)); EntityManagerFactory entityManagerFactory = persistenceProvider.createContainerEntityManagerFactory(persistenceUnitInfo, configuration); return entityManagerFactory; }
@Override public void start() { StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .applySetting("hibernate.connection.username", config.persistence.user) .applySetting("hibernate.connection.password", config.persistence.pass) .applySetting("hibernate.connection.driver_class", config.persistence.driver) .applySetting("hibernate.connection.url", config.persistence.url) .applySetting("hibernate.dialect", config.persistence.dialect) .applySetting("hibernate.connection.pool_size", config.persistence.pool_size + "") .applySetting("hibernate.hbm2ddl.auto", "update") .applySetting("hibernate.show_sql", config.persistence.showSQL + "") .build(); MetadataSources sources = new MetadataSources(registry); Timings.time("RegisterDBEntities", () -> new Reflections().getTypesAnnotatedWith(Entity.class).forEach(sources::addAnnotatedClass)); try { Metadata metadata = sources.buildMetadata(); sessionFactory = metadata.buildSessionFactory(); } catch (Exception e) { StandardServiceRegistryBuilder.destroy(registry); e.printStackTrace(); } }
/** * * @param manager {@link EntityManager} to create the query * @param klass klass to guess the list query and count query * @param currentPage * @param max max number of elements * @return */ public <T> PaginatedList list(EntityManager manager, Class<T> klass, int currentPage, int max) { if (!klass.isAnnotationPresent(Entity.class)) { throw new IllegalArgumentException("Your entity is not annotated with @Entity"); } TypedQuery<T> listQuery = manager.createQuery( "select o from " + klass.getSimpleName() + " o", klass); TypedQuery<Number> countQuery = manager.createQuery( "select count(1) from " + klass.getSimpleName() + " o", Number.class); return list(listQuery, countQuery, currentPage, max); }
/** * * @param entityClass * @param fieldList * @return */ private static List<Field> getAllField(Class<?> entityClass, List<Field> fieldList) { if (fieldList == null) { fieldList = new LinkedList<Field>(); } if (entityClass.equals(Object.class)) { return fieldList; } Field[] fields = entityClass.getDeclaredFields(); for (Field field : fields) { if (!Modifier.isStatic(field.getModifiers())) { fieldList.add(field); } } Class<?> superClass = entityClass.getSuperclass(); if (superClass != null && !superClass.equals(Object.class) && (superClass.isAnnotationPresent(Entity.class) || (!Map.class.isAssignableFrom(superClass) && !Collection.class.isAssignableFrom(superClass)))) { return getAllField(entityClass.getSuperclass(), fieldList); } return fieldList; }
@Test public void testGetEntityClassFromNodeLabelsHavingTheLabelDeclaredByTheTableAnnotationWithoutInheritance() throws Exception { final String simpleClassName = "EntityClass"; final String nodeLabel = "ENTITY_CLASS"; final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName); jClass.annotate(Entity.class); jClass.annotate(Table.class).param("name", nodeLabel); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name()); final Class<?> clazz = EntityUtils.getEntityClassFromNodeLabels(Arrays.asList(nodeLabel), Arrays.asList(entityClass)); assertThat(clazz, equalTo(entityClass)); }
@Test public void testGetNamesOfIdPropertiesFromASingleClassHavingAFieldAnnotatedWithId() throws Exception { // GIVEN final String simpleClassName = "EntityClass"; final String idPropertyName = "key"; final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName); jClass.annotate(Entity.class); jClass.field(JMod.PRIVATE, String.class, idPropertyName).annotate(Id.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name()); // WHEN final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass); // THEN assertThat(namesOfIdProperties.size(), equalTo(1)); assertThat(namesOfIdProperties, hasItem(idPropertyName)); }
@Test public void testGetNamesOfIdPropertiesFromASingleClassHavingAMethodAnnotatedWithId() throws Exception { // GIVEN final String simpleClassName = "EntityClass"; final String idPropertyName = "key"; final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, simpleClassName); jClass.annotate(Entity.class); jClass.method(JMod.PUBLIC, jCodeModel.VOID, "getKey").annotate(Id.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> entityClass = loadClass(testFolder.getRoot(), jClass.name()); // WHEN final List<String> namesOfIdProperties = EntityUtils.getNamesOfIdProperties(entityClass); // THEN assertThat(namesOfIdProperties.size(), equalTo(1)); assertThat(namesOfIdProperties, hasItem(idPropertyName)); }
@BeforeClass public static void generateTestModel() throws Exception { final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "A"); jClass.annotate(Entity.class); jClass.field(JMod.PRIVATE, Long.class, "id").annotate(Id.class); jClass.field(JMod.PRIVATE, String.class, "value"); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); entityAClass = loadClass(testFolder.getRoot(), jClass.name()); }
@Override public void jpaResultListQuery(EventMetadata metadata, Query query, CEntityManager entityManager) { List<?> result = new ArrayList<Object>(); if (!Context.requestScope().isPlaying()) { result = query.getResultList(); for (Object object : result) { if (object != null && entityManager.isLoadEager() && (object.getClass().getAnnotation(Embeddable.class) != null || object.getClass().getAnnotation(Entity.class) != null)) { CibetUtil.loadLazyEntities(object, object.getClass()); List<Object> references = new ArrayList<Object>(); references.add(object); CibetUtil.deepDetach(object, references); } } } metadata.getResource().setResultObject(result); }
@Override public void contribute(InFlightMetadataCollector metadataCollector, IndexView jandexIndex) { MetadataBuildingOptions options = metadataCollector.getMetadataBuildingOptions(); ClassLoaderService classLoaderService = options.getServiceRegistry().getService(ClassLoaderService.class); final ClassLoaderAccess classLoaderAccess = new ClassLoaderAccessImpl( options.getTempClassLoader(), classLoaderService ); this.metadataBuildingContext = new MetadataBuildingContextRootImpl( options, classLoaderAccess, metadataCollector ); java.util.Collection<PersistentEntity> persistentEntities = hibernateMappingContext.getPersistentEntities(); for (PersistentEntity persistentEntity : persistentEntities) { if(!persistentEntity.getJavaClass().isAnnotationPresent(Entity.class)) { if(ConnectionSourcesSupport.usesConnectionSource(persistentEntity, dataSourceName) && persistentEntity.isRoot()) { bindRoot((HibernatePersistentEntity) persistentEntity, metadataCollector, sessionFactoryName); } } } }
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; }
/** * Scan @Entity classes in base packages. * * @param basePackages * base package names. * @return List of entity class. */ public static List<Class<?>> scanEntities(String... basePackages) { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AnnotationTypeFilter(Entity.class)); List<Class<?>> classes = new ArrayList<>(); for (String basePackage : basePackages) { Set<BeanDefinition> beans = provider.findCandidateComponents(basePackage); for (BeanDefinition bean : beans) { try { classes.add(Class.forName(bean.getBeanClassName())); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } return classes; }
@Override /* * No longer persisting RestNotificationForQuery */ public boolean trigger(final Map<Object, Serializable> eventObject) { try { final JSONObject event = NotificationRuleUtils.toJSON(eventObject); //final RestNotificationForQuery notification = new RestNotificationForQuery(event.toString(), this); // no longer storing the notifications, as they were causing errors with JPA // probably because the entity was configured incorrectly. However, as no one // ever looks them up again, we should stop persisting these anyway. //notification.save(); Client client = ClientBuilder.newClient(); WebTarget target = client.target(this.notificationPath); Response response = target.request().post(javax.ws.rs.client.Entity.json(event.toString())); return response.getStatus() == 200; } catch (UnsupportedJsonTransformation e) { e.printStackTrace(); } return false; }
@Test public void testInsertAndQuery() throws Exception { final TestEntity entity = TestEntity.builder() .key("abc").build(); final Response response = this.client .target(String.format("http://localhost:%d/test", this.RULE.getLocalPort())) .request() .post(javax.ws.rs.client.Entity.json(entity)); assertThat(response.getStatus()).isEqualTo(Status.CREATED.getStatusCode()); final TestEntity createdEntity = this.client .target(String.format("http://localhost:%d/test/1", this.RULE.getLocalPort())) .request() .get(TestEntity.class); assertThat(createdEntity).isEqualToIgnoringGivenFields(entity, "id"); }
public static Entity valueOf(VersionedEntity entity) { if(entity instanceof Synonym) { return TERM_SYNONYM; } if(entity instanceof Relationship) { return TERM_RELATIONSHIP; } if(entity instanceof Term) { return TERM; } if(entity instanceof RelationshipType) { return RELATIONSHIP_TYPE; } if(entity instanceof Ontology) { return ONTOLOGY; } throw new IllegalArgumentException("Invalid entity: " + entity.getClass().getName()); }
@PrePersist public void setAuditCreatedBy(Object entity) throws Exception { if (entity.getClass().isAnnotationPresent(Entity.class)) { Field field = getSingleField(entity.getClass(), "auditable"); field.setAccessible(true); if (field.isAnnotationPresent(Embedded.class)) { Object auditable = field.get(entity); if (auditable == null) { field.set(entity, new Auditable()); auditable = field.get(entity); } Field temporalField = auditable.getClass().getDeclaredField("dateCreated"); Field agentField = auditable.getClass().getDeclaredField("createdBy"); setAuditValueTemporal(temporalField, auditable); setAuditValueAgent(agentField, auditable); } } }
@PreUpdate public void setAuditUpdatedBy(Object entity) throws Exception { if (entity.getClass().isAnnotationPresent(Entity.class)) { Field field = getSingleField(entity.getClass(), "auditable"); field.setAccessible(true); if (field.isAnnotationPresent(Embedded.class)) { Object auditable = field.get(entity); if (auditable == null) { field.set(entity, new Auditable()); auditable = field.get(entity); } Field temporalField = auditable.getClass().getDeclaredField("dateUpdated"); Field agentField = auditable.getClass().getDeclaredField("updatedBy"); setAuditValueTemporal(temporalField, auditable); setAuditValueAgent(agentField, auditable); } } }
private static String getInheritanceHierarchyRoot(Class<?> myEntityClass) { String myEntityName = myEntityClass.getName(); if (inheritanceHierarchyRoots.containsKey(myEntityName)) { return inheritanceHierarchyRoots.get(myEntityName); } Class<?> currentClass = myEntityClass; boolean eof = false; while (!eof) { Class<?> superclass = currentClass.getSuperclass(); if (superclass.equals(Object.class) || !superclass.isAnnotationPresent(Entity.class)) { eof = true; } else { currentClass = superclass; } } if (!currentClass.isAnnotationPresent(Cache.class)) { currentClass = myEntityClass; } inheritanceHierarchyRoots.put(myEntityName, currentClass.getName()); return inheritanceHierarchyRoots.get(myEntityName); }
/** * Validates the provided class' annotations. * Currently the only validation performed is for @Id & @SpaceId annotations * that must be declared on the same getter. */ private void validateClassAnnotations(Class<?> type) { // Validation is only relevant for Entities if (type.getAnnotation(Entity.class) == null) return; for (Method getter : type.getMethods()) { if (!getter.getName().startsWith("get")) continue; SpaceId spaceId = getter.getAnnotation(SpaceId.class); boolean hasJpaId = getter.getAnnotation(Id.class) != null || getter.getAnnotation(EmbeddedId.class) != null; if (spaceId != null || hasJpaId) { if (!hasJpaId || spaceId == null) throw new IllegalArgumentException("SpaceId and Id annotations must both be declared on the same property in JPA entities in type: " + type.getName()); if (spaceId.autoGenerate()) { GeneratedValue generatedValue = getter.getAnnotation(GeneratedValue.class); if (generatedValue == null || generatedValue.strategy() != GenerationType.IDENTITY) throw new IllegalArgumentException( "SpaceId with autoGenerate=true annotated property should also have a JPA GeneratedValue annotation with strategy = GenerationType.IDENTITY."); } break; } } }
BigInteger determineUniqueId() { String entityName = Terminal.class.getAnnotation(Entity.class).name(); BigInteger nextUniqueId = uniqueIdSequenceService.getNextId(entityName); boolean isUniqueIdAlreadyAssigned = terminalRepository.findByUniqueId(nextUniqueId) != null; while (isUniqueIdAlreadyAssigned) { // In this loop we increment the ID by ourselves to avoid write-accesses to the DB for performance. LOG.warn("Terminal uniqueId {} already assigned - trying next uniqueId", nextUniqueId); nextUniqueId = nextUniqueId.add(BigInteger.ONE); if (terminalRepository.findByUniqueId(nextUniqueId) == null) { isUniqueIdAlreadyAssigned = false; uniqueIdSequenceService.setNextId(entityName, nextUniqueId); } } return nextUniqueId; }
@PrePersist public void setAuditCreatedBy(Object entity) throws Exception { if (entity.getClass().isAnnotationPresent(Entity.class)) { Field field = getSingleField(entity.getClass(), "auditable"); field.setAccessible(true); if (field.isAnnotationPresent(Embedded.class)) { Object auditable = field.get(entity); if (auditable == null) { field.set(entity, new AdminAuditable()); auditable = field.get(entity); } Field temporalCreatedField = auditable.getClass().getDeclaredField("dateCreated"); Field temporalUpdatedField = auditable.getClass().getDeclaredField("dateUpdated"); Field agentField = auditable.getClass().getDeclaredField("createdBy"); setAuditValueTemporal(temporalCreatedField, auditable); setAuditValueTemporal(temporalUpdatedField, auditable); setAuditValueAgent(agentField, auditable); } } }
@PreUpdate public void setAuditUpdatedBy(Object entity) throws Exception { if (entity.getClass().isAnnotationPresent(Entity.class)) { Field field = getSingleField(entity.getClass(), "auditable"); field.setAccessible(true); if (field.isAnnotationPresent(Embedded.class)) { Object auditable = field.get(entity); if (auditable == null) { field.set(entity, new AdminAuditable()); auditable = field.get(entity); } Field temporalField = auditable.getClass().getDeclaredField("dateUpdated"); Field agentField = auditable.getClass().getDeclaredField("updatedBy"); setAuditValueTemporal(temporalField, auditable); setAuditValueAgent(agentField, auditable); } } }