JavaRush /Java Blog /Random EN /Continuation of the analysis of the test task
timurnav
Level 21

Continuation of the analysis of the test task

Published in the Random EN group
In continuation of the topic about the task I received , I publish an analysis of such issues as attaching a database to the Spring Boot project, connecting the database to the controller, outputting data from the database to the browser in JSON format. Fasten the database Let's start with the lyrics as usual. Hibernate, even if you used the Spring Data project ... Spring Boot gives you a unique drug that gets rid of hemorrhoids in just one application! What can I say, let's get down to business! According to the official documentation, in order to add an embedded database (embeded databases - google it!) to the project, we only need to add the dependency of the driver of the corresponding database and technology (we have data jpa) to the project memory, write an entity class, write one interface without implementation and write a database filling script, everything else will be done for us by the great and mighty Spring Boot, we will have a non-embeddable database, so there will be a little more action. And now for specific actions: We create an entity class, according to the assignment, we need to work with Users, so let's create a User class. Let's make it persistent right away - add the necessary annotations. Create a domain directory in the same folder as the main class. It should turn out like this: └── src └── main └── java └── demo(тут ваше название) └── controller - о нем речь в конце └── domain └── repository - о нем речь дальше └── User - новый класс └── DemoApplication - главный класс └── DemoController - контроллер созданный нами ранее and here is the class itself. package demo.domain; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; import java.sql.Timestamp; @Entity @Table(name = "users") public class User { @Id @GeneratedValue private long id; @Column(name = "avatar") private String url; @Length(min = 2) private String name; @Column(unique = true) @Email private String email; public long getId() { return id; } public User setId(long id) { this.id = id; return this; } public String getUrl() { return url; } public User setUrl(String url) { this.url = url; return this; } public String getName() { return name; } public User setName(String name) { this.name = name; return this; } } If you did not show independence, then most of the annotations will not be loaded, to use them, we need to pull up the boot libraries that are provided by the initializer when creating the project if you check the JPA box, but they can be added manually, for performance not will affect. Open pom.xml, find the <dependencies>...</dependencies> tag and insert another dependency into it org.springframework.boot spring-boot-starter-data-jpa after inserting these lines, we update the dependencies or enable auto-configuration of maven dependencies, after which we can go back to the class with the User and import annotations from javax.persistence.* so what did we do here?! @Entity - means that an object of this class can be saved to the database, and the class itself is a table schema, i.e. corresponds to the table structure: class fields - table columns. @Table - indicates which table in the database this class corresponds to. In our case, the name of the table, do not believe it! "users" @Id is the field id, @GeneratedValue is a no brainer that a value is being generated, in our case we mean autoincrement, but we don't have to worry about that and we'll soon find out why! @Column - is used if you need to add properties to a column or if the class field name does not match the table column name (for example, id matches, we don’t use it there), but you can use it, you won’t be scolded for it. @Length and @Email are validation annotations, click on them with pressed ctrl - fall into the sources, if they are not downloaded - download, read what is written there. In general, make it a rule for yourself to constantly go into the source code and read the comments of the code authors, look at their code, this is extremely useful. At first it may be completely incomprehensible, but over time you will understand more and more, then you will generally stop reading such crap as you are reading now - only the source code is only hardcore! In a test project, you need to use MySQL if you do not have it installed - how to install it and the basic syntax of the MySQL language can be googled without problems. At all don't get scolded for it. @Length and @Email are validation annotations, click on them with pressed ctrl - fall into the sources, if they are not downloaded - download, read what is written there. In general, make it a rule for yourself to constantly go into the source code and read the comments of the code authors, look at their code, this is extremely useful. At first it may be completely incomprehensible, but over time you will understand more and more, then you will generally stop reading such crap as you are reading now - only the source code is only hardcore! In a test project, you need to use MySQL if you do not have it installed - how to install it and the basic syntax of the MySQL language can be googled without problems. At all don't get scolded for it. @Length and @Email are validation annotations, click on them with pressed ctrl - fall into the sources, if they are not downloaded - download, read what is written there. In general, make it a rule for yourself to constantly go into the source code and read the comments of the code authors, look at their code, this is extremely useful. At first it may be completely incomprehensible, but over time you will understand more and more, then you will generally stop reading such crap as you are reading now - only the source code is only hardcore! In a test project, you need to use MySQL if you do not have it installed - how to install it and the basic syntax of the MySQL language can be googled without problems. At all make it a rule to constantly go into the source code and read the comments of the code authors, look at their code, this is extremely useful. At first it may be completely incomprehensible, but over time you will understand more and more, then you will generally stop reading such crap as you are reading now - only the source code is only hardcore! In a test project, you need to use MySQL if you do not have it installed - how to install it and the basic syntax of the MySQL language can be googled without problems. At all make it a rule to constantly go into the source code and read the comments of the code authors, look at their code, this is extremely useful. At first it may be completely incomprehensible, but over time you will understand more and more, then you will generally stop reading such crap as you are reading now - only the source code is only hardcore! In a test project, you need to use MySQL if you do not have it installed - how to install it and the basic syntax of the MySQL language can be googled without problems. At all if you do not have it installed - how to install it and the basic syntax of the MySQL language can be googled without problems. At all if you do not have it installed - how to install it and the basic syntax of the MySQL language can be googled without problems. At all Spring works with PostgreSQL, MySQL, Apache Derbi, H2 or HSQLDB (this is at the time of this writing, there will most likely be more of them later). Now it's time for a lesson in witchcraft and wizardry. Create a new repository package at the same level as domain. We create one single interface in it, let's call it DemoRepository, here's all its code, now we'll create a script for filling the plate, it must be called data.sql, put it in the src/mail/resources folder, and the final touch is what you don't need to do if you use an embedded base. insert the following lines into the application.properties file mysql mysql-connector-java package demo.repository; import demo.domain.User; import org.springframework.data.jpa.repository.JpaRepository; interface DemoRepository extends JpaRepository { } INSERT INTO users (avatar, name, email) VALUES ('/pic/ava1', 'Kris', 'kroskross@gmail.com'), ('/pic/ava2', 'Josh', 'joshlong@gmail.com'); spring.data.jpa.repositories.enabled=true spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=create spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root spring.jpa.show-sql=true and again, a small nuance, you need to have a database created in MySQL, which is called test, or insert the name of your other created database into datasource.url. so summary: to fasten the base you need to: 1. have a created base (you don’t need to create any plates by hand!, only a base) 2. create an entity class, instances of which will be saved to the base. 3. insert 2 dependencies into the pomnik 4. create a repository interface and inherit from one of the standard Spring Data Jpa repositories. 5. create a script that fills the database. 6. add database settings to application.properties It seems that just a huge amount of work has been done, would you highlight how much code you need to write to connect via hibernate! not to mention jdbc along with the creation of a database through the mysql console so check. restarting the application, we will see much more logs than before using the databases, but the main thing should be the following lines: Hibernate: drop table if exists users Hibernate: create table users (id bigint not null auto_increment, email varchar(255), name varchar(255), avatar varchar(255), primary key (id)) Hibernate: alter table users add constraint UK_6dotkott2kjsp8vw4d0m25fb7 unique (email) Yes, this Spring Boot creates our tables for us. When I first saw this, I was a little taken aback :) Now if you change the domain model at the design stage - you decide to add a last name or gender to the User or add a boolean whether he is a goat or not - you just need to add a field to the @Entity class and when you restart Spring boot will create a table for you with the desired column, all that remains is to add the appropriate field to the data.sql script, now let's finally display our users in the browser! we create a controller package, it contains the UserController class, and in it, as we already know, we create a method with a request mapping that will return us a list of our Users. package demo.controller; import demo.domain.User; import demo.repository.DemoRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping(value = "/users") public class UserController { @Autowired DemoRepository demoRepository; @RequestMapping(method = RequestMethod.GET) public List getAll() { return demoRepository.findAll(); } } There is nothing new here except @Autowired, this is the binding of the created repository bean (if you have not heard of such, read what java beans are, then read how they are used in Spring) to the link used in this class. restart the application, try the address in the browser
http://localhost:8080/users
the answer should be like this
[{"id":1,"url":"/pic/ava1","name":"Kris","email":"kroskross@gmail.com"},{"id":2,"url" :"/pic/ava2","name":"Josh","email":"joshlong@gmail.com"}]
these are our Users in JSON format, that's all for today. Thank you all ps in the next post, we will deal with the main functionality of the server on assignment
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION