I have been using Python before, but I have not been able to practice it after learning the basic syntax of Java. As the test platform of the department is developed by using the Spring Boot framework, I take this opportunity to learn about it and experience the differences with Python in the future.
With the target
Let’s first clarify what we want to achieve in this experience of Spring Boot:
- A Web interface
- Data is written to the database
These are both because they are the operations we most encounter in Web development.
And can realize after writing database, other search, change, delete operations are similar.
Based on the environment
tool | version |
---|---|
IDEA | 2019.2 |
JDK | 11 |
MySQL | 5.7 |
This is only personal environment, not recommended environment, environment inconsistency is not too big a problem
Install the Spring Boot plug-in
Professional edition comes with plug-ins, no installation required.
For the community edition, search for “Spring Assistant” in the IDEA plugin center to install.
Project configuration
New project
- Select project type “Spring Initializr”
- Select the corresponding SDK, “Initializr Service URL” and select the default, next step
- Enter the project name and other information (I keep the default, so the project is
com.example.demo
), I chose Maven as the build tool - Select the dependency you want to add. You are advised to use:
- Developer Tools:
- Spring Boot DevTools (automatic service restart after code modification)
- Lombok (Java’s excellent annotation library to reduce Setter/Getter and other code writing)
- Web:
- Spring Web Starter (contains components and containers required by Spring projects)
- SQL:
- Spring Data JPA (a JPA compliant library that uses Hibernate to persist Data)
- MySQL Driver
- Developer Tools:
This is the successful creation of a new project.
pom.xml
Because the project was created using Spring Initializr, the dependency coordinates in POM.xml are already configured and do not need to be modified.
Adding a Database Configuration
Modify the SRC/main/resouces/application. The properties file, add the following content:
# database configuration
The jPA library needs to be created in advancespring.datasource.url=jdbc:mysql://localhost:3306/jpa? useSSL=false
# database account
spring.datasource.username=root
# database password
spring.datasource.password=123456
# database driver
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# JPA configuration
Automatic handling of object-relational mapping, allowing automatic table building and other operations
spring.jpa.hibernate.ddl-auto=update
Whether to display database statements on the console
spring.jpa.show-sql=true
Copy the code
For spring.jpa.hibernate.dcl-auto configuration, there are several options:
- Validate: When Hibernate is loaded, verify that the database table structure is created
- Create: Re-creates the database table structure each time Hibernate is loaded
- Create-drop: Create tables when Hibernate is loaded and drop table structures when Hibernate exits
- Update: Loads Hibernate to automatically update the database table structure
Code implementation
Database operations
Entity class
An entity class is a code description of an entity object.
Establish relational mapping (ORM) between entity class and database tables and fields, so that the operation of adding, deleting, changing and checking database can be completed by operating entity class.
For example, creating a “Book” entity class, suppose we want to operate on a table named “t_book”:
// Mark this class as an entity class
@Entity
// Set the database table for the operation
@Table(name="t_book")
public class Book{
// Set the primary key
@Id
// The value of the field generated by the strategy, not to expand the description, can be private check
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
// Configure field attributes
@Column(length = 32)
private String name;
// Add getter/setter methods for fields
public Integer getId(a) {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString(a) {
return "Book{" +
"id=" + id +
", name='" + name + '\' ' +
'} '; }}Copy the code
The code is a bit long and can be simplified using Lombok.
* Use Lombok to simplify code
Lombok is a Java utility that helps developers eliminate verbose Java code with annotations that apply to our entity classes as follows:
@Entity
@Table(name="t_book")
@Data
public class Book{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
}
Copy the code
As you can see, using Lombok’s Data annotations simplifies our code a lot. We don’t need to write getters/setters and toString methods for fields, and we don’t need to specify a database Column for a field, just keep the @ID annotation for the primary key.
DAO class
The entity class Book just establishes the object-relational mapping, and you need to create a DAO class to simplify persistence (save/ Delete, etc.).
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookDao extends JpaRepository<Book.Integer> {}Copy the code
Methods are already implemented in JpaRepository and do not require additional writing.
The test case
Create a test case to test writing data:
@RunWith(SpringRunner.class)
@SpringBootTest
public class BookTests {
@Autowired
public BookDao bookDao;
@Test
public void testBook(a) {
Book book = new Book();
book.setName("book1"); bookDao.save(book); }}Copy the code
The test case passes and queries the T_book table of the database to see that a data entry has been inserted.
A Web interface
Start with the simplest implementation. Write an interface that receives GET requests and returns “Hello, Spring Boog!” Response content:
@RestController
@RequestMapping("/")
public class HelloController {
@RequestMapping("/hello")
public String index(a){
return "Hello, Spring Boot!"; }}Copy the code
Right-click DemoApplication, start it, and call 0.0.0.0:8080/hello to see the browser output “Hello, Spring Boot!” A simple interface is created.
conclusion
The previous impression of Java was tedious, with many declarations and configurations. However, after experiencing Spring Boot, especially after using some initialization plug-ins to create projects, we can find that in fact, the most basic code framework Spring Boot has been generated for us, but it is necessary to understand the use of some frameworks or libraries, the general idea of Web development is still the same. Let’s continue learning in business code!