Car j'ai eu le même problème. Il a plein d'exception quand on utilise le getById implémenté par Spring.
Même si je note que tu utilises un findById
Or, pour moi, il y a un double problème avec getById.
Quand avec un id (non null) j'ai en base de BDD rien, ça peut être normal.
Ça veut dire que ce que je cherche n'existe pas.
Second problème: si c'est null, on envoie une exception, au lieu de retourner un null (conclusion: il faut utiliser l'optionnal).
Dans le projet au boulôt
J'ai contourné le problème. Comme j'ai des champs uniques, qui définissent l'entité en BDD, je fais des recherches sur ces champs fonctionnels.
Soit:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
package com.acton.group.cooptation.repository.spring;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.acton.group.cooptation.entity.UsersEntity;
public interface SpringUsersEntityRepository extends JpaRepository<UsersEntity, Long>{
@Query("SELECT user FROM UsersEntity user WHERE user.login = ?1")
Optional<UsersEntity> getUserByLogin(String login);
} |
Dans mon métier, le login est unique. Dons le résultat est unique. Et là, ça marche sans problème.
Dans mon projet
Je n'utilise pas le CRUD Spring, je l'ai réimplémenté avec JPA pour coller à mon contrat.
J'ai un contrat de base pour les DAO:
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
|
package com.calculateur.warhammer.base.dao;
import java.util.List;
import java.util.Optional;
import com.calculateur.warhammer.base.entity.IEntity;
import com.calculateur.warhammer.base.exception.DAOException;
import com.calculateur.warhammer.base.exception.FunctionnalExeption;
/**
* DAO pour une entité en BDD
* @author phili
*
* @param <I> Type de l'id de l'entité
* @param <E> L'entité
*/
public interface IDAO <I,E extends IEntity<I>>{
/**
* Sauvegarde l'entité en BDD (Création)
* @param entity L'entité é sauvegarder
* @return L'entité é créer
* @throws DAOException Si probléeme en BDD
* @throws FunctionnalExeption Si probléme à la vérification avant d'insérer en BDD
*/
E save(E entity)throws DAOException,FunctionnalExeption;
/**
* Met é jour l'entit en BDD
* @param entity L'entité é modifier
* @return L'entité modifiée
* @throws DAOException Si probléme en BDD
* @throws FunctionnalExeption Si probléme avant de vérifier l'entité
*/
E update(E entity)throws DAOException,FunctionnalExeption;
/**
*
* @param id Id de l'entité
* @return L'id correspondant à l'entité (null sinon)
* @throws DAOException Si probléme en BDD
*/
Optional<E> getById(I id) throws DAOException;
/**
*
* @return La liste des entité présente en BDD
* @throws DAOException Si probléme en BDD
*/
List<E> getAll() throws DAOException;
/**
* Efface en BDD l'entité correspondant à l'identifiant
* @param id L'id de l'entité
* @throws DAOException Si probléme en BDD
*/
void delete(I id)throws DAOException;
/**
*
* @return Le nombre d'occurence en BDD
* @throws DAOException
*/
Long count()throws DAOException;
/**
* Vérifie la cohérence de l'entité
* @param entity L'entité é vérifier
* @throws DAOException Si erreur lors de recherche en BDD
* @throws FunctionnalExeption Si erreur intrinséque à l'entité
*/
void verifieEntity(E entity)throws DAOException,FunctionnalExeption;
} |
Et un template Methode pour l'implémentation:
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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
|
package com.calculateur.warhammer.dao.dao;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import com.calculateur.warhammer.base.dao.IDAO;
import com.calculateur.warhammer.base.entity.IEntity;
import com.calculateur.warhammer.base.exception.DAOException;
import com.calculateur.warhammer.base.exception.FunctionnalExeption;
import com.calculateur.warhammer.dao.verification.VerificationUtils;
/**
* Template Method pour les DAO avec JPA
* @author phili
*
* @param <I> Type de l'id
* @param <E> Type de l'entité
*/
public abstract class AbstractDAO<I,E extends IEntity<I>> implements IDAO<I, E>{
@PersistenceContext
protected final EntityManager em;
protected final PlatformTransactionManager transactionManager;
protected AbstractDAO(EntityManager em, PlatformTransactionManager transactionManager) {
this.em = em;
this.transactionManager = transactionManager;
}
/**
*
* @return La classe sous forme de String pour les Query JPQL
*/
protected abstract String getEntityClass();
/**
*
* @return Le libellé de l'entité pour les query JPQL
*/
protected abstract String getEntityLibelle();
/**
*
* @return Le resource Bundle d'erreur pour les erreurs fonctionnelles
*/
protected abstract String getErrorBundle();
/**
*
* @return L'entit� sous forme de classe
*/
protected abstract Class<E> getClassEntity();
@Override
public E save(E entity) throws DAOException, FunctionnalExeption {
verifieEntity(entity);
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try {
em.persist(entity);
transactionManager.commit(status);
return entity;
}catch (Exception e) {
transactionManager.rollback(status);
throw new DAOException(e);
}
}
@Override
public E update(E entity) throws DAOException, FunctionnalExeption {
verifieEntity(entity);
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try {
E rEntity = em.merge(entity);
transactionManager.commit(status);
return rEntity;
}catch (Exception e) {
transactionManager.rollback(status);
throw new DAOException(e);
}
}
@Override
public Optional<E> getById(I id) throws DAOException {
try {
return Optional.ofNullable(em.find(getClassEntity(), id));
}catch(Exception e) {
throw new DAOException(e);
}
}
@SuppressWarnings("unchecked")
@Override
public List<E> getAll() throws DAOException {
try {
Query query = em.createQuery(getJpqlAll());
return query.getResultList();
}catch(Exception e) {
throw new DAOException(e);
}
}
/**
*
* @return Le JPQL pour avoir toutes les entités
*/
private String getJpqlAll() {
StringBuilder sb = new StringBuilder("SELECT ");
sb.append(getEntityLibelle());
sb.append(" FROM ");
sb.append(getEntityClass());
sb.append(" ");
sb.append(getEntityLibelle());
return sb.toString();
}
@Override
public void delete(I id) throws DAOException {
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try {
Query queryDelete = getDeleteQuery(id);
queryDelete.executeUpdate();
transactionManager.commit(status);
}catch(Exception e) {
transactionManager.rollback(status);
throw new DAOException(e);
}
}
/**
* On laisse la possibilité de surcharger cette méthode au cas où l'id soit complexe (clé sur 2 colonnes par exemple).
* @param id L'id de l'entité à supprimer en BDD.
* @return La query pour effacer l'entit� (le paramétrage est fait.
*/
protected Query getDeleteQuery(I id) {
Query query = em.createQuery(getDeleteJpql());
query.setParameter("id", id);
return query;
}
/**
* On laisse la possibilité de surcharger cette méthode au cas où l'id soit complexe (clé sur 2 colonnes par exemple).
* @return JPQL pour suprimer une entité
*/
protected String getDeleteJpql() {
StringBuilder sb = new StringBuilder("DELETE ");
sb.append(" FROM ");
sb.append(getEntityClass());
sb.append(" ");
sb.append(getEntityLibelle());
sb.append(" WHERE ");
sb.append(getEntityLibelle());
sb.append(".id = : id");
return sb.toString();
}
@Override
public Long count() throws DAOException {
try {
Query query = em.createQuery(getJpqlCount());
return (Long) query.getSingleResult();
}catch (Exception e) {
throw new DAOException(e);
}
}
/**
*
* @return Le JPQL pour compter ce qui est en BDD.
*/
private String getJpqlCount() {
StringBuilder sb = new StringBuilder("SELECT DISTINCT(COUNT(");
sb.append(getEntityLibelle());
sb.append(")) FROM ");
sb.append(getEntityClass());
sb.append(" ");
sb.append(getEntityLibelle());
return sb.toString();
}
@Override
public void verifieEntity(E entity) throws DAOException, FunctionnalExeption {
VerificationUtils.verifie(entity, getErrorBundle());
}
} |
J'efface par Id car, pour le coup, c'est plus rapide, plus efficace et moins de requêtes en BDD:
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
|
@Override
public void delete(I id) throws DAOException {
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try {
Query queryDelete = getDeleteQuery(id);
queryDelete.executeUpdate();
transactionManager.commit(status);
}catch(Exception e) {
transactionManager.rollback(status);
throw new DAOException(e);
}
}
/**
* On laisse la possibilité de surcharger cette méthode au cas où l'id soit complexe (clé sur 2 colonnes par exemple).
* @param id L'id de l'entité à supprimer en BDD.
* @return La query pour effacer l'entit� (le paramétrage est fait.
*/
protected Query getDeleteQuery(I id) {
Query query = em.createQuery(getDeleteJpql());
query.setParameter("id", id);
return query;
}
/**
* On laisse la possibilité de surcharger cette méthode au cas où l'id soit complexe (clé sur 2 colonnes par exemple).
* @return JPQL pour suprimer une entité
*/
protected String getDeleteJpql() {
StringBuilder sb = new StringBuilder("DELETE ");
sb.append(" FROM ");
sb.append(getEntityClass());
sb.append(" ");
sb.append(getEntityLibelle());
sb.append(" WHERE ");
sb.append(getEntityLibelle());
sb.append(".id = : id");
return sb.toString();
} |
Si l'id est composite, il faut surcharger getDeleteJpql() .
Partager