| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
package net.sf.webphotos.dao.jpa; |
| 17 | |
|
| 18 | |
import java.util.List; |
| 19 | |
import javax.persistence.EntityManager; |
| 20 | |
import javax.persistence.PersistenceContext; |
| 21 | |
import javax.persistence.Query; |
| 22 | |
import net.sf.webphotos.entity.HasID; |
| 23 | |
|
| 24 | |
|
| 25 | |
|
| 26 | |
|
| 27 | |
|
| 28 | |
public class WebPhotosDAO<E extends HasID, I> { |
| 29 | |
|
| 30 | |
protected EntityManager entityManager; |
| 31 | |
private Class<E> entityClass; |
| 32 | |
private Class<I> keyClass; |
| 33 | |
|
| 34 | 0 | public WebPhotosDAO(Class<E> entityClass, Class<I> keyClass) { |
| 35 | 0 | this.entityClass = entityClass; |
| 36 | 0 | this.keyClass = keyClass; |
| 37 | 0 | } |
| 38 | |
|
| 39 | |
|
| 40 | |
|
| 41 | |
|
| 42 | |
|
| 43 | |
|
| 44 | |
|
| 45 | |
|
| 46 | |
@Deprecated |
| 47 | |
public Query createNativeQuery(String query) { |
| 48 | 0 | return entityManager.createNativeQuery(query); |
| 49 | |
} |
| 50 | |
|
| 51 | |
public E findBy(I id) { |
| 52 | 0 | return entityManager.find(this.entityClass, id); |
| 53 | |
} |
| 54 | |
|
| 55 | |
public void save(E object) throws Exception { |
| 56 | 0 | if (object.getId() != null && object.equals(entityManager.find(entityClass, object.getId()))) { |
| 57 | 0 | entityManager.merge(object); |
| 58 | |
} else { |
| 59 | 0 | entityManager.persist(object); |
| 60 | |
} |
| 61 | 0 | } |
| 62 | |
|
| 63 | |
public void remove(E object) throws Exception { |
| 64 | 0 | entityManager.remove(object); |
| 65 | 0 | entityManager.flush(); |
| 66 | 0 | } |
| 67 | |
|
| 68 | |
|
| 69 | |
|
| 70 | |
|
| 71 | |
public EntityManager getEntityManager() { |
| 72 | 0 | return entityManager; |
| 73 | |
} |
| 74 | |
|
| 75 | |
|
| 76 | |
|
| 77 | |
|
| 78 | |
@PersistenceContext |
| 79 | |
public void setEntityManager(EntityManager entityManager) { |
| 80 | 0 | this.entityManager = entityManager; |
| 81 | 0 | } |
| 82 | |
|
| 83 | |
|
| 84 | |
|
| 85 | |
|
| 86 | |
|
| 87 | |
|
| 88 | |
|
| 89 | |
|
| 90 | |
@Deprecated |
| 91 | |
public List<Object[]> findByNativeQuery(String query) { |
| 92 | 0 | return createNativeQuery(query).getResultList(); |
| 93 | |
} |
| 94 | |
|
| 95 | |
@SuppressWarnings(value = "unchecked") |
| 96 | |
protected List<E> find(String query) { |
| 97 | 0 | return entityManager.createQuery(query).getResultList(); |
| 98 | |
} |
| 99 | |
|
| 100 | |
@SuppressWarnings(value = "unchecked") |
| 101 | |
protected List<E> findByNamedQuery(String query) { |
| 102 | 0 | return entityManager.createNamedQuery(query).getResultList(); |
| 103 | |
} |
| 104 | |
} |