play.db.jpa.JPARepository Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of framework Show documentation
Show all versions of framework Show documentation
RePlay is a fork of the Play1 framework, created by Codeborne.
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();
}
}