📚 Cheatsheet

Une collection organisée de snippets de code pour accélérer votre développement. Parcourez, recherchez et copiez en un clic.

Snippets 11

Retour
Annotation @Transactional
Intermédiaire
@Service
public class MonService {
    @Transactional
    public void methodeTransactionnelle() {
        // ...
    }
}
Configuration de la base de données
Facile
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mabase
spring.datasource.username=root
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=update
Créer une interface Repository
Facile
public interface UtilisateurRepository extends JpaRepository<Utilisateur, Long> {
}
Définir une entité JPA (@Entity)
Facile
@Entity
public class Utilisateur {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String nom;
    private String email;
    // Getters and Setters
}
Dépendance 'spring-boot-starter-data-jpa'
Facile
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Méthode de requête dérivée
Facile
public interface UtilisateurRepository extends JpaRepository<Utilisateur, Long> {
    Utilisateur findByEmail(String email);
}
Relation @ManyToMany
Avancé
@ManyToMany
@JoinTable(
  name = "article_tag", 
  joinColumns = @JoinColumn(name = "article_id"), 
  inverseJoinColumns = @JoinColumn(name = "tag_id"))
private Set<Tag> tags;
Relation @ManyToOne
Intermédiaire
@ManyToOne
@JoinColumn(name = "auteur_id")
private Auteur auteur;
Relation @OneToMany
Intermédiaire
@OneToMany(mappedBy = "auteur")
private List<Article> articles;
Requête native avec @Query
Avancé
@Query(value = "SELECT * FROM utilisateurs WHERE email LIKE %?1", nativeQuery = true)
List<Utilisateur> findByEmailDomain(String domain);
Requête personnalisée avec @Query
Intermédiaire
@Query("SELECT u FROM Utilisateur u WHERE u.actif = true")
List<Utilisateur> findAllActif();