Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.project.service;
- import com.google.common.collect.Sets;
- import org.apache.commons.collections.CollectionUtils;
- import org.apache.commons.lang3.StringUtils;
- import org.jetbrains.annotations.NotNull;
- import org.reflections.Reflections;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import javax.persistence.*;
- import java.lang.reflect.Field;
- import java.util.Arrays;
- import java.util.List;
- import java.util.Set;
- import static org.reflections.ReflectionUtils.*;
- /**
- * Common interface for all persistent objects.
- *
- * @author Rivaldo
- */
- interface MyEntity {
- Long getId();
- }
- /**
- * Represents the existing relationship types.
- *
- * @author Rivaldo
- */
- enum Relationship {
- ONE_TO_ONE(OneToOne.class),
- ONE_TO_MANY(OneToMany.class),
- MANY_TO_ONE(ManyToOne.class);
- private Class relationshipAnnotation;
- Relationship(Class relationshipAnnotation) {
- this.relationshipAnnotation = relationshipAnnotation;
- }
- /**
- * Gets the relationship annotation
- *
- * @return the class that represents the relationship annotation
- */
- public Class getAnnotation() {
- return relationshipAnnotation;
- }
- /**
- * Gets a query to verify the relationship.
- * The query lists all the lines in which the attribute is equal to the desired entity.
- * The entity must be added as a query's parameter using the 'entity' variable.
- *
- * @param table the table where the query will be performed
- * @param attribute the classe attribute (table column) where the entity is hold
- *
- * @return a query to list all the lines in which the entity is related
- */
- public String getQuery(@NotNull String table, @NotNull String attribute) {
- if (this == ONE_TO_MANY) {
- return inListQuery(table, attribute);
- } else {
- return singleObjectQuery(table, attribute);
- }
- }
- @NotNull
- private String inListQuery(@NotNull String table, @NotNull String attribute) {
- StringBuilder jpql = new StringBuilder("SELECT v FROM ")
- .append(table)
- .append(" v WHERE :entity MEMBER OF ")
- .append("v.").append(attribute);
- return jpql.toString();
- }
- @NotNull
- private String singleObjectQuery(@NotNull String table, @NotNull String attribute) {
- StringBuilder jpql = new StringBuilder("SELECT v FROM ")
- .append(table)
- .append(" v WHERE v.")
- .append(attribute)
- .append(" = :entity");
- return jpql.toString();
- }
- }
- /**
- * A Spring service to verify an entity relationship.
- *
- * @author Rivaldo
- */
- @Service
- public class RelationshipService {
- private EntityManager entityManager;
- private Reflections reflections = new Reflections("com.project.model");
- @Autowired
- public RelationshipService(EntityManager entityManager) {
- this.entityManager = entityManager;
- }
- /**
- * Verify if the desired entity is being referenced in the database and
- * returns all classes in which the desired entity is being related.
- *
- * Checks if that specific entity object is being related by foreign key.
- *
- * @param entity the entity to verify the relationships
- * @return a list of classes where this specific entity is being related
- */
- public Set<Class> checkRelationship(MyEntity entity) {
- Set<Class> relationshipList = Sets.newHashSet();
- Set<Class<?>> entities = reflections.getTypesAnnotatedWith(Entity.class);
- if (CollectionUtils.isNotEmpty(entities)) {
- entities.forEach(clazz -> {
- Arrays.asList(Relationship.values()).forEach(relationship -> {
- if (hasRelationship(relationship, clazz, entity)) {
- relationshipList.add(clazz);
- }
- });
- });
- }
- return relationshipList;
- }
- private boolean hasRelationship(Relationship relationship, Class<?> clazz, MyEntity entity) {
- String tableName = clazz.getAnnotation(Entity.class).name();
- if (StringUtils.isNotBlank(tableName)) {
- Set<Field> fields = getAllFields(clazz, withAnnotation(relationship.getAnnotation()),
- withTypeAssignableTo(entity.getClass()));
- if (CollectionUtils.isNotEmpty(fields)) {
- String jpql;
- for (Field field : fields) {
- jpql = relationship.getQuery(tableName, field.getName());
- List result = entityManager.createQuery(jpql)
- .setParameter("entity", entity)
- .setMaxResults(1)
- .getResultList();
- if (CollectionUtils.isNotEmpty(result)) {
- return true;
- }
- }
- }
- }
- return false;
- }
- }
Add Comment
Please, Sign In to add comment