JavaRush /Java Blog /Random EN /Spring is not scary, or how to connect a database for a s...
Павел
Level 11

Spring is not scary, or how to connect a database for a student project in 5 minutes

Published in the Random EN group
CONTENTS OF THE ARTICLE CYCLE First, let's create a web server using Spring Boot . In the pom file, add the following dependencies to the <dependencies> block :
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>
The first dependency is needed for Spring to work with the database. The second dependency h2 (H2) will emulate the database without downloads, installations and complex configurations. Now I want you to ask yourself the question: “What do I want to become? A monkey coder who is not able to write something himself? Or a developer?” If you want to become a developer, then be sure to read a good book about the meaning and concept of Spring , or at least a series of articles . Right now you can search the Internet for information about what beans are, entities, dependency injection in Spring, and methods for configuring beans. Let's go back to our bases. The entire configuration will be as follows: In resourses , create an application.yml file (the name is very important!), fill it with the contents:
spring:
  datasource:
    driverClassName: org.h2.Driver
    url: jdbc:h2:mem:test;
    username: sa
    password:
    h2:
      console:
        enabled: true
  jpa:
    hibernate:
        ddl-auto: create
    generate-ddl: true
    show-sql: false
    properties:
      hibernate:
        dialect: org.hibernate.dialect.H2Dialect
Let's look at the datasource: driverClassName: indicates what type of base we will use, for us it is h2. If we installed Postgres, we would write rg.postgresql.Driver ; url: - this is the place where the database is located, in our case it is located directly in the project’s memory, as indicated by the word mem (from memory), that is, when the application is restarted, the database will be created anew. You can instead of jdbc:h2:mem:test; write jdbc:h2:~/test; , and the database will be stored in the project folder. Again, if we had Postgres installed, we would write something like jdbc:postgresql://localhost:5432/mydb . Now jpa : hibernate.ddl-auto: tells what to do with the base schema when the application is restarted. Now there is create here - that means creating again, it can also be update - adding to the database, create-drop - clearing at startup. The word hibernate is not casual here, read about it on the Internet, because we will need it. The rest of the words are not important now. Next, let's see how this database can be filled and how to work with it.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION