Created
February 28, 2022 20:33
-
-
Save onurcill/de3338f03335de48ce25b8252f8b7a29 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MultiTenancyRepository<T, I> extends SimpleJpaRepository<T, I> { | |
private final JpaEntityInformation<T, I> entityInformation; | |
private final EntityManager entityManager; | |
public MultiTenancyRepository( | |
final JpaEntityInformation<T, I> entityInformation, final EntityManager entityManager) { | |
super(entityInformation, entityManager); | |
this.entityInformation = entityInformation; | |
this.entityManager = entityManager; | |
} | |
@Override | |
public Optional<T> findById(@NonNull final I id) { | |
final Class<T> entityType = this.entityInformation.getJavaType(); | |
Objects.requireNonNull(id, "ID can not be null for Type [" + entityType + "]"); | |
final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); | |
final CriteriaQuery<T> cq = criteriaBuilder.createQuery(entityType); | |
cq.where( | |
criteriaBuilder.equal( | |
cq.from(entityType).get(this.entityInformation.getRequiredIdAttribute().getName()), | |
id)); | |
final TypedQuery<T> q = this.entityManager.createQuery(cq); | |
return q.getResultStream().findFirst(); | |
} | |
@Override | |
public T getOne(@NonNull final I i) { | |
throw new EntityNotFoundException(); | |
} | |
@Override | |
public void delete(@NonNull final T entity) { | |
Objects.requireNonNull( | |
entity, "Entity can not be null for Object [" + this.entityInformation.getJavaType() + "]"); | |
if (this.entityInformation.isNew(entity) | |
|| this.findById(this.entityInformation.getRequiredId(entity)).isEmpty()) { | |
return; | |
} | |
this.entityManager.remove( | |
this.entityManager.contains(entity) ? entity : this.entityManager.merge(entity)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment