1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
public abstract class GenericDAOImpl<T, I extends Serializable> implements GenericDAO<T, I>
{
protected Class<? extends T> clazz;
/**
* Constructeur générique
*/
@SuppressWarnings("unchecked")
protected GenericDAOImpl()
{
this.clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
/**
* Récupération de l'objet pour la clé recherchée
*/
public T find(I id)
{
try
{
return (T) getEntityManager().find(clazz, id);
}
catch (Exception e)
{
return null;
}
}
/**
* Suppression de l'objet pour la clé recherchée
*/
public void delete(I id)
{
delete(find(id));
}
/**
* Suppression de l'objet
*/
public void delete(T t)
{
t = (T)getEntityManager().merge(t);
getEntityManager().remove(t);
}
/**
* Ajouter
*/
public T save(T t)
{
getEntityManager().persist(t);
getEntityManager().flush();
return (T) t;
}
/**
* Modifier un objet
*/
public T update(T t)
{
T entity = (T) getEntityManager().merge(t);
return (T) entity;
}
/**
* Récupération de tous les enregistrements
*/
@SuppressWarnings("unchecked")
public List<T> findAll()
{
return getEntityManager().createQuery("select a from " + clazz.getName() + " a").getResultList();
}
} |
Partager