Skip to content

Instantly share code, notes, and snippets.

@onurcill
Created February 28, 2022 20:33
Show Gist options
  • Save onurcill/de3338f03335de48ce25b8252f8b7a29 to your computer and use it in GitHub Desktop.
Save onurcill/de3338f03335de48ce25b8252f8b7a29 to your computer and use it in GitHub Desktop.
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