Estructura de un proyecto empresarial típico de Spring Framework

Estructura de un proyecto empresarial típico de Spring Framework

Entenderemos como se logra persistencia entre una base de datos y la estructura de un proyecto Spring, utilizando el patron D.A.O (data access object)

Crearemos un proyecto Maven, haremos divisiones por capas de servicios, de datos y algunas consideraciones a tener en cuenta.

  • Herramientas Utilizadas

  • IDE Spring Tool Suite, JDK 8

  • MySql Workbench como gestor de base de datos, Xampp Server como servidor MySQl

1 – Creamos el Diagrama de Entidades(modelo de negocio)

image.png

Creamos la BD

CREATE DATABASE `springdb2` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `springdb2`;
CREATE TABLE `equipo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nombre` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `jugador` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nombre` varchar(45) DEFAULT NULL,
  `idEquipo` int(11) NOT NULL,
  `idCamiseta` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `camiseta` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `numero` varchar(45) DEFAULT NULL,
  `idMarca` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `marca` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nombre` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/* Ahora creamos las relaciones */;
alter table jugador add constraint  FK_Jugador_Equipo foreign key (idEquipo) references equipo(id) on delete cascade on update cascade;
alter table jugador add constraint  FK_Jugador_Camiseta foreign key (idCamiseta) references camiseta(id) on delete cascade on update cascade;
alter table camiseta add constraint  FK_Camiseta_Marca foreign key (idMarca) references marca(id) on delete cascade on update cascade;

Visualizamos la Bd

image.png

2-Creamos el proyecto Maven

Org.apache.maven.archetype-quickstart

image.png

image.png Agregamos una carpeta src/main/resources , donde allí iran colocado el archivo de configuración bean.xml

image.png Me voy al builth path del proyecto Builthsource-> add folder

image.png

image.png Agrego las dependencias necesarias

image.png Listo de configuraciones , ahora creamos los paquetes y las clases del proyecto

4-Creamos las entidades

image.png

image.png Tambien las creamos con sus getters and setter

4.1 Empezampos a crear el patrón DAO

Empezaremos a trabajar con la clase MARCA

image.png DAOMarca.java

package com.mitocode.dao;
import com.mitocode.beans.Marca;
public interface DAOMarca {
    public void registrar(Marca marca) throws Exception;
}

DAOMarcaImpl.java

@Repository
public class DAOMarcaImpl implements DAOMarca {
    @Autowired
    private DataSource dataSource;
    @Override
    public void registrar(Marca marca) throws Exception {
        String sql="INSERT INTO marca(id,nombre) values(?,?)";
        Connection con=null;
        try {
            con=dataSource.getConnection();
            PreparedStatement ps=con.prepareStatement(sql);
            ps.setInt(1,marca.getId());
            ps.setString(2,marca.getNombre());
            ps.executeUpdate();
            ps.close();
        } catch (Exception e) {
            throw e;
        }finally {
            if(con !=null) {
                con.close();
            }
        }
        }
}

ServiceMarca.java

package com.mitocode.service;
import com.mitocode.beans.Marca;
public interface ServiceMarca {
    public void registrar(Marca marca) throws Exception;
}

ServiceMarcaImpl.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mitocode.beans.Marca;
import com.mitocode.dao.DAOMarca;
@Service
public class ServiceMarcaImpl implements ServiceMarca{
    @Autowired
    private DAOMarca daoMarca;
    @Override
    public void registrar(Marca marca) throws Exception {
         try {
            daoMarca.registrar(marca);
        } catch (Exception e) {
            throw e;
        }
   }
}

Configuramos el archivo Beans.xml beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc.xsd  ">
<context:component-scan base-package="com.mitocode"/>
<bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/springdb2"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
 </bean>
  <bean id="marca3"  class="com.mitocode.beans.Marca">
      <property name="id" value="3"></property>
      <property name="nombre"  value="Marca3"></property>
  </bean>

</beans>

image.png

4.2 Analizamos la Entidad Marca

image.png

image.png

image.png

Analizamos el Service

image.png

4.3 Ejecutamos la aplicación

App.java

package com.mitocode.springdb;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mitocode.beans.Marca;
import com.mitocode.service.ServiceMarca;
public class App {
    public static void main( String[] args ){
        System.out.println( "Hello World!" );
        Marca mar=new Marca();
        mar.setId(2);
        mar.setNombre("Marca2");
         ApplicationContext appContext = new 
       ClassPathXmlApplicationContext("com/mitocode/xml/beans.xml");
        ServiceMarca sm=(ServiceMarca) appContext.getBean("serviceMarcaImpl");
        Marca mar3=(Marca)appContext.getBean("marca3");
         try {
              sm.registrar(mar);
             //sm.registrar(mar3);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

image.png

image.png Nos fijamos en Workbench , en la bd

image.png los registros se insertaron correctamente!!

image.png Fuente en la que me base para hacer y esxpilcar este tema tan importante youtube.com/watch?v=hinfBLVsqF4&t=166s Spring Framework Tutorial - 25 MySQL-MITOCODE – Año 2017 . Actualizado al 2022