Skip to content

Instantly share code, notes, and snippets.

View dmitry-osin's full-sized avatar

Dmitry Osin dmitry-osin

  • InnoTech
  • Moscow, Russia
View GitHub Profile
package pw.osin.example.data;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import java.util.Collection;
import java.util.List;
public abstract class AbstractJPADataAccess<TKey, TEntity> implements DataAccess<TKey, TEntity> {
public void createAll(Collection<TEntity> entities) {
final EntityTransaction tx = beginTransaction();
try {
int i = 0;
for (final TEntity entity : entities) {
getEntityManager().persist(entity);
if (++i % 50 == 0) {
getEntityManager().flush();
getEntityManager().clear();
}
public List<TEntity> findAll() {
final TypedQuery<TEntity> query = getEntityManager().createQuery(String.format("SELECT entity FROM %s entity",
getType().getSimpleName()), getType());
return query.getResultList();
}
public List<TEntity> findAll(int size, int offset) {
final TypedQuery<TEntity> query = getEntityManager().createQuery(String.format("SELECT entity FROM %s entity",
getType().getSimpleName()), getType());
query.setFirstResult(offset);
public TEntity findById(TKey id) {
return getEntityManager().find(getType(), id);
}
public TEntity create(TEntity entity) {
final EntityTransaction tx = beginTransaction();
try {
getEntityManager().persist(entity);
tx.commit();
return entity;
} catch (Exception ex) {
ex.printStackTrace();
tx.rollback();
throw new RuntimeException(ex);
package pw.osin.example.data;
import pw.osin.example.model.JPAEntity;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import java.util.Collection;
import java.util.List;
package pw.osin.example.data;
import pw.osin.example.model.JPAEntity;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import java.util.Collection;
import java.util.List;
package pw.osin.example.data;
import pw.osin.example.model.JPAEntity;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
public abstract class AbstractJPADataAccess<TKey, TEntity> implements DataAccess<TKey, TEntity> {
protected abstract EntityManager getEntityManager();
package pw.osin.example.data;
import javax.persistence.EntityManager;
public abstract class AbstractJPADataAccess<TKey, TEntity> implements DataAccess<TKey, TEntity> {
protected abstract EntityManager getEntityManager();
protected abstract Class<TEntity> getType();
package pw.osin.example.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Tweet {
@Id