IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JDBC Java Discussion :

[junit][MySQL] JDBC encapsulation


Sujet :

JDBC Java

  1. #1
    Membre à l'essai
    Homme Profil pro
    En recherche d’emploi
    Inscrit en
    Mai 2015
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : En recherche d’emploi
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Mai 2015
    Messages : 14
    Points : 14
    Points
    14
    Par défaut [junit][MySQL] JDBC encapsulation
    Bonjour,
    Pour tester une connexion à une base de donnees, j'ai ecrit un code où l'objet 'Connection' est déclaré private dans une classe 'JdbcModel'
    encapsulante. Cette classe definit une méthode 'searchEmpTBC' (Employee basique) où un objet ResultSet est déclaré.
    Question: cette méthode est elle une bonne façon de faire? Elle compile mais j'ai du corriger plusieurs erreur de la variable 'Connection' qui ne pouvait pas être definie comme static à l'extérieur de la classe.
    A suivre
    Voici le code:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    package com.javatpoint.models;
     
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.HashMap;
    import java.sql.*;
    import com.javatpoint.models.Emp;
     
    public class JdbcModel {   // extends HttpServlet { // in the future
       // Jdbc connection parameters
       private static final Integer port=3306;
       private String server;
       private String db;
       private String login;
       private String password;
     
    	public JdbcModel(String server, String db, String login, String password) {
    		super();
    		// this.port = port;
    		this.server = server;
    		this.db = db;
    		this.login = login;
    		this.password = password;
    	}
     
       public int getPort() {  // to demonstrate a very simple junit test
          return (int) port;
       }
       private Connection connection;
    // procedure that connect to the DB
       public void connect() throws SQLException 
       {
         String url="jdbc:mysql://"+server+":"+port+"/"+db; // the database address
         connection = DriverManager.getConnection(url, login, password);
       }
     
    // procedure that perform a stmt.executeQuery search for a particular name but w/o presentation work
    // which is bad practice
       public List<Emp> searchEmpTBC(String empname) throws SQLException
       {..}
     
    }  // end class
    Merci d'avance

  2. #2
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    453
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 453
    Points : 883
    Points
    883
    Billets dans le blog
    5
    Par défaut
    Je peux expliquer comment j'ai fait dans mon projet perso:
    https://bitbucket.org/philippegibaul...r40k/src/main/

    Commençons par un principe de base: Je sais ce que tu fais mais je ne veux pas savoir comment t'es codé.

    Ce principe de base en amène un second:
    Il se pourrait que je change de BDD, comme le fait que je suis sous H2 pour les tests et Postgress pour la Prod.
    Le principe suivant a été réutilisé pour le projet sur lequel je travaille. Et ainsi, je peux injecter (via Spring par exemple) la bonne implémentation suivant la BDD attaqué.

    Il me faut donc d'abord un contrat pour regrouper les informations de la BDD:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    package com.calculateur.warhammer.base.server;
     
    /**
     * Interface pour la configuration en BDD
     * @author phili
     *
     */
    public interface IDatabaseConfiguration {
     
    	/**
             * 
             * @return URL
             */
    	String getUrl();
     
    	/**
             * 
             * @return URL JDBC
             */
    	String getJDBCUrl();
     
    	/**
             * 
             * @return User
             */
    	String getUser();
     
    	/**
             * 
             * @return Password
             */
    	String getPassword();
     
    	/**
             * 
             * @return port
             */
    	String getPort();
     
    	/**
             * 
             * @return Le Driver JDBC
             */
    	String getClassDriver();
     
    	/**
             * 
             * @return Un String donnant les informations de la BDD
             */
    	String getInformations();
    }
    On y trouve en vrac l'url, la JDBC url, le login, password, les classes pour JPA...

    Ce qui donne les implémentations suivantes pour Postgresql:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    package com.calculateur.warhammer.dao.postgresql;
     
     
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    import org.postgresql.Driver;
     
    import com.calculateur.warhammer.base.server.IDatabaseConfiguration;
     
    /**
     * Configuration PostgresQL
     * @author phili
     *
     */
    public class ConfigurationPostgresql implements IDatabaseConfiguration{
     
    	private static final Logger LOGGER = Logger.getLogger(ConfigurationPostgresql.class.getName());
     
    	private final String host;
    	private final String login;
    	private final String password;
    	private final String port;
    	private final String database;
    	private final String properties;
     
    	public ConfigurationPostgresql(String host, String login, String password, String port, String database,
    			String properties) {
    		this.host = host;
    		this.login = login;
    		this.password = password;
    		this.port = port;
    		this.database = database;
    		this.properties = properties;
    		LOGGER.log(Level.INFO,getInformations());
    	}
     
    	@Override
    	public String getUrl() {
    		return host;
    	}
     
    	@Override
    	public String getJDBCUrl() {
    		StringBuilder sb = new StringBuilder("jdbc:postgresql://");
    		sb.append(host);
    		sb.append(":");
    		sb.append(port);
    		sb.append("/");
    		sb.append(database);
    		if(properties != null && !properties.isEmpty()) {
    			sb.append("?");
    			sb.append(properties);
    		}
    		return sb.toString();
    	}
     
    	@Override
    	public String getUser() {
    		return login;
    	}
     
    	@Override
    	public String getPassword() {
    		return password;
    	}
     
    	@Override
    	public String getPort() {
    		return port;
    	}
     
    	@Override
    	public String getClassDriver() {
    		return Driver.class.getName();
    	}
     
    	@Override
    	public String getInformations() {
    		StringBuilder sb = new StringBuilder();
    		sb.append("Information BDD Postgres:").append("\n");
    		sb.append("    host: ").append(getUrl()).append("\n");
    		sb.append("    user: ").append(getUser()).append("\n");
    		sb.append("    database name: ").append(database).append("\n");
    		sb.append("    jdbc: ").append(getJDBCUrl()).append("\n");
    		return sb.toString();
    	}
    }
    Et H2:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    package com.calculateur.warhammer.dao.h2;
     
    import java.io.File;
    import java.io.IOException;
     
    import org.apache.commons.io.FileUtils;
    import org.h2.Driver;
     
    import com.calculateur.warhammer.base.server.IDatabaseConfiguration;
     
    import jakarta.annotation.PostConstruct;
    import jakarta.annotation.PreDestroy;
     
    /**
     * La configuration pour une Base de donnée H2
     * 
     * @author phili
     *
     */
    public class ConfigurationH2 implements IDatabaseConfiguration {
     
    	private static final String USER = "sa";
     
    	private static final String USER_PASSWORD = "sa";
     
    	private File useFile;
     
    	private final File initialFile;
     
    	private final File copiedFile;
     
    	private final Integer port;
     
    	private final String path;
     
    	private final String databaseName;
     
    	public ConfigurationH2(File initialFile, File copiedFile, Integer port, String path, String databaseName) {
    		this.initialFile = initialFile;
    		this.copiedFile = copiedFile;
    		this.port = port;
    		this.path = path;
    		this.databaseName = databaseName;
    	}
     
    	@PostConstruct
    	public void init() throws IOException {
    		if (copiedFile != null) {
    			FileUtils.copyDirectory(initialFile, copiedFile);
    			useFile = copiedFile;
    		} else {
    			useFile = initialFile;
    		}
    	}
     
    	@PreDestroy
    	private void destroy() throws IOException {
    		if (copiedFile != null && copiedFile.listFiles() != null) {
    			for(File file:copiedFile.listFiles()) {
    				FileUtils.deleteDirectory(file);
    			}
    		}
    	}
     
    	@Override
    	public String getUrl() {
    		return useFile.getAbsolutePath();
    	}
     
    	@Override
    	public String getJDBCUrl() {
    		StringBuilder sb = new StringBuilder("jdbc:h2:file:");
    		sb.append(useFile.getAbsolutePath());
    		sb.append("/");
    		sb.append(path);
    		sb.append("/");
    		sb.append(databaseName);
    		return sb.toString();
    	}
     
    	@Override
    	public String getUser() {
    		return USER;
    	}
     
    	@Override
    	public String getPassword() {
    		return USER_PASSWORD;
    	}
     
    	@Override
    	public String getPort() {
    		return port.toString();
    	}
     
    	@Override
    	public String getClassDriver() {
    		return Driver.class.getName();
    	}
     
    	@Override
    	public String getInformations() {
    		return null;
    	}
    }
    On a le Design Pattern Stratégie:
    https://fr.wikipedia.org/wiki/Strat%...de_conception)

    On peut de fait avoir une configuration selon la BDD en injectant dans la conf cette interface:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    package com.calculateur.warhammer.dao.configuration.general;
     
    import javax.sql.DataSource;
     
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.jdbc.DataSourceBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.orm.jpa.JpaTransactionManager;
    import org.springframework.orm.jpa.JpaVendorAdapter;
    import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
    import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
    import org.springframework.transaction.PlatformTransactionManager;
     
    import com.calculateur.warhammer.base.server.IDatabaseConfiguration;
    import com.calculateur.warhammer.dao.postgresql.ConfigurationPostgresql;
     
    import jakarta.persistence.EntityManager;
     
    /**
     * Configuration abstraite pour Postgresql
     * @author phili
     *
     */
    @ComponentScan(basePackages = {"com.calculateur.warhammer.dao.dao","com.calculateur.warhammer.dao.dao.applicable"})
    public abstract class AbstractConfigurationPostgreSQL {
     
    	@Value("${databaseHost}")
    	private String databaseHost;
     
    	@Value("${loginDatabase}")
    	private String loginDatabase;
     
    	@Value("${passwordDatabase}")
    	private String passwordDatabase;
     
    	@Value("${portDatabase}")
    	private String portDatabase;
     
    	@Value("${databaseName}")
    	private String databaseName;
     
    	@Value("${databaseProperties}")
    	private String databaseProperties;
     
    	@Bean("configurationPostgresql")
    	public IDatabaseConfiguration getConfiguration() {
    		return new ConfigurationPostgresql(databaseHost,loginDatabase,passwordDatabase,portDatabase,databaseName,databaseProperties);
    	}
     
    	/**
             * 
             * @return Vrai si Hibernate show SQL
             */
    	protected abstract boolean isShowSQL();
     
    	/**
             * 
             * @return Vrai si le sclema doit être créé
             */
    	protected abstract boolean isCreateSchema();
     
    	@Bean(name = "localContainerEntityManagerFactoryBean")
    	public LocalContainerEntityManagerFactoryBean getLocalContainerEntityManagerFactoryBean() {
    		LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
    		bean.setDataSource(getDataSource());
    		bean.setPackagesToScan("com.calculateur.warhammer.entity.entity");
    		bean.setJpaVendorAdapter(getJpaVendorAdapter());
    		return bean;
    	}
     
    	@Bean(name = "jpaVendorAdapter")
    	public JpaVendorAdapter getJpaVendorAdapter() {
    		HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    		adapter.setShowSql(isShowSQL());
    		adapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQLDialect");
    		adapter.setGenerateDdl(isCreateSchema());
    		return adapter;
    	}
     
    	@Bean("entityManager")
    	public EntityManager getEntityManager() {
    		return getLocalContainerEntityManagerFactoryBean().getNativeEntityManagerFactory().createEntityManager();
    	}
     
    	@Bean(name = "dataSource")
    	public DataSource getDataSource() {
    		IDatabaseConfiguration conf = getConfiguration();
    		DataSourceBuilder<?> builder = DataSourceBuilder.create();
    		builder.driverClassName(conf.getClassDriver());
    		builder.url(conf.getJDBCUrl());
    		builder.username(conf.getUser());
    		builder.password(conf.getPassword());
     
    		return builder.build();
    	}
     
    	@Bean(name = "transactionManager")
    	public PlatformTransactionManager getTransactionManager() {
    		JpaTransactionManager transactionManager
            = new JpaTransactionManager();
          transactionManager.setEntityManagerFactory(
            getLocalContainerEntityManagerFactoryBean().getObject() );
          return transactionManager;
    	}
    }
    Mais mieux, cette interface peut être utilisée pour faire du JDBC pure et dure:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    package com.calculateur.warhammer.create.database.sql;
     
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.TreeMap;
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    import com.calculateur.warhammer.base.bdd.IExecuteSQL;
    import com.calculateur.warhammer.base.exception.DAOException;
    import com.calculateur.warhammer.base.server.IDatabaseConfiguration;
     
    public class ExecuteFichiersSQL implements IExecuteSQL {
     
    	private static final Logger LOGGER = Logger.getLogger(ExecuteFichiersSQL.class.getName());
     
    	private static final String SEPARATOR_SQL_FILE = "_";
     
    	private static final String SQL_COMMENTAIRE = "--";
     
    	private static final int INDEX_NUMERO = 0;
     
    	private final File folderSQL;
     
    	private final IDatabaseConfiguration configuration;
     
    	private final Map<Integer, File> mapExecution;
     
    	public ExecuteFichiersSQL(File folderSQL, IDatabaseConfiguration configuration) {
    		this.folderSQL = folderSQL;
    		this.configuration = configuration;
    		mapExecution = new TreeMap<>();
    	}
     
    	@Override
    	public void executeSQL() throws DAOException {
    		try {
    			determinerOrdreExecution();
    			executeSQLFiles();
    		} catch (Exception e) {
    			throw new DAOException(e);
    		}
    	}
     
    	private void determinerOrdreExecution() {
    		String fileName;
    		String[] tab;
    		Integer order;
    		for (File sqlFile : folderSQL.listFiles()) {
    			fileName = sqlFile.getName();
    			tab = fileName.split(SEPARATOR_SQL_FILE);
    			order = Integer.parseInt(tab[INDEX_NUMERO]);
    			mapExecution.put(order, sqlFile);
    		}
    	}
     
    	private void executeSQLFiles() throws ClassNotFoundException, SQLException, IOException {
    		Class.forName(configuration.getClassDriver());
    		try (Connection connection = DriverManager.getConnection(configuration.getJDBCUrl(), configuration.getUser(),
    				configuration.getPassword())) {
    			for (Entry<Integer, File> entry : mapExecution.entrySet()) {
    				LOGGER.info("Execution ficnier n°" + entry.getKey() + " " + entry.getValue().getAbsolutePath());
    				executeSQLFile(connection, entry.getValue());
    				LOGGER.info("Le ficnier n°" + entry.getKey() + " " + entry.getValue().getAbsolutePath()+" a été executé entièrement");
    			}
    		}
    	}
     
    	private void executeSQLFile(Connection connection, File file) throws IOException, SQLException {
    		try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    			String sql;
    			while ((sql = br.readLine()) != null) {
    				if(!sql.isEmpty() && !sql.startsWith(SQL_COMMENTAIRE)) {
    					executeUpdate(connection, sql);
    				}
    			}
    		}
    	}
     
    	private void executeUpdate(Connection connection,String sql)throws SQLException{
    		try(PreparedStatement ps =connection.prepareStatement(sql)){
    			LOGGER.log(Level.INFO,"Execute SQL : {0}",sql);
    			ps.executeUpdate();
    		}
    	}
    }

  3. #3
    Membre à l'essai
    Homme Profil pro
    En recherche d’emploi
    Inscrit en
    Mai 2015
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : En recherche d’emploi
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Mai 2015
    Messages : 14
    Points : 14
    Points
    14
    Par défaut vers une interface contrat
    Bonjour et merci pour le retour, je suis preneur.
    Si je vous suis bien il existe une interface contrat avec un pattern Configuration de BDD (architecture au choix)
    et l'appel de ses méthodes sur l'objet Connection JDBC permet d'actualiser la connection en fonction du choix retenu.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    	public ExecuteFichiersSQL(File folderSQL, IDatabaseConfiguration configuration) {
    		this.folderSQL = folderSQL;
    		this.configuration = configuration;
    		mapExecution = new TreeMap<>();
    	}
    Et plus interessant, le dernier code montre que l'on peut separer le code sql pur JDBC du programme (executeSQLFile).
    De mon coté j'ai repris votre suggestion d'interface contrat et ai écris sur l'encapsulation d'une classe Employee.java et sa version persistante via JDBC (create (le code ci-dessous, update, delete), la différence avec mon dernier programme est qu'il y a une dépendance avec la classe Employee
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
     
    public class EmployeeManager {
     
        Connection connection;
     
        public EmployeeManager() {}
     
        public void openConnection() {
           ConfigurationPostgresql cfp = new  ConfigurationPostgresql("localhost", "root", "xxx", "8080", "eltechdb", "");
           connection = DriverManager.getConnection(cfp.getJDBCUrl(), cfp.getUser(), cfp.getPassword());
     
        }
     
        // create N rows in the database with Employee Object
        public void saveEmployee(List<Emp> emps) {
    	String req = "INSERT INTO tblEmployees (emp_no, birth_date, first_name, last_name, gender, hire_date) VALUES=(emp_no=:emp_no, birth_date=:birth_date, first_name=:first_name, last_name=:last_name, gender=:gender, hire_date=:hire_date);";
            PreparedStatement prestmt = connection.prepareStatement(req);
    	while (emps.hasNext()) {
               try {
                  theEmp = (Emp) emps.next();
    	      prestmt.setString("emp_no", theEmp.getId());
    	      prestmt.setString("first_name", theEmp.getFirstName());
    	      prestmt.setString("last_name", theEmp.getLastName());	      
    	      prestmt.setString("birth_date", theEmp.getBirthDate());
    	      prestmt.setString("gender", theEmp.getGender());	      
      	      prestmt.setString("hire_date", theEmp.getHireDate());
                  prestmt.executeUpdate();
    	   }
    	   catch (SQLException ex) {
                 System.out.println("error save Employee");
    	   }
    	   prestmt.close();
    	}
        }
    }
    Merci encore pour le lien vers votre projet. Ca m'aidera pour mieux separer logique et acces dao, meme si je ne suis pas sur

  4. #4
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    453
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 453
    Points : 883
    Points
    883
    Billets dans le blog
    5
    Par défaut
    Toujours garder en mémoire "Je sais ce que tu fais mais je ne veux pas savoir comment t'es codé.".

    Je pense que tu es sur la bonne voie.

    Néanmoins, toujours selon ce principe, le EmployeeManager doit implémenter une interface pour pouvoir être injecté là où l'on demande le traitement. C'est de l'injection de dépendance:
    https://fr.wikipedia.org/wiki/Inject...C3%A9pendances

    Spring est le frameworks le plus souvent utilisé pour faire ça.

    Par ailleurs, en général, en BDD, on fait toujours la même chose, du CRUD (Create, Read, Update, Delete).
    https://fr.wikipedia.org/wiki/CRUD

    On utilise de fait une DAO pour faire ça:
    https://www.baeldung.com/java-dao-pattern

    Notez que la DAO peut s'appliquer à une BDD relationnelle, NO-SQL, voir SQL ou simplement un système de fichier...

    Dans mon projet, j'ai aussi définit ça:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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;
    }
    Enfin, détail sur le code, il faut faire attention à ce qui est Closable/Autoclosable et utiliser le TRY-WITH-RESSOURCES

    Dans la liste, on a:
    La connexion JDBC
    Le Prepared Statment
    Le ResultSet
    ....

    De plus, on préfère le foreach au while.

    De même, du point de vue de la base de donnée, on est dans une transaction, donc il faut ROLLBACK si on a une erreur.

    Pour ma DAO, implémenté via Hibernate/JPA, j'utilise le template Method suivant (Un autre Design Pattern):
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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());
    	}
    }

Discussions similaires

  1. [MySQL-JDBC] Problème de CLASSPATH
    Par stukov dans le forum JDBC
    Réponses: 3
    Dernier message: 14/03/2006, 13h55
  2. [Mysql][JDBC][Java]
    Par julienduprat dans le forum SQL Procédural
    Réponses: 1
    Dernier message: 03/03/2006, 13h29
  3. [JDBC]pb com.mysql.jdbc.Driver
    Par fafaroro dans le forum Eclipse Java
    Réponses: 4
    Dernier message: 30/12/2005, 20h42
  4. [Débutant] MySQL, JDBC et combolists à jour
    Par calogerogigante dans le forum JDBC
    Réponses: 9
    Dernier message: 06/09/2005, 17h40
  5. [Mysql][JDBC] Votre avis !
    Par sebb84 dans le forum JDBC
    Réponses: 5
    Dernier message: 07/12/2004, 14h59

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo