All Downloads are FREE. Search and download functionalities are using the official Maven repository.

play.db.jpa.JPARepository Maven / Gradle / Ivy

There is a newer version: 2.6.2
Show newest version
package play.db.jpa;

import jakarta.inject.Singleton;
import jakarta.persistence.Entity;
import jakarta.persistence.PersistenceUnit;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import play.db.jpa.GenericModel.JPAQuery;

@Singleton
public class JPARepository {
  private final String entityName;
  private final String dbName;

  @Nonnull
  public static  JPARepository from(Class modelClass) {
    return new JPARepository<>(modelClass);
  }

  private JPARepository(Class modelClass) {
    if (!modelClass.isAnnotationPresent(Entity.class)) {
      throw new IllegalArgumentException("Only JPA entities are supported");
    }

    PersistenceUnit persistenceUnit = modelClass.getAnnotation(PersistenceUnit.class);
    dbName = persistenceUnit == null ? JPA.DEFAULT : persistenceUnit.name();
    entityName = modelClass.getName();
  }

  public long count() {
    return JPQL.instance.count(dbName, entityName);
  }

  public long count(String query, Object... params) {
    return JPQL.instance.count(dbName, entityName, query, params);
  }

  @Nonnull
  public List findAll() {
    return JPQL.instance.findAll(dbName, entityName);
  }

  @Nullable
  public T findById(Object id) {
    try {
      return (T) JPQL.instance.findById(dbName, entityName, id);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  @Nonnull
  public JPAQuery find(String query, Object... params) {
    return JPQL.instance.find(dbName, entityName, query, params);
  }

  public int delete(String query, Object... params) {
    return JPQL.instance.delete(dbName, entityName, query, params);
  }

  public int deleteAll() {
    return JPQL.instance.deleteAll(dbName, entityName);
  }

  public void save(T model) {
    model._save();
  }

  public void delete(T model) {
    model._delete();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy