05.1 - Riassunto

Database con JDBC e ORM (Hibernate e JPA)
...

  1. JDBC Tradizionale:

    • Il problema principale di JDBC è la gestione manuale delle operazioni CRUD (Create, Read, Update, Delete), il che può risultare complesso e non portabile tra diversi database.
    • ORM e JPA risolvono questo problema mappando automaticamente le classi Java su tabelle del database.
  2. Hibernate e JPA:

    • JPA (Java Persistence API): è una specifica che gestisce la persistenza degli oggetti Java nei database relazionali.
    • Hibernate: è l'implementazione più popolare di JPA, aggiungendo funzionalità come generatori di identificatori avanzati, entità immutabili, supporto ID naturali, e altro.

    Esempio di classe Hibernate:

    package com.example.accessingdatamysql;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity // Indica che Hibernate deve creare una tabella da questa classe
    public class User {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Integer id;
        private String name;
        private String email;
    
        // Getter e Setter
        public Integer getId() { return id; }
        public void setId(Integer id) { this.id = id; }
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
    }
    

Spring JDBC con JdbcTemplate
...

  1. JdbcTemplate:

    • Classe che semplifica l'accesso al database, gestendo connessioni, risorse e gestione degli errori, lasciando lo sviluppatore concentrato sul task principale.
  2. Esempio di applicazione JDBC:

    Definizione del modello:

    package hello;
    public class Customer {
        private long id;
        private String firstName, lastName;
    
        public Customer(long id, String firstName, String lastName) {
            this.id = id;
            this.firstName = firstName;
            this.lastName = lastName;
        }
    
        @Override
        public String toString() {
            return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
        }
    }
    

    Esecuzione dell'applicazione Spring con JDBC:

    package hello;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.jdbc.core.JdbcTemplate;
    import java.util.List;
    
    @SpringBootApplication
    public class Application implements CommandLineRunner {
        @Autowired
        JdbcTemplate jdbcTemplate;
    
        @Override
        public void run(String... args) throws Exception {
            jdbcTemplate.execute("CREATE TABLE customers(" +
                    "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");
            // Inserimento di alcuni record nel database
            jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)",
                    List.of(new Object[]{"John", "Doe"}, new Object[]{"Jane", "Smith"}));
        }
    }
    

Spring Data JPA: Creazione, Accesso e Persistenza dei Dati
...

  1. Entity e Repository:

    • La classe Customer viene utilizzata come entità JPA per rappresentare i clienti, con la gestione automatica del database.
    • CustomerRepository estende CrudRepository, permettendo operazioni CRUD automatiche su un'entità.

    Esempio di classe Customer:

    @Entity
    public class Customer {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Long id;
        private String firstName;
        private String lastName;
    
        // Costruttori e metodi di accesso
        public Customer(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
    
        public String toString() {
            return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
        }
    }
    

    Repository per Customer:

    public interface CustomerRepository extends CrudRepository<Customer, Long> {
        List<Customer> findByLastName(String lastName);
        Customer findById(long id);
    }
    

Configurazione di Spring Boot e MySQL
...

  1. File di configurazione: application.properties
   spring.jpa.hibernate.ddl-auto=update
   spring.datasource.url=jdbc:mysql://localhost:3306/db_example
   spring.datasource.username=myusername
   spring.datasource.password=mypassword