|
| 1 | +package org.rest.common.dao.jpa; |
| 2 | + |
| 3 | +import java.io.Serializable; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +import javax.persistence.EntityManager; |
| 7 | +import javax.persistence.PersistenceContext; |
| 8 | + |
| 9 | +import org.rest.common.dao.ICommonOperations; |
| 10 | +import org.springframework.transaction.annotation.Propagation; |
| 11 | +import org.springframework.transaction.annotation.Transactional; |
| 12 | + |
| 13 | +import com.google.common.base.Preconditions; |
| 14 | + |
| 15 | +@SuppressWarnings( "unchecked" ) |
| 16 | +@Transactional( propagation = Propagation.SUPPORTS ) |
| 17 | +public abstract class AbstractJpaDAO< T extends Serializable > implements ICommonOperations< T >{ |
| 18 | + private Class< T > clazz; |
| 19 | + |
| 20 | + protected EntityManager entityManager; |
| 21 | + |
| 22 | + public AbstractJpaDAO(){ |
| 23 | + super(); |
| 24 | + } |
| 25 | + |
| 26 | + // |
| 27 | + @PersistenceContext |
| 28 | + public void setEm( final EntityManager emToSet ){ |
| 29 | + Preconditions.checkNotNull( emToSet ); |
| 30 | + this.entityManager = emToSet; |
| 31 | + } |
| 32 | + |
| 33 | + public void setClazz( final Class< T > clazzToSet ){ |
| 34 | + Preconditions.checkNotNull( clazzToSet ); |
| 35 | + this.clazz = clazzToSet; |
| 36 | + } |
| 37 | + |
| 38 | + // get |
| 39 | + |
| 40 | + @Override |
| 41 | + @Transactional( readOnly = true ) |
| 42 | + public T getById( final Long id ){ |
| 43 | + Preconditions.checkArgument( id != null ); |
| 44 | + |
| 45 | + return this.entityManager.find( this.clazz, id ); |
| 46 | + } |
| 47 | + |
| 48 | + @Override |
| 49 | + @Transactional( readOnly = true ) |
| 50 | + public List< T > getAll(){ |
| 51 | + return this.entityManager.createQuery( "from " + this.clazz.getName() ).getResultList(); |
| 52 | + } |
| 53 | + |
| 54 | + // create/persist |
| 55 | + |
| 56 | + @Override |
| 57 | + public void create( final T entity ){ |
| 58 | + Preconditions.checkNotNull( entity ); |
| 59 | + |
| 60 | + this.entityManager.persist( entity ); |
| 61 | + } |
| 62 | + |
| 63 | + // update |
| 64 | + |
| 65 | + @Override |
| 66 | + public void update( final T entity ){ |
| 67 | + Preconditions.checkNotNull( entity ); |
| 68 | + |
| 69 | + this.entityManager.merge( entity ); |
| 70 | + } |
| 71 | + |
| 72 | + // delete |
| 73 | + |
| 74 | + @Override |
| 75 | + public void delete( final T entity ){ |
| 76 | + Preconditions.checkNotNull( entity ); |
| 77 | + |
| 78 | + this.entityManager.remove( entity ); |
| 79 | + } |
| 80 | + |
| 81 | + public void deleteById( final Long entityId ){ |
| 82 | + final T entity = this.getById( entityId ); |
| 83 | + Preconditions.checkState( entity != null ); |
| 84 | + |
| 85 | + this.delete( entity ); |
| 86 | + } |
| 87 | + |
| 88 | +} |
0 commit comments