You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
16 Hrs
10 Min
59 Seg

Conectar el proyecto a la base de datos

3/25
Resources

What is the entity-relationship model of the pizzeria?

Our entity-relationship model for the pizzeria project database is composed of four fundamental tables: pizza, pizza_order, order_item and customer. Here we briefly break down each of these tables and their functions:

  • Pizza table:

    • Pizza ID: Unique identifier for each pizza.
    • Name and description: Detailed information of the pizza.
    • Price: Decimal type 5,2 (five digits in total, two after the dot).
    • Boolean attributes: Identification of whether the pizza is vegetarian, vegan or available by using tinyint columns.
  • Table pizza_order:

    • Order ID: Unique identifier of each order.
    • Relationship to customer: Using customer ID as foreign key.
    • Order date: Time stamp of order creation.
    • Total value: Sum of the cost of all pizzas in the order.
    • Delivery method: Stores in one character whether the order is take-out, pick-up or eat-in.
    • Additional notes: Record for customer specific remarks about the order.
  • Customer table:

    • Customer ID: Unique identification of each customer.
    • Customer data: Includes name, address, email and phone number.
  • Table order_item:

    • One-to-one relationship with pizza: Each order item has a link to a specific pizza.
    • One-to-many relationship with pizza_order: An order can have multiple items.
    • Primary keys: Composed by item ID and order ID.
    • Quantity and price: Quantity management and price adjustments according to the number of pizzas ordered.

How to connect the project to the database?

To connect our project to a MySQL database from IntelliJ IDEA, we must edit the application.properties file in the resources directory. Here we must put four essential instructions to establish the connection:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/fixeria?createDatabaseIfNotExist=truespring.datasource.username=rootspring.datasource.password=admin

What parameters are essential in application.properties?

  • spring.datasource.driver-class-name: Specifies the database type.
  • spring.datasource.url: Address and name of the database along with the createDatabaseIfNotExist=true statement for MySQL.
  • spring.datasource.username and password: Database access credentials.

Advanced configuration: How to use Hikari CP and Spring JPA?

What is Hikari CP for?

Hikari CP is an automatic database connection manager, optimizing the number of connections according to the number of users in the application. It provides better performance and is essential for the efficiency and scalability of the system.

How to configure Spring JPA?

To dynamically manage the database schema, we can add and configure Spring JPA:

spring.jpa.hibernate.ddl-auto=updatespring.jpa.show-sql=true
  • spring.jpa.hibernate.ddl-auto:
    • update: Adapts to the schema when synchronizing changes without losing data.
  • spring.jpa.show-sql: Allows to visualize in the console the SQL actions performed by our application.

These configurations allow the database structure to be automatically updated from the entities defined in our project. In addition, enabling show-sql helps us to verify and analyze how our actions affect the database in real time.

How to adapt the new IntelliJ IDEA interface?

Finally, to take advantage of IntelliJ IDEA 's updates to its interface, we can enable the "New UI" in Appearance & Behavior. This will allow us to familiarize ourselves with a more modern and efficient interface. Simply enable the interface, apply the changes and restart IntelliJ IDEA.

Using these options not only enhances the development experience, but also optimizes project management in a database environment. By continuing to learn and explore new tools and configurations, you enhance your ability to create robust and efficient applications. Go ahead and explore more on this exciting learning journey!

Contributions 30

Questions 8

Sort by:

Want to see more contributions, questions and answers from the community?

YAML es un formato práctico para especificar datos de configuración jerárquicos.

  • Recomiendo renombrar el

application.properties —> application.yaml

  • Utilizar la siguiente configuración para PostgreSQL en el archivo de configuración application.yaml
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/pizza
    username: admin
    password: Jaime2030
  jpa:
    hibernate:
      ddl-auto: update
      dialect: org.hibernate.dialect.PostgreSQLDialect
      jdbc:
        lob.non-contextual-creation: true
    properties:
      hibernate:
        show_sql: true 

Para los que trabajan en sql server la linea de codigo sería : spring.datasource.url=jdbc:sqlserver://localhost:<port>;databaseName=<NombreDeBaseDeDatos>

Para los que prefieren trabajar con postgresql tienen que reemplazar en application.properties

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

spring.datasource.url=jdbc:postgresql://localhost:<port>:<NombreDeBaseDeDatos>

por defecto el puerto se usa 5432 … y en el archivo build.gradle agregamos

runtimeOnly 'org.postgresql:postgresql'

la funcion de crear la base de dato me toco realizarla manualmente desde postgresql

A mí no me funcionaba, hasta que ingresé:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/pizzeria?createDatabaseIfNotExist=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.datasource.username=<tu-usuario>
spring.datasource.username.password=<tu-clave>

Hasta este punto recomiendo mucho Docker, así nos evitamos instalaciones de cada motor de base de datos y con simples lineas de codigo ya tendríamos nuestra base de datos montada en un contenedor y lista para usar.
Aquí estaría la creación de la base de datos con docker:

docker volume create mysql-volume
docker run -d -p 3306:3306 -v mysql-volume:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=<contraseña que quieras asignar > --name mysql-container mysql:latest

Ya con esto podemos probar si la conexión es exitosa y listo a seguir aprendiendo. Sin embargo, recomiendo el curso de Docker.

https://platzi.com/cursos/docker/

URL Instalador 3 Mb :

https://dev.mysql.com/downloads/installer/

  1. Instalar

  2. Abrir y dar click en catalog.

  3. Se abre una nueva ventata, Click en Execute.

  4. Se regresa a la ventana anterior, Click en “Add” seleccionar

  5. MySQL Server.

  6. Seleccionar la ultima versión, instalar y finalizar.

Como crear una base de datos MySql con Docker compose

La base de datos se crea con un volumen para poder almacenar los datos en forma persistente dentro de nuestro sistema de archivos

Tener instalado el docker-desktop en el caso de windows y Mac. Los usuarios linux ya saben que hacer.

crear el archivo desde la linea de comandos, para el caso linux & mac

touch docker-compose.yml 

Pegar el siguiente texto dentro del archivo

NOTA: Las lineas que comienzan con # son comentarios que solo sirven como ayuda memoria

#################
### desde la consola de comandos ejecutar
#################

#################
### inicial el contenedor ###
#################
# docker compose up mysql

#################
### inicial el contenedor sin los logs de consola ###
#################
# docker compose up mysql -d

#################
###detener el contenedor###
#################
# docker compose down

#################
#################
#cambiar a gusto las credenciales del usuario
#################

version: '3.8'
services:
  mysql:
        image: mysql:latest
        command: --default-authentication-plugin=mysql_native_password
        volumes:
        - "./mysql-data/db:/var/lib/mysql"
        restart: always        
        ports:
            - 3306:3306
        environment:
            MYSQL_ROOT_PASSWORD: rootpw
            MYSQL_DATABASE: pizzeria
            MYSQL_USER: pizza
            MYSQL_PASSWORD: 123456

Un administrador de base de datos recomendable para todos los Sistemas operativos populares, funciona muy bien y además tiene muchos atajos de teclado, es el dbeaver.

Saludos

En lugar de instalar mysql en el computador seria mejor utilizar docker, y manejar la conexion en el docker-compose file

El nombre de la base de datos que se va a usar es pizzería, si estas usando mysql puedes poner le opción de createDatabaseIfNotExist=true para que cree la base de datos automáticamente, en la opción spring.jpa.hibernate.ddl-auto la vamos a poner a update para que nos cree las tablas pero no borre información

Tienen que tener la base de datos instalada, si utilizan otra base de datos recuerden que el código createDatabaseIfNotExist=true solo funciona con mysql,
pueden crear manual mente la tabla y la base en donde estará la tabla cualquier duda no duden en preguntar por haca

La siguiente propiedad permite mostrar en la consola del IDA la instrucción SQL que se está ejecutando:

spring.jpa.show-sql=true

Si se desea verla con un mejor formato y estructura, se puede agregar también la siguiente propiedad:

spring.jpa.properties.hibernate.format_sql=true

Para quienes tengan problemas con Dialect pueden agregar la siguiente propiedad:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect 

Tener en cuenta que la versión del dialecto debe ser la del MySQL que tengan instalado en sus maquinas

Estas fueron las configuraciones que en mi caso necesite

spring.datasource.url=jdbc:mysql://localhost:3306/pizzeria
spring.datasource.username=root
spring.datasource.password=*****
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect

Si quieren usar .env
dotenv
main

public class PlatziPizzeriaApplication {

	public static void main(String[] args) {
		Dotenv dotenv = Dotenv.configure().load();
		dotenv.entries().forEach(entry -> System.setProperty(entry.getKey(), entry.getValue()));
		SpringApplication.run(PlatziPizzeriaApplication.class, args);

	}

}

aplication

spring.datasource.url=jdbc:mysql://localhost:3306/pizzeria
spring.datasource.username=${USER_SQL}
spring.datasource.password=${PASSWORD_SQL}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect

Si tiene Mysql 8 deben de agregar la siguiente linea a la configuración

spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect

me funcionó sin poner el puerto

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/pizzeria?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=*****

Hola tú

Por si no te autocompleta algunos campos en el archivo application.properties, puedes usar el siguiente plugin: wl Spring Assistant, no es tan bueno como el del profesor (creo que tiene IntelliJ Idea Ultimate), pero es muy bueno para la versión community.

excelente explicaicon
Por si a alguien le pasa lo mismo que a mi... hay que instalar mysql jeje
Este es el contenido de mi archivo de properties: spring.application.name=platzi-pizzeria spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:Mysql:/localhost:3307/pizzeria?createDatabaseIfNotExist=true spring.datasource.name=root spring.datasource.password=\*\*\*\*\* spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect spring.jpa.hibernate.ddl-auto=update sin embargo al ejecutarlo me manda el siguiente error: \> Task :PlatziPizzeriaApplication.main() . \_\_\_\_ \_ \_\_ \_ \_ /\\\ / \_\_\_'\_ \_\_ \_ \_(\_)\_ \_\_ \_\_ \_ \ \ \ \\ ( ( )\\\_\_\_ | '\_ | '\_| | '\_ \\/ \_` | \ \ \ \\ \\\\/ \_\_\_)| |\_)| | | | | || (\_| | ) ) ) ) ' |\_\_\_\_| .\_\_|\_| |\_|\_| |\_\\\_\_, | / / / / \=========|\_|==============|\_\_\_/=/\_/\_/\_/ :: Spring Boot :: (v3.3.5) 2024-11-28T19:18:11.948-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] c.p.pizza.PlatziPizzeriaApplication : Starting PlatziPizzeriaApplication using Java 17.0.13 with PID 16176 (C:\Users\Carlos Rojas\OneDrive\Documentos\crojas\per\cursos\Spring-JPA\platzi-pizzeria\build\classes\java\main started by Carlos Rojas in C:\Users\Carlos Rojas\OneDrive\Documentos\crojas\per\cursos\Spring-JPA\platzi-pizzeria) 2024-11-28T19:18:11.954-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] c.p.pizza.PlatziPizzeriaApplication : No active profile set, falling back to 1 default profile: "default" 2024-11-28T19:18:13.529-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2024-11-28T19:18:13.592-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 37 ms. Found 0 JPA repository interfaces. 2024-11-28T19:18:14.784-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port 8080 (http) 2024-11-28T19:18:14.823-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] o.apache.catalina.core.StandardService : Starting service \[Tomcat] 2024-11-28T19:18:14.823-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: \[Apache Tomcat/10.1.31] 2024-11-28T19:18:15.076-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] o.a.c.c.C.\[Tomcat].\[localhost].\[/] : Initializing Spring embedded WebApplicationContext 2024-11-28T19:18:15.080-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3013 ms 2024-11-28T19:18:15.493-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo \[name: default] 2024-11-28T19:18:15.672-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 6.5.3.Final 2024-11-28T19:18:15.765-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] o.h.c.internal.RegionFactoryInitiator : HHH000026: Second-level cache disabled 2024-11-28T19:18:16.603-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] o.s.o.j.p.SpringPersistenceUnitInfo : No LoadTimeWeaver setup: ignoring JPA class transformer 2024-11-28T19:18:16.705-06:00 INFO 16176 --- \[platzi-pizzeria] \[ main] com.zaxxer.hikari.HikariDataSource : root - Starting... 2024-11-28T19:18:17.986-06:00 WARN 16176 --- \[platzi-pizzeria] \[ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 08S01 2024-11-28T19:18:17.986-06:00 ERROR 16176 --- \[platzi-pizzeria] \[ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. 2024-11-28T19:18:17.988-06:00 WARN 16176 --- \[platzi-pizzeria] \[ main] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000342: Could not obtain connection to query metadata org.hibernate.exception.JDBCConnectionException: unable to obtain isolated JDBC connection \[Communications link failure Sin embargo mi BD MySQL se conecta sin problemas desde el workbench ![](<C:\Users\Carlos Rojas\Downloads>)
Si alguien se conectara un dia con AWS Elastic Beanstalk: ```js # Database Las variables de entorno se encuentran en AWS Elastic Beanstalk spring.datasource.url=jdbc:postgresql://${RDS_HOSTNAME}:${RDS_PORT}/${RDS_DB_NAME} spring.datasource.username=${RDS_USERNAME} spring.datasource.password=${RDS_PASSWORD} ```# Database Las variables de entorno se encuentran en AWS Elastic Beanstalk spring.datasource.url=jdbc:postgresql://${RDS\_HOSTNAME}:${RDS\_PORT}/${RDS\_DB\_NAME} spring.datasource.username=${RDS\_USERNAME} spring.datasource.password=${RDS\_PASSWORD}
Para facilitar la instalación de la DB así como su administración les compoarto el docker-compose.yml ```js version: '3.9' # mysql services: db: image: mysql:8.0.37-bookworm container_name: mysql_db environment: - MYSQL_ROOT_PASSWORD=123456789 - MYSQL_DATABASE=pizzeria ports: - 3306:3306 volumes: - spring-data-access:/var/lib/mysq l workbench: image: linuxserver/mysql-workbench:8.0.38 container_name: mysql_workbench depends_on: - db environment: - PUID=1000 - PGID=1000 ports: - 3333:3000 volumes: - spring-data-access-ui:/config volumes: spring-data-access: spring-data-access-ui: ``` Para ejecutar docker `docker-compose up -d` Entrar a MySQL Workbench `localhost puerto 3333`
Que copado el detalle que se haya incluido tanto las pizzas vegetarianas como las veganas en el proyecto! Pequeños detalles que dan satisfacción :)
Configuración para conectar al SQL SERVER `spring.application.name=pizzeria` `spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver` `spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=<nombrebasedatos>;encrypt=true;trustServerCertificate=true` `spring.datasource.username=<user>` `spring.datasource.password=<contraseña>` `spring.jpa.hibernate.ddl-auto=update` `spring.jpa.show-sql=true` Será necesario habilitar el TCP/IP (seguir los pasos del link) <https://help.dugeo.com/m/Insight/l/438913-troubleshooting-enabling-tcp-ip-in-the-sql-server> Ademas tendras que descargar el mssql-jdbc actual en mi caso descargue la version 12.6.1.jre11, link de descarga: <https://learn.microsoft.com/en-us/sql/connect/jdbc/release-notes-for-the-jdbc-driver?view=sql-server-ver16> Posterior tendras que agregar la libreria al proyecto y agregar la linea de codigo al build.gradle en las dependencies: `implementation 'com.microsoft.sqlserver:mssql-jdbc:12.6.1.jre11'`
Para SQL Server. `# Database` `spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver` `spring.datasource.url=jdbc:sqlserver://;serverName=localhost;databaseName=PizzeriaDev;encrypt=true;trustServerCertificate=true;` `spring.datasource.username=sa` `spring.datasource.password=TuContrasena` `spring.jpa.hibernate.ddl-auto=update` `spring.jpa.show-sql=true` Validar que la configuración TCP/IP de SQL Server este habilitada. En caso contrario deberá habilitarla. Habilitar TCP/IP: <https://help.dugeo.com/m/Insight/l/438913-troubleshooting-enabling-tcp-ip-in-the-sql-server>
![](https://static.platzi.com/media/user_upload/image-7602b4f1-f94f-4baf-bd83-c88394a5a52b.jpg)```js porfavor ayuda porque ese ERROR ? ```
como siempre capo mi estimado, gracias a ti estoy perfeccionandome, detallado el curso un crack
Hola, recomiendo mucho utilizar docker-compose, de esta manera no andar peleando con configuraciones e instalaciones que después resultan mal, les comparto mi configuración de mi **docker-compose.yml**: `versión: '3.3'` `services:` ` db:` ` image: mysql:5` ` container_name: mysql_container` ` environment:` ` MYSQL_ROOT_PASSWORD: admin123` ` MYSQL_DATABASE: course_spring_data_jpa` ` ports:` ` - "3306:3306"` ` volumes:` ` - mysql_data:/var/lib/mysql` ` phpmyadmin:` ` image: phpmyadmin/phpmyadmin` ` container_name: phpmyadmin_container` ` environment:` ` PMA_ARBITRARY: 1` ` ports:` ` - "8080:80"` ` depends_on:` ` - db` `volumes:` ` mysql_data:`
muy claro. que bueno el nivel de abstraccion de la herramienta

Yo me conecté con PostgreSQL usando la misma configuración del proyecto del curso anterior

Configuración para conectar al SQL SERVER ```js spring.application.name=pizzeria spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=<nombrebasedatos>;encrypt=true;trustServerCertificate=true spring.datasource.username=<user> spring.datasource.password=<contraseña> spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true ```Será necesario habilitar el TCP/IP (seguir los pasos del link) <https://help.dugeo.com/m/Insight/l/438913-troubleshooting-enabling-tcp-ip-in-the-sql-server> Además tendrás que descargar el mssql-jdbc actual en mi caso descargue la versión 12.6.1.jre11, link de descarga: <https://learn.microsoft.com/en-us/sql/connect/jdbc/release-notes-for-the-jdbc-driver?view=sql-server-ver16> Posterior tendrás que agregar la librería al proyecto y agregar la linea de código al build.gradle en las dependencies: ```js implementation 'com.microsoft.sqlserver:mssql-jdbc:12.6.1.jre11' ```