Antes de empezar

1

Pasos para aprender Java Spring

2

Instalación de ambiente de desarrollo: Windows

3

¿Java sigue siendo gratuito?

4

Instalación de ambiente de desarrollo: Linux Ubuntu

5

Instalación de ambiente de desarrollo: macOS

Introducción a Spring boot

6

¿Qué es y qué usaremos de Spring?

7

Conocer qué es una aplicación autocontenida

8

Crear nuestra aplicación con Spring Initializr

9

Hola mundo con Spring Boot

10

Configurar Spring Boot

11

Crear la estructura del proyecto

Spring Data

12

¿Qué es JPA?

13

Conocer qué es Spring Data

14

Conectar la base de datos a nuestra aplicación

15

Mapear las tablas como clases

16

Crear Entity cuando su clave primaria es compuesta

17

Mapear relaciones entre clases

18

Usar la interface CrudRepository

19

Query Methods

Construyendo nuestra API

20

Implementar la anotación @Repository

21

¿Qué es el patrón Data Mapper y qué resuelve?

22

Orientar nuestra API al dominio con MapStruct

23

Orientar nuestro repositorio a términos del dominio

24

Inyección de dependencias

25

Implementar la anotación @Service

26

Implementar la anotación @RestController

27

Exponer nuestra API

Mejorando nuestra API

28

Controlar las respuestas HTTP

29

Crear el dominio de compras

30

Mapear el dominio de compras

31

Crear el repositorio de compras

32

Probando nuestros servicios de compras

33

Documentar nuestra API con Swagger

Spring Security

34

Configurar la seguridad de nuestra API con Spring Security

35

Generar un JWT

36

Autenticación con JWT

37

Autorización con JWT

Despliegue de nuestra aplicación

38

Desplegar nuestra API desde la ventana de comandos

39

Desplegar nuestra base de datos con Heroku

40

Desplegar nuestra API con Heroku

41

Conclusiones y despedida del curso

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Aprende todo un fin de semana sin pagar una suscripción 🔥

Aprende todo un fin de semana sin pagar una suscripción 🔥

Regístrate

Comienza en:

2D
13H
35M
38S
Curso de Java Spring

Curso de Java Spring

Alejandro Ramírez

Alejandro Ramírez

Conectar la base de datos a nuestra aplicación

14/41
Recursos

Aportes 72

Preguntas 39

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

o inicia sesión.

Aunque java puede descubrir el driver por la url, es buena practica decir el driver. Para postgresql

spring.datasource.driver-class-name=org.postgresql.Driver

De esta forma Spring usara ese driver y si la url esta mal escrita indicará los errores, sino se coloca el driver y la url esta mal escrita Spring dira que no encuentra driver para conectarse.

Para aquel que esté enfrentando los problemas de:

  • Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
  • Access to DialectResolutionInfo cannot be null when ‘hibernate.dialect’ not set
  • Execution failed for task…

Deben colocar en application-dev.properties y en application-pdn.properties la siguiente línea:

spring.jpa.database=postgresql

Para usar MySql

implementation 'mysql:mysql-connector-java'
spring.datasource.url=jdbc:mysql://localhost/java?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Si alguien quiere user postgres y pgadmin con docker-compose, puede usar lo siguiente:

version: '3'
services:
  db:
    image: 'postgres:alpine'
    ports:
      - '5432:5432'
    environment:
      POSTGRES_USER: 'postgres'
      POSTGRES_PASSWORD: 'platzi'
      POSTGRES_DB: 'platzi-market'
    volumes:
      - db-data:/var/lib/postgresql/data/
      # - ./db:/docker-entrypoint-initdb.d

  pgadmin:
    image: dpage/pgadmin4:4.22
    environment:
      PGADMIN_DEFAULT_EMAIL: admin@example.com
      PGADMIN_DEFAULT_PASSWORD: admin
      PGADMIN_LISTEN_PORT: 80
    ports:
      - '64374:80'
    volumes:
      - pgadmin-data:/var/lib/pgadmin
    depends_on:
      - db

volumes:
  db-data:
  pgadmin-data:

Podríamos incluir Flyway para versionar la base de datos y mantener la consistencia sin importar si ejecutamos la aplicación en desarollo o producción.

Con solo incluir la dependencia de flyway en el proyecto, el starter de spring boot data jpa se encarga de autoconfigurarlo.

dependencies {

	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.flywaydb:flyway-core:7.0.0'

	runtimeOnly 'org.postgresql:postgresql'

	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

Dentro de resources creamos la estructura de carpetas como se muestra en la imagen y un archivo donde pegaremos el contenido de schema.sql

Ya solo bastaría agregar una clase para decirle a flyway que ejecute todos los scripts que encuentre en la carpeta db/migration

@Configuration
public class DatabaseConfig {

    @Bean
    public FlywayMigrationStrategy migrationStrategy() {
        return flyway -> {
            flyway.repair();
            flyway.migrate();
        };
    }
}

Al correr la aplicación veremos que se genera una tabla que lleva el control de las versiones de la base de datos llamada flyway_schema_history.

Si necesitamos cambiar la estructura de la base de datos ya solo agregaremos archivos .sql en la carpeta db/migration y flyway se encargará de ejecutarlos automáticamente. Así mantenemos la consistencia en todos los ambientes donde ejecutemos la aplicación sin tener que correr los scripts manualmente.

Estuve 30 minutos con un error de contraseña hasta que me di cuenta que escribí sping.datasource.password

Schema Mysql :


– Table “CATEGORIAS”


CREATE TABLE CATEGORIAS (
id_categoria int NOT NULL,
descripcion VARCHAR(45) NOT NULL,
estado BOOLEAN NOT NULL,
PRIMARY KEY (id_categoria));


– Table “PRODUCTOS”


CREATE TABLE PRODUCTOS (
id_producto int NOT NULL,
nombre VARCHAR(45) NULL,
id_categoria INT NOT NULL,
codigo_barras VARCHAR(150) NULL,
precio_venta DECIMAL(16,2) NULL,
cantidad_stock INT NOT NULL,
estado BOOLEAN NULL,
PRIMARY KEY (id_producto),
CONSTRAINT fk_PRODUCTOS_CATEGORIAS
FOREIGN KEY (id_categoria)
REFERENCES CATEGORIAS (id_categoria)
ON DELETE NO ACTION
ON UPDATE NO ACTION);


– Table “CLIENTES”


CREATE TABLE CLIENTES (
id VARCHAR(20) NOT NULL,
nombre VARCHAR(40) NULL,
apellidos VARCHAR(100) NULL,
celular NUMERIC NULL,
direccion VARCHAR(80) NULL,
correo_electronico VARCHAR(70) NULL,
PRIMARY KEY (id));


– Table “COMPRAS”


CREATE TABLE COMPRAS (
id_compra int NOT NULL,
id_cliente VARCHAR(20) NOT NULL,
fecha TIMESTAMP NULL,
medio_pago CHAR(1) NULL,
comentario VARCHAR(300) NULL,
estado CHAR(1) NULL,
PRIMARY KEY (id_compra),
CONSTRAINT fk_COMPRAS_CLIENTES1
FOREIGN KEY (id_cliente)
REFERENCES CLIENTES (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION);


– Table “COMPRAS_PRODUCTOS”


CREATE TABLE COMPRAS_PRODUCTOS (
id_compra INT NOT NULL,
id_producto INT NOT NULL,
cantidad INT NULL,
total DECIMAL(16,2) NULL,
estado BOOLEAN NULL,
PRIMARY KEY (id_compra, id_producto),
CONSTRAINT fk_COMPRAS_PRODUCTOS_PRODUCTOS1
FOREIGN KEY (id_producto)
REFERENCES PRODUCTOS (id_producto)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_COMPRAS_PRODUCTOS_COMPRAS1
FOREIGN KEY (id_compra)
REFERENCES COMPRAS (id_compra)
ON DELETE NO ACTION
ON UPDATE NO ACTION);

Hubiese sido interesante que usará Hibernate para crear las tablas, sin necesidad de escribir el SQL

para los que les aparece el siguiente error:

"Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured"
les recomiendo que en el archivo aplication.properties ingresen el iguiente codigo:

spring.autoconfigure.exclude = org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration 

Esto por que debe configurar el controlador de la base de datos y las propiedades de conexión de JDBC.

Configuración para realizar la conexión a base de datos

#DataBase
spring.datasource.url=jdbc:postgresql://localhost:5432/platzi-market
spring.datasource.username=postgres
spring.datasource.password=platzi
spring.datasource.driver-class-name=org.postgresql.Driver

Para los que usan maven

<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.20</version>
</dependency>

Para Sql Server

implementation group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '8.4.1.jre14'
<code>spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=employees
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql = true

Si les da error al ejecutar el archivo data.sql en la línea:

INSERT INTO compras VALUES (1, '4546221', '10/08/1992 17:30:00', 'E', '', 'P');

Yo en mi caso cambie el formato de la fecha para ‘1992/10/08 17:30:00’, entonces toda la línea queda:

INSERT INTO compras VALUES (1, '4546221', '1992/10/08 17:30:00', 'E', '', 'P');

Y me funciono luego la ejecución.

Hola! para los que usan ubuntu como yo, al momento de entrar a pgadmin no hay ningún servidor configurado, por esa razón tenemos que crear uno nuevo.

Damos clic derecho sobre Servers> create > server

Acá nos muestra una ventana de dialogo en la que nos pide nombre en la pestaña “General” y luego el host en la pestaña “Connection”. En el nombre le damos el nombre que queramos y en Connection se pone localhost, se deja el puerto por defecto y ponemos la contraseña del usuario postgres (si es que tenemos una definida), luego damos clic en save (guardar) listo, tenemos nuestro servidor local.

Y para los que tienen Ubuntu pueden instalar Postgresql

sudo apt update
sudo apt install postgresql postgresql-contrib

Al instalar se crea una cuenta de usuario llamada postgres en el sistema linux , que se asocia con el rol preterminado de Postgresql
Para iniciar postgres , debemos iniciar sesion en esa cuenta.

-> cambiando a la cuenta de postgres
**sudo -i -u postgres **
-> acceder a la linea de comnados de PostgreSQL
psql

Ahora puede crear sus roles , bases de datos , tablas , etc.

-> para salir de esa linea de comandos de PostgreSQL
postgres=# \q
Con esto regresará a la linea de comadnos de linux de postgres.

/* para los que usan mysql ya esta con datos y relaciones */


– Host: localhost
– Versión del servidor: 5.7.24 - MySQL Community Server (GPL)
– SO del servidor: Win64
– HeidiSQL Versión: 11.0.0.5919


/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT /;
/
!40101 SET NAMES utf8 /;
/
!50503 SET NAMES utf8mb4 /;
/
!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 /;
/
!40101 SET @[email protected]@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO’ */;

– Volcando estructura de base de datos para platzi-market
CREATE DATABASE IF NOT EXISTS platzi-market /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_spanish_ci */;
USE platzi-market;

– Volcando estructura para tabla platzi-market.categorias
CREATE TABLE IF NOT EXISTS categorias (
id_categoria int(11) NOT NULL AUTO_INCREMENT,
descripcion varchar(45) NOT NULL DEFAULT ‘0’,
estado int(11) NOT NULL DEFAULT ‘0’,
PRIMARY KEY (id_categoria),
KEY id_categoria (id_categoria)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

– Volcando datos para la tabla platzi-market.categorias: ~8 rows (aproximadamente)
DELETE FROM categorias;
/*!40000 ALTER TABLE categorias DISABLE KEYS /;
INSERT INTO categorias (id_categoria, descripcion, estado) VALUES
(1, ‘Frutas y verduras’, 1),
(2, ‘Pastelería’, 1),
(3, ‘Carnes y pescados’, 1),
(4, ‘Frutas y verduras’, 1),
(5, ‘Bebidas’, 1),
(6, ‘Licores’, 1),
(7, ‘Cuidado personal’, 1),
(8, ‘Despensa’, 1);
/
!40000 ALTER TABLE categorias ENABLE KEYS */;

– Volcando estructura para tabla platzi-market.clientes
CREATE TABLE IF NOT EXISTS clientes (
id varchar(20) NOT NULL,
nombre varchar(40) DEFAULT NULL,
apellidos varchar(100) DEFAULT NULL,
celular decimal(10,0) DEFAULT ‘0’,
direccion varchar(80) DEFAULT ‘0’,
correo_electronico varchar(70) DEFAULT ‘0’,
PRIMARY KEY (id),
KEY id (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

– Volcando datos para la tabla platzi-market.clientes: ~3 rows (aproximadamente)
DELETE FROM clientes;
/*!40000 ALTER TABLE clientes DISABLE KEYS /;
INSERT INTO clientes (id, nombre, apellidos, celular, direccion, correo_electronico) VALUES
(‘2552243’, ‘Galileo’, ‘Galilei’, 3462257293, ‘Cl 1 # 11 - 11’, ‘[email protected]’),
(‘4546221’, ‘Johannes’, ‘Kepler’, 3104583224, ‘Cl 3 # 33 - 33’, ‘[email protected]’),
(‘983824’, ‘Nicolás’, ‘Copernico’, 3019392466, ‘Cl 2 # 22 - 22’, ‘[email protected]’);
/
!40000 ALTER TABLE clientes ENABLE KEYS */;

– Volcando estructura para tabla platzi-market.compras
CREATE TABLE IF NOT EXISTS compras (
id_compra int(11) NOT NULL AUTO_INCREMENT,
id_cliente varchar(20) NOT NULL DEFAULT ‘’,
fecha datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
medio_pago char(1) DEFAULT ‘’,
comentario varchar(300) DEFAULT ‘’,
estado char(1) DEFAULT ‘’,
PRIMARY KEY (id_compra),
KEY id_compra (id_compra),
KEY id_cliente (id_cliente),
CONSTRAINT FK_compras_clientes FOREIGN KEY (id_cliente) REFERENCES clientes (id)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

– Volcando datos para la tabla platzi-market.compras: ~1 rows (aproximadamente)
DELETE FROM compras;
/*!40000 ALTER TABLE compras DISABLE KEYS /;
INSERT INTO compras (id_compra, id_cliente, fecha, medio_pago, comentario, estado) VALUES
(1, ‘4546221’, ‘1992-10-08 17:30:00’, ‘E’, ‘’, ‘P’);
/
!40000 ALTER TABLE compras ENABLE KEYS */;

– Volcando estructura para tabla platzi-market.compras_productos
CREATE TABLE IF NOT EXISTS compras_productos (
id_compra int(11) NOT NULL,
id_producto int(11) NOT NULL,
cantidad int(11) DEFAULT NULL,
total decimal(16,2) DEFAULT NULL,
estado tinyint(4) DEFAULT NULL,
KEY id_compra (id_compra),
KEY id_producto (id_producto),
CONSTRAINT FK_compras_productos_compras FOREIGN KEY (id_compra) REFERENCES compras (id_compra),
CONSTRAINT id_productofk FOREIGN KEY (id_producto) REFERENCES productos (id_producto)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

– Volcando datos para la tabla platzi-market.compras_productos: ~6 rows (aproximadamente)
DELETE FROM compras_productos;
/*!40000 ALTER TABLE compras_productos DISABLE KEYS /;
INSERT INTO compras_productos (id_compra, id_producto, cantidad, total, estado) VALUES
(1, 1, 10, 3000.00, 1),
(1, 36, 1, 40000.00, 1),
(1, 27, 1, 9000.00, 1),
(1, 49, 2, 16400.00, 1),
(1, 24, 1, 4000.00, 1);
/
!40000 ALTER TABLE compras_productos ENABLE KEYS */;

– Volcando estructura para tabla platzi-market.productos
CREATE TABLE IF NOT EXISTS productos (
id_producto int(11) NOT NULL AUTO_INCREMENT,
nombre varchar(50) DEFAULT ‘0’,
id_categoria int(11) NOT NULL DEFAULT ‘0’,
codigo_barras varchar(50) DEFAULT ‘0’,
precio_venta decimal(16,2) DEFAULT ‘0.00’,
cantidad_stock int(11) NOT NULL DEFAULT ‘0’,
estado tinyint(4) DEFAULT ‘0’,
PRIMARY KEY (id_producto),
KEY id_producto (id_producto),
KEY id_categoria (id_categoria),
CONSTRAINT FK_productos_categorias FOREIGN KEY (id_categoria) REFERENCES categorias (id_categoria)
) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=latin1;

– Volcando datos para la tabla platzi-market.productos: ~50 rows (aproximadamente)
DELETE FROM productos;
/*!40000 ALTER TABLE productos DISABLE KEYS /;
INSERT INTO productos (id_producto, nombre, id_categoria, codigo_barras, precio_venta, cantidad_stock, estado) VALUES
(1, ‘Guayaba Feijoa’, 1, ‘7029 A42 23’, 300.00, 500, 1),
(2, ‘Mango’, 1, ‘0316 R56 01’, 2100.00, 250, 1),
(3, ‘Manzana’, 1, ‘7923 T23 19’, 700.00, 130, 1),
(4, ‘Aguacate’, 1, ‘9322 Q33 02’, 2500.00, 98, 1),
(5, ‘Lechuga’, 1, ‘9742 S22 21’, 4000.00, 86, 1),
(6, ‘Tomate’, 1, ‘0483 R00 97’, 290.00, 430, 1),
(7, ‘Pera’, 1, ‘9999 X10 01’, 750.00, 210, 1),
(8, ‘Apio’, 1, ‘3390 F29 45’, 150.00, 115, 1),
(9, ‘Papaya’, 1, ‘5291 J34 32’, 4500.00, 73, 1),
(10, ‘Limón’, 1, ‘7886 N18 32’, 350.00, 425, 1),
(11, ‘Brownie’, 2, ‘6683 H15 20’, 2500.00, 80, 1),
(12, ‘Pan tajado’, 2, ‘5745 F05 47’, 4500.00, 120, 1),
(13, ‘Torta’, 2, ‘3831 D97 99’, 10000.00, 35, 1),
(14, ‘Tortilla’, 2, ‘4335 Z33 84’, 6400.00, 87, 1),
(15, ‘Tostadas’, 2, ‘6584 M19 25’, 4000.00, 45, 1),
(16, ‘Chocorramo’, 2, ‘4487 S00 97’, 2000.00, 105, 1),
(17, ‘Salmón’, 3, ‘4546 A00 01’, 28000.00, 55, 1),
(18, ‘Punta de anca’, 3, ‘3678 E57 22’, 12000.00, 32, 1),
(19, ‘Posta’, 3, ‘8893 O01 03’, 7800.00, 40, 1),
(20, ‘Costilla de cerdo’, 3, ‘4534 Q12 88’, 8600.00, 70, 1),
(21, ‘Tilapia’, 3, ‘5684 R53 02’, 17000.00, 60, 1),
(22, ‘Merluza’, 3, ‘3523 R04 00’, 23000.00, 45, 1),
(23, ‘Leche de vaca’, 4, ‘2323 T56 33’, 2500.00, 500, 1),
(24, ‘Queso’, 4, ‘7786 K19 56’, 4000.00, 300, 1),
(25, ‘Huevos de gallina feliz’, 4, ‘3478 M74 01’, 400.00, 1000, 1),
(26, ‘Clara de huevo’, 4, ‘7932 R31 46’, 3200.00, 200, 1),
(27, ‘Suero costeño’, 4, ‘5463 W23 33’, 9000.00, 110, 1),
(28, ‘Agua’, 5, ‘8965 I32 11’, 2000.00, 600, 1),
(29, ‘Jugo de naranja’, 5, ‘7445 T87 44’, 7400.00, 200, 1),
(30, ‘Gaseosa Colombiana’, 5, ‘3434 R34 63’, 3100.00, 175, 1),
(31, ‘Jugo de Lulo’, 5, ‘9753 W33 19’, 8250.00, 630, 1),
(32, ‘Tea’, 5, ‘9836 F35 69’, 1900.00, 450, 1),
(33, ‘Cerveza’, 6, ‘3432 G67 21’, 2100.00, 800, 1),
(34, ‘Tequila’, 6, ‘9529 E45 98’, 65000.00, 764, 1),
(35, ‘Ron’, 6, ‘1947 R07 53’, 55000.00, 240, 1),
(36, ‘Aguardiente Antioqueño’, 6, ‘3160 A54 94’, 40000.00, 480, 1),
(37, ‘Vino’, 6, ‘7891 W46 95’, 82000.00, 560, 1),
(38, ‘Crema dental’, 7, ‘6310 C99 73’, 7500.00, 200, 1),
(39, ‘Jabón de manos’, 7, ‘9371 J14 75’, 4900.00, 90, 1),
(40, ‘Enjuague bucal’, 7, ‘1942 T68 01’, 12000.00, 105, 1),
(41, ‘Shampoo’, 7, ‘6789 W01 23’, 9300.00, 200, 1),
(42, ‘Desodorante’, 7, ‘7333 S21 36’, 6900.00, 85, 1),
(43, ‘Arroz’, 8, ‘4676 I83 00’, 3500.00, 600, 1),
(44, ‘Lentejas’, 8, ‘7333 S21 36’, 3000.00, 560, 1),
(45, ‘Harina’, 8, ‘7333 S21 36’, 1800.00, 300, 1),
(46, ‘Sal’, 8, ‘7333 S21 36’, 1400.00, 500, 1),
(47, ‘Aceite’, 8, ‘7333 S21 36’, 6500.00, 135, 1),
(48, ‘Cereal’, 8, ‘4673 K53 98’, 7000.00, 75, 1),
(49, ‘Frijol’, 8, ‘2745 F40 45’, 8200.00, 270, 1),
(50, ‘Café’, 8, ‘6351 R33 92’, 7200.00, 400, 1);
/
!40000 ALTER TABLE productos ENABLE KEYS */;

/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, ‘’) /;
/
!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) /;
/
!40101 SET [email protected]_CHARACTER_SET_CLIENT */;

Instalé la última versión (v13.1) y no me funcionó se quedó ciclado y bajé a la versión 11.10 y esta funcionando correcto, por si a alguien le paso lo mismo.

Como conectar SpringBoot a una Base de Datos

Spring Boot te permite conectarte a una base de datos de forma simple y con minimas configuraciones.
Veamos en este post como conectarse a una base de datos.
Como conectar Spring Boot con una base de datos

Puedes crear una conexión a una base de datos en Spring Boot con pocos pasos.

  • Define la base de datos que quieres utilizar.
  • Incluye las dependencias.
  • Define los parámetros de conexión en el archivo de propiedades.

Define la base de datos

En este ejemplo, nosotros usaremos MySql, pero la configuración aplica a cualquier base de datos. La única diferencia es la dependencia necesaria para conectar tu base de datos con tu servicio.
Dependencias para crear la conexión con la base de datos en Spring Boot

Para crear una DB conexión, tu necesitas las siguientes dependencias.

Para MySql necesitas:

‘mysql:mysql-connector-java:8.0.28’

Para PostgreSQL:

‘org.postgresql:postgresql’

Para Oracle:

‘com.oracle.database.jdbc:ojdbc8’

Para MSSQL:

‘com.microsoft.sqlserver:mssql-jdbc’

Los parámetros de conexión en el archivo de propiedades

En estas propiedades, nosotros primero debemos establecer el path de conexión con la DB. Luego indicamos el user y el password. Con esta minima configuración y la dependencia, ya es suficiente para Spring entender como conectarse.

La configuración minima para conectar a la base queda así:

Para MySql:

spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_user
spring.datasource.password=your_password

Para PostgreSQL:

spring.datasource.url=jdbc:postgresql://localhost:5432/your_database
spring.datasource.username=your_user
spring.datasource.password=your_password

Para Oracle:

spring.datasource.url=jdbc:oracle://localhost:1521/your_database
spring.datasource.username=your_user
spring.datasource.password=your_password

Para MSSQL:

spring.datasource.url=jdbc:sqlserver://localhost:1433/your_database
spring.datasource.username=your_user
spring.datasource.password=your_password

*Observa que el puerto y la url podrían cambiar dependiendo de la instalación de cada base de datos.

Execution failed for task ':EndeporteApplication.main()'.
> Process 'command 'C:/Program Files/AdoptOpenJDK/jdk-11.0.9.101-hotspot/bin/java.exe'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

¿Porque aparece ese error ?

Saludos, buen día

EN mi caso utilice docker-compose

Agrego commandos para crear, detener, iniciar o eliminar recursos.

### Crear el compose
docker-compose up -d

### detener los containers
docker-compose stop

### iniciar contenedores
docker-compose start

### eliminar los contenedores
docker-compose down

El docker compose crea los siguientes elementos

  • La base de datos postgres (platzi-postgres)
  • PGAdmin (platzi-pgadmin)
  • Volumen para almacenar los datos (platzi-postgres-volume)
  • La red donde se conectan los componentes (platzi-postgres_network)

Para conectarse de PGAdmin a la base de datos, al crear el server, en lugar de localhost, se usa el nombre del contenedor
platzi-postgres

El archivo yaml, esta a la altura del archivo build.gradle

version: "3.8"
services:
  postgres:
    image: postgres:11
    container_name: platzi-postgres
    ports:
        - 5432:5432
    volumes:
        - platzi-postgres-volume:/var/lib/posgresql/data
    environment:
      - POSTGRES_USER=postgres_user
      - POSTGRES_PASSWORD=supersecret
  pgadmin:
    image: dpage/pgadmin4
    container_name: platzi-pgadmin
    restart: always
    ports:
      - 8989:80
    environment:
      - [email protected]
      - PGADMIN_DEFAULT_PASSWORD=SuperSecret

volumes:
  platzi-postgres-volume:

networks:
    default:
      name: platzi-postgres_network

Otra forma de ejecutar los scripts en el mismo proyecto, es incluirlos en la carpeta resources, y agregar al yml o properties
spring.datasource.initialization-mode= always
y ejecutara al inicio tanto el schema como el data sql… esto ayuda mucho para que al momento de subirlo a git o compartir el proyecto, todos los archivos estén en el mismo proyecto

En ocasiones IJ no toma correctamente los drivers del postgres, si es asi agreguen esta linea.

spring.datasource.driver-class-name=org.postgresql.Driver```


Luego si de igual manera no lo lee, reinicien el IJ y deberia de funcionar

Les dejo el docker-compose para los que utilizan docker, y no quieren hacer la instalación del Postgres y pgAdmin en local.

URL: https://github.com/loaizamateo/compose-postgres

¿Como conectar a dos base datos por ejemplo Mysql y ¨Postgresql?

El no poner un número de versión en las dependencias de gradle hace que gradle vaya al servidor a consultar la versión más reciente disponible, lo cual incrementa los tiempos de compilación

Dejo el script sql del esquema por si alguien quiere tenerlo en inglés.

-- -----------------------------------------------------
-- Table "CATEGORIES"
-- -----------------------------------------------------
CREATE TABLE  CATEGORIES (
  "category_id" SERIAL NOT NULL,
  "description" VARCHAR(45) NOT NULL,
  "state" BOOLEAN NOT NULL,
  PRIMARY KEY ("category_id"));


-- -----------------------------------------------------
-- Table "PRODUCTS"
-- -----------------------------------------------------
CREATE TABLE  PRODUCTS (
  "product_id" SERIAL NOT NULL,
  "name" VARCHAR(45) NULL,
  "category_id" INT NOT NULL,
  "barcode" VARCHAR(150) NULL,
  "price" DECIMAL(16,2) NULL,
  "stock_quantity" INT NOT NULL,
  "state" BOOLEAN NULL,
  PRIMARY KEY ("product_id"),
  CONSTRAINT "fk_PRODUCTS_CATEGORIES"
    FOREIGN KEY ("category_id")
    REFERENCES CATEGORIES ("category_id")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);


-- -----------------------------------------------------
-- Table "CLIENTS"
-- -----------------------------------------------------
CREATE TABLE  CLIENTS (
  "id" VARCHAR(20) NOT NULL,
  "name" VARCHAR(40) NULL,
  "surnames" VARCHAR(100) NULL,
  "cellphone" NUMERIC NULL,
  "address" VARCHAR(80) NULL,
  "email" VARCHAR(70) NULL,
  PRIMARY KEY ("id"));


-- -----------------------------------------------------
-- Table "PURCHASES"
-- -----------------------------------------------------
CREATE TABLE  PURCHASES (
  "purchase_id" SERIAL NOT NULL,
  "client_id" VARCHAR(20) NOT NULL,
  "date" TIMESTAMP NULL,
  "payment_method" CHAR(1) NULL,
  "comment" VARCHAR(300) NULL,
  "state" CHAR(1) NULL,
  PRIMARY KEY ("purchase_id"),
  CONSTRAINT "fk_PURCHASES_CLIENTS1"
    FOREIGN KEY ("client_id")
    REFERENCES CLIENTS ("id")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);


-- -----------------------------------------------------
-- Table "PURCHASES_PRODUCTS"
-- -----------------------------------------------------
CREATE TABLE  PURCHASES_PRODUCTS (
  "purchase_id" INT NOT NULL,
  "product_id" INT NOT NULL,
  "quantity" INT NULL,
  "total" DECIMAL(16,2) NULL,
  "state" BOOLEAN NULL,
  PRIMARY KEY ("purchase_id", "product_id"),
  CONSTRAINT "fk_PURCHASES_PRODUCTS_PRODUCTS1"
    FOREIGN KEY ("product_id")
    REFERENCES PRODUCTS ("product_id")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT "fk_PURCHASES_PRODUCTS_PURCHASES1"
    FOREIGN KEY ("purchase_id")
    REFERENCES PURCHASES ("purchase_id")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

En mi caso adicional a definir la clase del driver tuve que cambiar el runtimeOnly a implementation

Quien lo está intentando con Maven, me funciono agregando las siguientes dependencias:

		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
			<version>2.4.5</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<version>42.2.19</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework/spring-dao -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-dao</artifactId>
			<version>2.0.8</version>
		</dependency>

En mi caso yo no instalé ni PostgreSql ni pgAdmin. Yo use Docker para crear estos servicios dentro de un contenedor.
Los configuré y pude conectarme a la base de datos sin problemas.
Acá los recursos por si alguien gusta hacerlo así.

docker-compose.yml

Para correr los servicios:

docker-compose up -d

Para ver los contenedores ejecutarse.

docker ps

y obtenemos algo como esto:

CONTAINER ID   IMAGE            COMMAND                  CREATED       STATUS       PORTS                           NAMES
bed2882d776f   postgres:13      "docker-entrypoint.s…"   2 hours ago   Up 2 hours   0.0.0.0:5432->5432/tcp          adhara-store-postgres-1
d3ab36a5d17a   dpage/pgadmin4   "/entrypoint.sh"         2 hours ago   Up 2 hours   443/tcp, 0.0.0.0:5050->80/tcp   adhara-store-pgadmin-1

para este caso el id del contenedor de postgres es bed2882d776f. De este contenedor requiero ver su IP para ello ejecuto el comando

docker inspect bed2882d776f

Va a lanzar un montón de información pero lo que interesa es la IP, esa esta casi hasta el final.

Con esto ya puedo conectar mi base de datos con pgAdmin.

Solo falta ejecutar los scripts sql que se ven en clase y realizar un select a alguna de las tablas para comprobar los datos. En mi caso yo cambie los datos.

Modifique mi archivo applcation-dev.properties y mi applcation-prod.properties

Finalmente ejecute le aplicación y sin problema.

2020-09-19 18:13:59.419 WARN 11872 — [ task-1] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000342: Could not obtain connection to query metadata : FATAL: la autentificaci�n password fall� para el usuario �postgres� (pgjdbc: autodetected server-encoding to be ISO-8859-1, if the message is not readable, please check database logs and/or host, port, dbname, user, password, pg_hba.conf)

me da error de password

Lamentablemente el curso Postgre es REMALO!!!

Aqui un pequeño resumen de postgresql

Hola compañeros, si a alguien le sirve la estructura de la base de datos para Mysql puede consultarlo en este enlace
Realicé algunos cambios referente a como se haría en Postgress

/* Para los que quieren usar mysql aqui les dejo la bd con datos y relaciones*/


– Host: localhost
– Versión del servidor: 5.7.24 - MySQL Community Server (GPL)
– SO del servidor: Win64
– HeidiSQL Versión: 11.0.0.5919


/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT /;
/
!40101 SET NAMES utf8 /;
/
!50503 SET NAMES utf8mb4 /;
/
!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 /;
/
!40101 SET @[email protected]@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO’ */;

– Volcando estructura de base de datos para platzi-market
CREATE DATABASE IF NOT EXISTS platzi-market /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_spanish_ci */;
USE platzi-market;

– Volcando estructura para tabla platzi-market.categorias
CREATE TABLE IF NOT EXISTS categorias (
id_categoria int(11) NOT NULL AUTO_INCREMENT,
descripcion varchar(45) NOT NULL DEFAULT ‘0’,
estado int(11) NOT NULL DEFAULT ‘0’,
PRIMARY KEY (id_categoria),
KEY id_categoria (id_categoria)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

– Volcando datos para la tabla platzi-market.categorias: ~8 rows (aproximadamente)
DELETE FROM categorias;
/*!40000 ALTER TABLE categorias DISABLE KEYS /;
INSERT INTO categorias (id_categoria, descripcion, estado) VALUES
(1, ‘Frutas y verduras’, 1),
(2, ‘Pastelería’, 1),
(3, ‘Carnes y pescados’, 1),
(4, ‘Frutas y verduras’, 1),
(5, ‘Bebidas’, 1),
(6, ‘Licores’, 1),
(7, ‘Cuidado personal’, 1),
(8, ‘Despensa’, 1);
/
!40000 ALTER TABLE categorias ENABLE KEYS */;

– Volcando estructura para tabla platzi-market.clientes
CREATE TABLE IF NOT EXISTS clientes (
id varchar(20) NOT NULL,
nombre varchar(40) DEFAULT NULL,
apellidos varchar(100) DEFAULT NULL,
celular decimal(10,0) DEFAULT ‘0’,
direccion varchar(80) DEFAULT ‘0’,
correo_electronico varchar(70) DEFAULT ‘0’,
PRIMARY KEY (id),
KEY id (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

– Volcando datos para la tabla platzi-market.clientes: ~3 rows (aproximadamente)
DELETE FROM clientes;
/*!40000 ALTER TABLE clientes DISABLE KEYS /;
INSERT INTO clientes (id, nombre, apellidos, celular, direccion, correo_electronico) VALUES
(‘2552243’, ‘Galileo’, ‘Galilei’, 3462257293, ‘Cl 1 # 11 - 11’, ‘[email protected]’),
(‘4546221’, ‘Johannes’, ‘Kepler’, 3104583224, ‘Cl 3 # 33 - 33’, ‘[email protected]’),
(‘983824’, ‘Nicolás’, ‘Copernico’, 3019392466, ‘Cl 2 # 22 - 22’, ‘[email protected]’);
/
!40000 ALTER TABLE clientes ENABLE KEYS */;

– Volcando estructura para tabla platzi-market.compras
CREATE TABLE IF NOT EXISTS compras (
id_compra int(11) NOT NULL,
id_cliente varchar(20) NOT NULL DEFAULT ‘’,
fecha datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
medio_pago char(1) DEFAULT ‘’,
comentario varchar(300) DEFAULT ‘’,
estado char(1) DEFAULT ‘’,
PRIMARY KEY (id_compra),
KEY id_compra (id_compra),
KEY id_cliente (id_cliente),
CONSTRAINT FK_compras_clientes FOREIGN KEY (id_cliente) REFERENCES clientes (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

– Volcando datos para la tabla platzi-market.compras: ~0 rows (aproximadamente)
DELETE FROM compras;
/*!40000 ALTER TABLE compras DISABLE KEYS /;
INSERT INTO compras (id_compra, id_cliente, fecha, medio_pago, comentario, estado) VALUES
(1, ‘4546221’, ‘1992-10-08 17:30:00’, ‘E’, ‘’, ‘P’);
/
!40000 ALTER TABLE compras ENABLE KEYS */;

– Volcando estructura para tabla platzi-market.compras_productos
CREATE TABLE IF NOT EXISTS compras_productos (
id_compra int(11) NOT NULL,
id_producto int(11) NOT NULL,
cantidad int(11) DEFAULT NULL,
total decimal(16,2) DEFAULT NULL,
estado tinyint(4) DEFAULT NULL,
KEY id_compra (id_compra),
KEY id_producto (id_producto),
CONSTRAINT id_comprafk FOREIGN KEY (id_compra) REFERENCES compras (id_compra),
CONSTRAINT id_productofk FOREIGN KEY (id_producto) REFERENCES productos (id_producto)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

– Volcando datos para la tabla platzi-market.compras_productos: ~0 rows (aproximadamente)
DELETE FROM compras_productos;
/*!40000 ALTER TABLE compras_productos DISABLE KEYS /;
INSERT INTO compras_productos (id_compra, id_producto, cantidad, total, estado) VALUES
(1, 1, 10, 3000.00, 1),
(1, 36, 1, 40000.00, 1),
(1, 27, 1, 9000.00, 1),
(1, 49, 2, 16400.00, 1),
(1, 24, 1, 4000.00, 1);
/
!40000 ALTER TABLE compras_productos ENABLE KEYS */;

– Volcando estructura para tabla platzi-market.productos
CREATE TABLE IF NOT EXISTS productos (
id_producto int(11) NOT NULL AUTO_INCREMENT,
nombre varchar(50) DEFAULT ‘0’,
id_categoria int(11) NOT NULL DEFAULT ‘0’,
codigo_barras varchar(50) DEFAULT ‘0’,
precio_venta decimal(16,2) DEFAULT ‘0.00’,
cantidad_stock int(11) NOT NULL DEFAULT ‘0’,
estado tinyint(4) DEFAULT ‘0’,
PRIMARY KEY (id_producto),
KEY id_producto (id_producto),
KEY id_categoria (id_categoria),
CONSTRAINT FK_productos_categorias FOREIGN KEY (id_categoria) REFERENCES categorias (id_categoria)
) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=latin1;

– Volcando datos para la tabla platzi-market.productos: ~50 rows (aproximadamente)
DELETE FROM productos;
/*!40000 ALTER TABLE productos DISABLE KEYS /;
INSERT INTO productos (id_producto, nombre, id_categoria, codigo_barras, precio_venta, cantidad_stock, estado) VALUES
(1, ‘Guayaba Feijoa’, 1, ‘7029 A42 23’, 300.00, 500, 1),
(2, ‘Mango’, 1, ‘0316 R56 01’, 2100.00, 250, 1),
(3, ‘Manzana’, 1, ‘7923 T23 19’, 700.00, 130, 1),
(4, ‘Aguacate’, 1, ‘9322 Q33 02’, 2500.00, 98, 1),
(5, ‘Lechuga’, 1, ‘9742 S22 21’, 4000.00, 86, 1),
(6, ‘Tomate’, 1, ‘0483 R00 97’, 290.00, 430, 1),
(7, ‘Pera’, 1, ‘9999 X10 01’, 750.00, 210, 1),
(8, ‘Apio’, 1, ‘3390 F29 45’, 150.00, 115, 1),
(9, ‘Papaya’, 1, ‘5291 J34 32’, 4500.00, 73, 1),
(10, ‘Limón’, 1, ‘7886 N18 32’, 350.00, 425, 1),
(11, ‘Brownie’, 2, ‘6683 H15 20’, 2500.00, 80, 1),
(12, ‘Pan tajado’, 2, ‘5745 F05 47’, 4500.00, 120, 1),
(13, ‘Torta’, 2, ‘3831 D97 99’, 10000.00, 35, 1),
(14, ‘Tortilla’, 2, ‘4335 Z33 84’, 6400.00, 87, 1),
(15, ‘Tostadas’, 2, ‘6584 M19 25’, 4000.00, 45, 1),
(16, ‘Chocorramo’, 2, ‘4487 S00 97’, 2000.00, 105, 1),
(17, ‘Salmón’, 3, ‘4546 A00 01’, 28000.00, 55, 1),
(18, ‘Punta de anca’, 3, ‘3678 E57 22’, 12000.00, 32, 1),
(19, ‘Posta’, 3, ‘8893 O01 03’, 7800.00, 40, 1),
(20, ‘Costilla de cerdo’, 3, ‘4534 Q12 88’, 8600.00, 70, 1),
(21, ‘Tilapia’, 3, ‘5684 R53 02’, 17000.00, 60, 1),
(22, ‘Merluza’, 3, ‘3523 R04 00’, 23000.00, 45, 1),
(23, ‘Leche de vaca’, 4, ‘2323 T56 33’, 2500.00, 500, 1),
(24, ‘Queso’, 4, ‘7786 K19 56’, 4000.00, 300, 1),
(25, ‘Huevos de gallina feliz’, 4, ‘3478 M74 01’, 400.00, 1000, 1),
(26, ‘Clara de huevo’, 4, ‘7932 R31 46’, 3200.00, 200, 1),
(27, ‘Suero costeño’, 4, ‘5463 W23 33’, 9000.00, 110, 1),
(28, ‘Agua’, 5, ‘8965 I32 11’, 2000.00, 600, 1),
(29, ‘Jugo de naranja’, 5, ‘7445 T87 44’, 7400.00, 200, 1),
(30, ‘Gaseosa Colombiana’, 5, ‘3434 R34 63’, 3100.00, 175, 1),
(31, ‘Jugo de Lulo’, 5, ‘9753 W33 19’, 8250.00, 630, 1),
(32, ‘Tea’, 5, ‘9836 F35 69’, 1900.00, 450, 1),
(33, ‘Cerveza’, 6, ‘3432 G67 21’, 2100.00, 800, 1),
(34, ‘Tequila’, 6, ‘9529 E45 98’, 65000.00, 764, 1),
(35, ‘Ron’, 6, ‘1947 R07 53’, 55000.00, 240, 1),
(36, ‘Aguardiente Antioqueño’, 6, ‘3160 A54 94’, 40000.00, 480, 1),
(37, ‘Vino’, 6, ‘7891 W46 95’, 82000.00, 560, 1),
(38, ‘Crema dental’, 7, ‘6310 C99 73’, 7500.00, 200, 1),
(39, ‘Jabón de manos’, 7, ‘9371 J14 75’, 4900.00, 90, 1),
(40, ‘Enjuague bucal’, 7, ‘1942 T68 01’, 12000.00, 105, 1),
(41, ‘Shampoo’, 7, ‘6789 W01 23’, 9300.00, 200, 1),
(42, ‘Desodorante’, 7, ‘7333 S21 36’, 6900.00, 85, 1),
(43, ‘Arroz’, 8, ‘4676 I83 00’, 3500.00, 600, 1),
(44, ‘Lentejas’, 8, ‘7333 S21 36’, 3000.00, 560, 1),
(45, ‘Harina’, 8, ‘7333 S21 36’, 1800.00, 300, 1),
(46, ‘Sal’, 8, ‘7333 S21 36’, 1400.00, 500, 1),
(47, ‘Aceite’, 8, ‘7333 S21 36’, 6500.00, 135, 1),
(48, ‘Cereal’, 8, ‘4673 K53 98’, 7000.00, 75, 1),
(49, ‘Frijol’, 8, ‘2745 F40 45’, 8200.00, 270, 1),
(50, ‘Café’, 8, ‘6351 R33 92’, 7200.00, 400, 1);
/
!40000 ALTER TABLE productos ENABLE KEYS */;

/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, ‘’) /;
/
!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) /;
/
!40101 SET [email protected]_CHARACTER_SET_CLIENT */;

Bien explicado…

Excelente todo el contenido hasta el momento, muy buen profesor Alejandro Ramirez

me Ayudan por favor.

Ayuda me quedé en este error:
Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

estamos utilizando Hibernate ??

Tenía un problema con la clave del usuario postgres. Este link me ayudó: https://www.postgresqltutorial.com/postgresql-reset-password/

a mi me funciono asi :
spring.datasource.url=jdbc:mysql://localhost:3306/platzi-market
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update

ya que la nueva actualizacion de driver en MSQL ES : com.mysql.cj.jdbc.Driver

esta es la consulta par MYSLQ de phpmyadmi:


– Table “CATEGORIAS”


CREATE TABLE CATEGORIAS (
id_categoria INT NOT NULL AUTO_INCREMENT,
descripcion VARCHAR(45) NOT NULL,
estado BOOLEAN NOT NULL,
PRIMARY KEY (id_categoria)
);


– Table “PRODUCTOS”


CREATE TABLE PRODUCTOS (
id_producto INT NOT NULL AUTO_INCREMENT,
nombre VARCHAR(45) NULL,
id_categoria INT NOT NULL,
codigo_barras VARCHAR(150) NULL,
precio_venta DECIMAL(16,2) NULL,
cantidad_stock INT NOT NULL,
estado BOOLEAN NULL,
PRIMARY KEY (id_producto),
CONSTRAINT fk_PRODUCTOS_CATEGORIAS
FOREIGN KEY (id_categoria)
REFERENCES CATEGORIAS (id_categoria)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);


– Table “CLIENTES”


CREATE TABLE CLIENTES (
id VARCHAR(20) NOT NULL,
nombre VARCHAR(40) NULL,
apellidos VARCHAR(100) NULL,
celular NUMERIC NULL,
direccion VARCHAR(80) NULL,
correo_electronico VARCHAR(70) NULL,
PRIMARY KEY (id)
);


– Table “COMPRAS”


CREATE TABLE COMPRAS (
id_compra INT NOT NULL AUTO_INCREMENT,
id_cliente VARCHAR(20) NOT NULL,
fecha TIMESTAMP NULL,
medio_pago CHAR(1) NULL,
comentario VARCHAR(300) NULL,
estado CHAR(1) NULL,
PRIMARY KEY (id_compra),
CONSTRAINT fk_COMPRAS_CLIENTES1
FOREIGN KEY (id_cliente)
REFERENCES CLIENTES (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);


– Table “COMPRAS_PRODUCTOS”


CREATE TABLE COMPRAS_PRODUCTOS (
id_compra INT NOT NULL,
id_producto INT NOT NULL,
cantidad INT NULL,
total DECIMAL(16,2) NULL,
estado BOOLEAN NULL,
PRIMARY KEY (id_compra, id_producto),
CONSTRAINT fk_COMPRAS_PRODUCTOS_PRODUCTOS1
FOREIGN KEY (id_producto)
REFERENCES PRODUCTOS (id_producto)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_COMPRAS_PRODUCTOS_COMPRAS1
FOREIGN KEY (id_compra)
REFERENCES COMPRAS (id_compra)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);

chicos me sale este error tengo java 17 y la ve

he puesto el dev.propertiers de esta forma no he logrado hacer que funcione
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:postgresql://localhost:5432/platzi-market
spring.datasource.username=postgres
spring.datasource.password=Root2014
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
spring.jpa.show-sql=true


APPLICATION FAILED TO START


Description:
Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use ‘–warning-mode all’ to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.6.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 12s
3 actionable tasks: 3 executed
9:40:59 p. m.: Execution finished ‘:PlatziMarketApplication.main()’.

Para quienes usan Docker para levantar la base de datos este sería el código:

recuerden levantarlo con docker-compose up -d postgres y
docker-compose up -d gadmin
el puerto del pgadmin para verlo es el 5050

version: '3.3'

services:
  postgres:
    image: postgres:13
    environment:
      - POSTGRES_DB=platzi-market
      - POSTGRES_USER=gilbert
      - POSTGRES_PASSWORD=0208
    ports:
      - 5432:5432
    volumes:
      - ./postgres_data:/var/lib/postgresql/data

  pgadmin:
    image: dpage/pgadmin4
    environment:
      - [email protected]
      - PGADMIN_DEFAULT_PASSWORD=0208
    ports:
      - 5050:80

Por si aún tienen problemas con MySql la implementación no soportaba sin la versión y un error adicional con hibernate.

implementation 'mysql:mysql-connector-java:8.0.32’
implementation ‘com.h2database:h2’

spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update

muy buen curso!

Recuerden que si requieren revisar su configuración pueden hacerlo en el pgadmin de manera sencilla :

No sirvió PostgreSQL apuntaba a un usuario que no existía en la bd, hasta cre un nuevo user con todos los permisos y queria seguir accediendo al mismo usuario.

Por si alguien quiere los queries en inglés y de esta manera manera también utilizarlos en nuestros Entities.
DATA.SQL:

-- CATEGORIES
INSERT INTO categories VALUES (1, 'Frutas y verduras', true);
INSERT INTO categories VALUES (2, 'Pastelería', true);
INSERT INTO categories VALUES (3, 'Carnes y pescados', true);
INSERT INTO categories VALUES (4, 'Lácteos y huevos', true);
INSERT INTO categories VALUES (5, 'Bebidas', true);
INSERT INTO categories VALUES (6, 'Licores', true);
INSERT INTO categories VALUES (7, 'Cuidado personal', true);
INSERT INTO categories VALUES (8, 'Despensa', true);

-- PRODUCTS
INSERT INTO products VALUES (1, 1, 'Guayaba Feijoa', '7029 A42 23', 300, 500, true);
INSERT INTO products VALUES (2, 1, 'Mango', '0316 R56 01', 2100, 250, true);
INSERT INTO products VALUES (3, 1, 'Manzana', '7923 T23 19', 700, 130, true);
INSERT INTO products VALUES (4, 1, 'Aguacate', '9322 Q33 02', 2500, 98, true);
INSERT INTO products VALUES (5, 1, 'Lechuga', '9742 S22 21', 4000, 86, true);
INSERT INTO products VALUES (6, 1, 'Tomate', '0483 R00 97', 290, 430, true);
INSERT INTO products VALUES (7, 1, 'Pera', '9999 X10 01', 750, 210, true);
INSERT INTO products VALUES (8, 1, 'Apio', '3390 F29 45', 150, 115, true);
INSERT INTO products VALUES (9, 1, 'Papaya', '5291 J34 32', 4500, 73, true);
INSERT INTO products VALUES (10, 1, 'Limón', '7886 N18 32', 350, 425, true);
INSERT INTO products VALUES (11, 2, 'Brownie', '6683 H15 20', 2500, 80, true);
INSERT INTO products VALUES (12, 2, 'Pan tajado', '5745 F05 47', 4500, 120, true);
INSERT INTO products VALUES (13, 2, 'Torta', '3831 D97 99', 10000, 35, true);
INSERT INTO products VALUES (14, 2, 'Tortilla', '4335 Z33 84', 6400, 87, true);
INSERT INTO products VALUES (15, 2, 'Tostadas', '6584 M19 25', 4000, 45, true);
INSERT INTO products VALUES (16, 2, 'Chocorramo', '4487 S00 97', 2000, 105, true);
INSERT INTO products VALUES (17, 3, 'Salmón', '4546 A00 01', 28000, 55, true);
INSERT INTO products VALUES (18, 3, 'Punta de anca', '3678 E57 22', 12000, 32, true);
INSERT INTO products VALUES (19, 3, 'Posta', '8893 O01 03', 7800, 40, true);
INSERT INTO products VALUES (20, 3, 'Costilla de cerdo', '4534 Q12 88', 8600, 70, true);
INSERT INTO products VALUES (21, 3, 'Tilapia', '5684 R53 02', 17000, 60, true);
INSERT INTO products VALUES (22, 3, 'Merluza', '3523 R04 00', 23000, 45, true);
INSERT INTO products VALUES (23, 4, 'Leche de vaca', '2323 T56 33', 2500, 500, true);
INSERT INTO products VALUES (24, 4, 'Queso', '7786 K19 56', 4000, 300, true);
INSERT INTO products VALUES (25, 4, 'Huevos de gallina feliz', '3478 M74 01', 400, 1000, true);
INSERT INTO products VALUES (26, 4, 'Clara de huevo', '7932 R31 46', 3200, 200, true);
INSERT INTO products VALUES (27, 4, 'Suero costeño', '5463 W23 33', 9000, 110, true);
INSERT INTO products VALUES (28, 5, 'Agua', '8965 I32 11', 2000, 600, true);
INSERT INTO products VALUES (29, 5, 'Jugo de naranja', '7445 T87 44', 7400, 200, true);
INSERT INTO products VALUES (30, 5, 'Gaseosa Colombiana', '3434 R34 63', 3100, 175, true);
INSERT INTO products VALUES (31, 5, 'Jugo de Lulo', '9753 W33 19', 8250, 630, true);
INSERT INTO products VALUES (32, 5, 'Tea', '9836 F35 69', 1900, 450, true);
INSERT INTO products VALUES (33, 6, 'Cerveza', '3432 G67 21', 2100, 800, true);
INSERT INTO products VALUES (34, 6, 'Tequila', '9529 E45 98', 65000, 764, true);
INSERT INTO products VALUES (35, 6, 'Ron', '1947 R07 53', 55000, 240, true);
INSERT INTO products VALUES (36, 6, 'Aguardiente Antioqueño', '3160 A54 94', 40000, 480, true);
INSERT INTO products VALUES (37, 6, 'Vino', '7891 W46 95', 82000, 560, true);
INSERT INTO products VALUES (38, 7, 'Crema dental', '6310 C99 73', 7500, 200, true);
INSERT INTO products VALUES (39, 7, 'Jabón de manos', '9371 J14 75', 4900, 90, true);
INSERT INTO products VALUES (40, 7, 'Enjuague bucal', '1942 T68 01', 12000, 105, true);
INSERT INTO products VALUES (41, 7, 'Shampoo', '6789 W01 23', 9300, 200, true);
INSERT INTO products VALUES (42, 7, 'Desodorante', '7333 S21 36', 6900, 85, true);
INSERT INTO products VALUES (43, 8, 'Arroz', '4676 I83 00', 3500, 600, true);
INSERT INTO products VALUES (44, 8, 'Lentejas', '7333 S21 36', 3000, 560, true);
INSERT INTO products VALUES (45, 8, 'Harina', '7333 S21 36', 1800, 300, true);
INSERT INTO products VALUES (46, 8, 'Sal', '7333 S21 36', 1400, 500, true);
INSERT INTO products VALUES (47, 8, 'Aceite', '7333 S21 36', 6500, 135, true);
INSERT INTO products VALUES (48, 8, 'Cereal', '4673 K53 98', 7000, 75, true);
INSERT INTO products VALUES (49, 8, 'Frijol', '2745 F40 45', 8200, 270, true);
INSERT INTO products VALUES (50, 8, 'Café', '6351 R33 92', 7200, 400, true);

-- CUSTOMERS
INSERT INTO customers VALUES ('4546221', 'Johannes', 'Kepler', 3104583224, 'Cl 3 # 33 - 33', '[email protected]');
INSERT INTO customers VALUES ('2552243', 'Galileo', 'Galilei', 3462257293, 'Cl 1 # 11 - 11', '[email protected]');
INSERT INTO customers VALUES ('983824', 'Nicolás', 'Copernico', 3019392466, 'Cl 2 # 22 - 22', '[email protected]');

-- PURCHASES
INSERT INTO purchases VALUES (1, '4546221', TO_TIMESTAMP('10/08/1992 17:30:00','DD/MM/YYYY HH24:MI:SS'), 'E', '', 'P');

-- PRODUCT_PURCHASES
INSERT INTO product_purchases VALUES (1, 1, 10, 3000, true);
INSERT INTO product_purchases VALUES (36, 1, 1, 40000, true);
INSERT INTO product_purchases VALUES (27, 1, 1, 9000, true);
INSERT INTO product_purchases VALUES (49, 1, 2, 16400, true);
INSERT INTO product_purchases VALUES (24, 1, 1, 4000, true);

-- SET_VAlUES_OF_INDEX
SELECT setval('public.products_id_product_seq', 50, true);
SELECT setval('public.categories_id_category_seq', 8, true);
SELECT setval('public.purchases_id_purchase_seq', 1, true);

SCHEMA.SQL:

<-- -----------------------------------------------------
-- Table "CATEGORIES"
-- -----------------------------------------------------
CREATE TABLE  CATEGORIES (
  "id_category" SERIAL NOT NULL,
  "description" VARCHAR(45) NOT NULL,
  "state" BOOLEAN NOT NULL,
  PRIMARY KEY ("id_category"));


-- -----------------------------------------------------
-- Table "PRODUCTS"
-- -----------------------------------------------------
CREATE TABLE  PRODUCTS (
  "id_product" SERIAL NOT NULL,
  "id_category" INT NOT NULL,
  "name" VARCHAR(45) NULL,
  "barcode" VARCHAR(150) NULL,
  "price" DECIMAL(16,2) NULL,
  "stock_quantity" INT NOT NULL,
  "state" BOOLEAN NULL,
  PRIMARY KEY ("id_product"),
  CONSTRAINT "fk_PRODUCTS_CATEGORIES"
    FOREIGN KEY ("id_category")
    REFERENCES CATEGORIES ("id_category")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);


-- -----------------------------------------------------
-- Table "CUSTOMERS"
-- -----------------------------------------------------
CREATE TABLE  CUSTOMERS (
  "id_customer" VARCHAR(20) NOT NULL,
  "name" VARCHAR(40) NULL,
  "lastname" VARCHAR(100) NULL,
  "number_phone" NUMERIC NULL,
  "address" VARCHAR(80) NULL,
  "email" VARCHAR(70) NULL,
  PRIMARY KEY ("id_customer"));


-- -----------------------------------------------------
-- Table "PURCHASES"
-- -----------------------------------------------------
CREATE TABLE  PURCHASES (
  "id_purchase" SERIAL NOT NULL,
  "id_customer" VARCHAR(20) NOT NULL,
  "date" TIMESTAMP NULL,
  "half_pay" CHAR(1) NULL,
  "commentary" VARCHAR(300) NULL,
  "state" CHAR(1) NULL,
  PRIMARY KEY ("id_purchase"),
  CONSTRAINT "fk_PURCHASES_CUSTOMERS"
    FOREIGN KEY ("id_customer")
    REFERENCES CUSTOMERS ("id_customer")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);


-- -----------------------------------------------------
-- Table "PRODUCT_PURCHASES"
-- -----------------------------------------------------
CREATE TABLE  PRODUCT_PURCHASES (
  "id_product" INT NOT NULL,
  "id_purchase" INT NOT NULL,
  "quantity" INT NULL,
  "total" DECIMAL(16,2) NULL,
  "state" BOOLEAN NULL,
  PRIMARY KEY ("id_product","id_purchase"),
  CONSTRAINT "fk_PRODUCT_PURCHASES_PRODUCTS"
    FOREIGN KEY ("id_product")
    REFERENCES PRODUCTS ("id_product")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT "fk_PRODUCT_PURCHASES_PURCHASES"
    FOREIGN KEY ("id_purchase")
    REFERENCES PURCHASES ("id_purchase")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);
> 

en oralce:
runtimeOnly ‘com.oracle.database.jdbc:ojdbc8’

spring.datasource.url=jdbc:oracle:thin:@//localhost:1523/XE
spring.datasource.username="nombre de usuario/schema"
spring.datasource.password=“contraseña”

Para los vagos que no quieren escribir
spring.datasource.url=jdbc:postgresql://localhost:5432/platzi-market
spring.datasource.username=postgres
spring.datasource.password=18199218

data sql

-- CATEGORIAS
INSERT INTO categorias VALUES (1, 'Frutas y verduras', true);
INSERT INTO categorias VALUES (2, 'Pastelería', true);
INSERT INTO categorias VALUES (3, 'Carnes y pescados', true);
INSERT INTO categorias VALUES (4, 'Lácteos y huevos', true);
INSERT INTO categorias VALUES (5, 'Bebidas', true);
INSERT INTO categorias VALUES (6, 'Licores', true);
INSERT INTO categorias VALUES (7, 'Cuidado personal', true);
INSERT INTO categorias VALUES (8, 'Despensa', true);

-- PRODUCTOS
INSERT INTO productos VALUES (1, 'Guayaba Feijoa', 1, '7029 A42 23', 300, 500, true);
INSERT INTO productos VALUES (2, 'Mango', 1, '0316 R56 01', 2100, 250, true);
INSERT INTO productos VALUES (3, 'Manzana', 1, '7923 T23 19', 700, 130, true);
INSERT INTO productos VALUES (4, 'Aguacate', 1, '9322 Q33 02', 2500, 98, true);
INSERT INTO productos VALUES (5, 'Lechuga', 1, '9742 S22 21', 4000, 86, true);
INSERT INTO productos VALUES (6, 'Tomate', 1, '0483 R00 97', 290, 430, true);
INSERT INTO productos VALUES (7, 'Pera', 1, '9999 X10 01', 750, 210, true);
INSERT INTO productos VALUES (8, 'Apio', 1, '3390 F29 45', 150, 115, true);
INSERT INTO productos VALUES (9, 'Papaya', 1, '5291 J34 32', 4500, 73, true);
INSERT INTO productos VALUES (10, 'Limón', 1, '7886 N18 32', 350, 425, true);
INSERT INTO productos VALUES (11, 'Brownie', 2, '6683 H15 20', 2500, 80, true);
INSERT INTO productos VALUES (12, 'Pan tajado', 2, '5745 F05 47', 4500, 120, true);
INSERT INTO productos VALUES (13, 'Torta', 2, '3831 D97 99', 10000, 35, true);
INSERT INTO productos VALUES (14, 'Tortilla', 2, '4335 Z33 84', 6400, 87, true);
INSERT INTO productos VALUES (15, 'Tostadas', 2, '6584 M19 25', 4000, 45, true);
INSERT INTO productos VALUES (16, 'Chocorramo', 2, '4487 S00 97', 2000, 105, true);
INSERT INTO productos VALUES (17, 'Salmón', 3, '4546 A00 01', 28000, 55, true);
INSERT INTO productos VALUES (18, 'Punta de anca', 3, '3678 E57 22', 12000, 32, true);
INSERT INTO productos VALUES (19, 'Posta', 3, '8893 O01 03', 7800, 40, true);
INSERT INTO productos VALUES (20, 'Costilla de cerdo', 3, '4534 Q12 88', 8600, 70, true);
INSERT INTO productos VALUES (21, 'Tilapia', 3, '5684 R53 02', 17000, 60, true);
INSERT INTO productos VALUES (22, 'Merluza', 3, '3523 R04 00', 23000, 45, true);
INSERT INTO productos VALUES (23, 'Leche de vaca', 4, '2323 T56 33', 2500, 500, true);
INSERT INTO productos VALUES (24, 'Queso', 4, '7786 K19 56', 4000, 300, true);
INSERT INTO productos VALUES (25, 'Huevos de gallina feliz', 4, '3478 M74 01', 400, 1000, true);
INSERT INTO productos VALUES (26, 'Clara de huevo', 4, '7932 R31 46', 3200, 200, true);
INSERT INTO productos VALUES (27, 'Suero costeño', 4, '5463 W23 33', 9000, 110, true);
INSERT INTO productos VALUES (28, 'Agua', 5, '8965 I32 11', 2000, 600, true);
INSERT INTO productos VALUES (29, 'Jugo de naranja', 5, '7445 T87 44', 7400, 200, true);
INSERT INTO productos VALUES (30, 'Gaseosa Colombiana', 5, '3434 R34 63', 3100, 175, true);
INSERT INTO productos VALUES (31, 'Jugo de Lulo', 5, '9753 W33 19', 8250, 630, true);
INSERT INTO productos VALUES (32, 'Tea', 5, '9836 F35 69', 1900, 450, true);
INSERT INTO productos VALUES (33, 'Cerveza', 6, '3432 G67 21', 2100, 800, true);
INSERT INTO productos VALUES (34, 'Tequila', 6, '9529 E45 98', 65000, 764, true);
INSERT INTO productos VALUES (35, 'Ron', 6, '1947 R07 53', 55000, 240, true);
INSERT INTO productos VALUES (36, 'Aguardiente Antioqueño', 6, '3160 A54 94', 40000, 480, true);
INSERT INTO productos VALUES (37, 'Vino', 6, '7891 W46 95', 82000, 560, true);
INSERT INTO productos VALUES (38, 'Crema dental', 7, '6310 C99 73', 7500, 200, true);
INSERT INTO productos VALUES (39, 'Jabón de manos', 7, '9371 J14 75', 4900, 90, true);
INSERT INTO productos VALUES (40, 'Enjuague bucal', 7, '1942 T68 01', 12000, 105, true);
INSERT INTO productos VALUES (41, 'Shampoo', 7, '6789 W01 23', 9300, 200, true);
INSERT INTO productos VALUES (42, 'Desodorante', 7, '7333 S21 36', 6900, 85, true);
INSERT INTO productos VALUES (43, 'Arroz', 8, '4676 I83 00', 3500, 600, true);
INSERT INTO productos VALUES (44, 'Lentejas', 8, '7333 S21 36', 3000, 560, true);
INSERT INTO productos VALUES (45, 'Harina', 8, '7333 S21 36', 1800, 300, true);
INSERT INTO productos VALUES (46, 'Sal', 8, '7333 S21 36', 1400, 500, true);
INSERT INTO productos VALUES (47, 'Aceite', 8, '7333 S21 36', 6500, 135, true);
INSERT INTO productos VALUES (48, 'Cereal', 8, '4673 K53 98', 7000, 75, true);
INSERT INTO productos VALUES (49, 'Frijol', 8, '2745 F40 45', 8200, 270, true);
INSERT INTO productos VALUES (50, 'Café', 8, '6351 R33 92', 7200, 400, true);

-- CLIENTES
INSERT INTO clientes VALUES ('4546221', 'Johannes', 'Kepler', 3104583224, 'Cl 3 # 33 - 33', '[email protected]');
INSERT INTO clientes VALUES ('2552243', 'Galileo', 'Galilei', 3462257293, 'Cl 1 # 11 - 11', '[email protected]');
INSERT INTO clientes VALUES ('983824', 'Nicolás', 'Copernico', 3019392466, 'Cl 2 # 22 - 22', '[email protected]');

-- COMPRA
INSERT INTO compras VALUES (1, '4546221', TO_TIMESTAMP('10/08/1992 17:30:00','DD/MM/YYYY HH24:MI:SS'), 'E', '', 'P');
INSERT INTO compras_productos VALUES (1, 1, 10, 3000, true);
INSERT INTO compras_productos VALUES (1, 36, 1, 40000, true);
INSERT INTO compras_productos VALUES (1, 27, 1, 9000, true);
INSERT INTO compras_productos VALUES (1, 49, 2, 16400, true);
INSERT INTO compras_productos VALUES (1, 24, 1, 4000, true);

-- SE REINICIAN LAS SECUENCIAS SEGÚN LOS DATOS INICIALES
SELECT setval('public.productos_id_producto_seq', 50, true);
SELECT setval('public.categorias_id_categoria_seq', 8, true);
SELECT setval('public.compras_id_compra_seq', 1, true);

schema sql

-- -----------------------------------------------------
-- Table "CATEGORIAS"
-- -----------------------------------------------------
CREATE TABLE  CATEGORIAS (
  "id_categoria" SERIAL NOT NULL,
  "descripcion" VARCHAR(45) NOT NULL,
  "estado" BOOLEAN NOT NULL,
  PRIMARY KEY ("id_categoria"));


-- -----------------------------------------------------
-- Table "PRODUCTOS"
-- -----------------------------------------------------
CREATE TABLE  PRODUCTOS (
  "id_producto" SERIAL NOT NULL,
  "nombre" VARCHAR(45) NULL,
  "id_categoria" INT NOT NULL,
  "codigo_barras" VARCHAR(150) NULL,
  "precio_venta" DECIMAL(16,2) NULL,
  "cantidad_stock" INT NOT NULL,
  "estado" BOOLEAN NULL,
  PRIMARY KEY ("id_producto"),
  CONSTRAINT "fk_PRODUCTOS_CATEGORIAS"
    FOREIGN KEY ("id_categoria")
    REFERENCES CATEGORIAS ("id_categoria")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);


-- -----------------------------------------------------
-- Table "CLIENTES"
-- -----------------------------------------------------
CREATE TABLE  CLIENTES (
  "id" VARCHAR(20) NOT NULL,
  "nombre" VARCHAR(40) NULL,
  "apellidos" VARCHAR(100) NULL,
  "celular" NUMERIC NULL,
  "direccion" VARCHAR(80) NULL,
  "correo_electronico" VARCHAR(70) NULL,
  PRIMARY KEY ("id"));


-- -----------------------------------------------------
-- Table "COMPRAS"
-- -----------------------------------------------------
CREATE TABLE  COMPRAS (
  "id_compra" SERIAL NOT NULL,
  "id_cliente" VARCHAR(20) NOT NULL,
  "fecha" TIMESTAMP NULL,
  "medio_pago" CHAR(1) NULL,
  "comentario" VARCHAR(300) NULL,
  "estado" CHAR(1) NULL,
  PRIMARY KEY ("id_compra"),
  CONSTRAINT "fk_COMPRAS_CLIENTES1"
    FOREIGN KEY ("id_cliente")
    REFERENCES CLIENTES ("id")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);


-- -----------------------------------------------------
-- Table "COMPRAS_PRODUCTOS"
-- -----------------------------------------------------
CREATE TABLE  COMPRAS_PRODUCTOS (
  "id_compra" INT NOT NULL,
  "id_producto" INT NOT NULL,
  "cantidad" INT NULL,
  "total" DECIMAL(16,2) NULL,
  "estado" BOOLEAN NULL,
  PRIMARY KEY ("id_compra", "id_producto"),
  CONSTRAINT "fk_COMPRAS_PRODUCTOS_PRODUCTOS1"
    FOREIGN KEY ("id_producto")
    REFERENCES PRODUCTOS ("id_producto")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT "fk_COMPRAS_PRODUCTOS_COMPRAS1"
    FOREIGN KEY ("id_compra")
    REFERENCES COMPRAS ("id_compra")
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

2020-10-14 20:11:03.164 INFO 10812 — [ Test worker] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug’ enabled.
2020-10-14 20:11:03.180 ERROR 10812 — [ Test worker] o.s.b.d.LoggingFailureAnalysisReporter :


APPLICATION FAILED TO START


Description:

Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

yo tenia activo en postgresql dos servidores: PostgreSQL 13 y PostgreSQL 14. La base de datos la tenía en el servidor postgres14. Tuve que entrar a las propiedades de ese servidor y ver el puerto en el cual corria, en este caso era el 5433. por eso no me encontraba la base de datos

Puede ser que en las versiones recientes de postgres, y de SpringBoot, puede que se requiera definir la siguiente propiedad:

spring.datasource.driver-class-name=org.postgresql.Driver

En lugar de

spring.datasource.driver-class-name=org.postgresql.Driver

Sobre todo cuando el servicio al iniciar falla por errores relacionados al dialecto

SQLServer

runtimeOnly’com.microsoft.sqlserver:mssql-jdbc’

spring.datasource.url=jdbc:sqlserver://localhost;databaseName=market
spring.datasource.username=sa
spring.datasource.password=12345

spring.datasource.url=jdbc:postgresql://localhost/platzi-market?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrival=true
spring.datasource.username=postgres
spring.datasource.password=contraseña

spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

Para conectarse a Oracle DB

spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/XEPDB1
spring.datasource.username="Schema"
spring.datasource.password="password"
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
logging.level.root=INFO

spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect
spring.jpa.hibernate.ddl-auto=update
logging.level.org.hibernate.SQL=debug
spring.sql.init.mode=always
spring.sql.init.platform=oracle

Yo estoy utilizando SQL Server en lugar de PostgreSQL y me arrojaba errores acerca de la configuración del dialecto con hibernate, investigando me topé con que se necesitaba configurar el dialecto “aceptado” por hibernate, lo solucioné con lo siguiente

spring.jpa.database-platform=org.hibernate.dialect.SQLServerDialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=create

Si estan usando Ubuntu WSL. La cadena de conexión debe de ir con IP

spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/market

alguie sabe como puedo solucionar este error?:

Caused by: java.net.ConnectException: Connection refused: connec

alguien sabe como lo puedo solucionar?

buenas pueden actualizar los enlaces a los scripts por favor, porque los links de drive no funcionan, gracias!

Fuaaaaa 🔥🔥🔥
Java siempre ha sido mi lenguaje favorito, pero con esto que estoy aprendiendo mis expectativas se van por los cielos

**SQL Server
**

runtimeOnly 'com.microsoft.sqlserver:mssql-jdbc'

Hola Profe tengo un problema que no he podido detectar y desde que agregue el tema de BD y le doy RUN no me pasa de

com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...

Sabes que puede ser? gracias…

buenas noches, como puedo debuggear y saber donde tengo errores que quizas el run no muestre. se me queda pegado justamente en esta parte del run

com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...

Este error, a que se debe?

org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"
	at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:525) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:146) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:197) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:217) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.Driver.makeConnection(Driver.java:458) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.Driver.connect(Driver.java:260) ~[postgresql-42.2.14.jar:42.2.14]
	at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.5.jar:na]
	at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358) ~[HikariCP-3.4.5.jar:na]
	at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-3.4.5.jar:na]
	at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477) ~[HikariCP-3.4.5.jar:na]
	at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560) ~[HikariCP-3.4.5.jar:na]
	at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.4.5.jar:na]
	at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.4.5.jar:na]
	at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:158) ~[spring-jdbc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:116) ~[spring-jdbc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79) ~[spring-jdbc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:324) ~[spring-jdbc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.boot.jdbc.EmbeddedDatabaseConnection.isEmbedded(EmbeddedDatabaseConnection.java:120) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.HibernateDefaultDdlAutoProvider.getDefaultDdlAuto(HibernateDefaultDdlAutoProvider.java:42) ~[spring-boot-autoconfigure-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration.lambda$getVendorProperties$1(HibernateJpaConfiguration.java:130) ~[spring-boot-autoconfigure-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings.getDdlAuto(HibernateSettings.java:41) ~[spring-boot-autoconfigure-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties.determineDdlAuto(HibernateProperties.java:136) ~[spring-boot-autoconfigure-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties.getAdditionalProperties(HibernateProperties.java:102) ~[spring-boot-autoconfigure-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties.determineHibernateProperties(HibernateProperties.java:94) ~[spring-boot-autoconfigure-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration.getVendorProperties(HibernateJpaConfiguration.java:132) ~[spring-boot-autoconfigure-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.entityManagerFactory(JpaBaseConfiguration.java:133) ~[spring-boot-autoconfigure-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:635) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]
	at com.platzi.market.PlatziMarketApplication.main(PlatziMarketApplication.java:10) ~[main/:na]

hace mucha falta el esquema de la base de datos para poder ver como se relacionan las tablas. a la imaginación no se puede

Si alguien desea usar postgresql y pgadmin con docker compose me apoye en el post de Manuel Eguiluz pero le hice algunas modificaciones

version: '3.1'
services:
  db:
    image: 'postgres'
    environment:
      POSTGRES_USER: 'postgres'
      POSTGRES_PASSWORD: 'postgres'
      POSTGRES_DB: 'db-app-market'
    volumes:
      - db-data:/var/lib/postgresql/data/
    ports:
      - '5432:5432'
    networks:
      - postgres
    restart: unless-stopped

  pgadmin:
    image: dpage/pgadmin4:4.22
    environment:
      PGADMIN_DEFAULT_EMAIL: [email protected]
      PGADMIN_DEFAULT_PASSWORD: admin
      PGADMIN_CONFIG_SERVER_MODE: 'False'
    volumes:
        - pgadmin-data:/var/lib/pgadmin
    ports:
      - '1234:80'
    networks:
      - postgres
    restart: unless-stopped
    depends_on:
      - db

networks:
  postgres:
    driver: bridge

volumes:
  db-data:
  pgadmin-data:

al momento de ligar la base de datos para poderla administrar con pgadmin puede que les arroje que no es posible establecer conexión por eso les recomiendo la siguiente solución que me funciono que encontré en stackoverflow https://stackoverflow.com/a/60668718/9024005

luego en el proyecto en el archivo application-dev.properties usar la siguiente configuración

Database

spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/db-app-market
spring.datasource.username=postgres
spring.datasource.password=postgres

Vengo del curso de JEE avanzado y recién cuando lo estaba terminando vi que los comentarios eran de hace 3 años.
Este profe explica muy claro. Ojalá y siga así todo el curso!

hola compañeros por favor una ayuda esta es mi configuracion

#DataBase
spring.datasource.url=jdbc:postgresql://localhost:5432/platzi-market
spring.datasource.username=postgres
spring.datasource.password=platzi
spring.datasource.driver-class-name=org.postgresql.Driver

y me esta lanzando este error

Caused by: java.lang.IllegalStateException: Cannot load driver class: org.postgresql.Driver

alguien sabe como solucionarlo??