Python has been used before, after learning the basic syntax of Java and has not been able to practice, just to test the platform sector is developed using the Spring Boot frame, take the opportunity to learn about the future can taste the difference with Python.
With the goal
First, we define the function in this experience in Spring Boot want to achieve:
- A Web Interface
- Data written to the database
The reason is both, because we are the most experienced in Web development is that they operate.
After writing the database can be realized, other check, change, delete operations are similar.
Basic environment
tool | version |
---|---|
IDEA | 2019.2 |
JDK | 11 |
MySQL | 5.7 |
Here is just a personal environment, non-recommended environment, environmental inconsistency no big problem
Spring Boot plug-in installation
Professional Edition comes with plug-ins, no installation.
Community Edition need to search for "Spring Assistant" is installed at the IDEA plug-center.
Project Configuration
New Project
- Select the type of project "Spring Initializr"
- Select the corresponding SDK, "Initializr Service URL" to select the default, the next step
- Enter a project name and other information (I keep the default, so the project is
com.example.demo
), I chose to Maven as a build tool - The choice depends need to add, we recommend:
- Developer Tools:
- Spring Boot DevTools (after modifying the code to automatically restart the service)
- Lombok (Java annotations excellent library, you can reduce the write Setter / Getter code, etc.)
- Web:
- Spring Web Starter (Spring container contains components required for the project)
- SQL:
- Spring Data JPA (JPA specification to follow, using the Hibernate persistence library data)
- MySQL Driver (database-driven)
- Developer Tools:
Above that is successfully created a new project.
pom.xml
Because the use of Spring Initializr
creating a project, pom.xml
is dependent coordinates have been configured, without modification.
Adding database configuration
Modify the src/main/resouces/application.properties
file, add the following content:
# 数据库配置
# 数据库连接地址,jpa库需要提前创建好
spring.datasource.url=jdbc:mysql://localhost:3306/jpa?useSSL=false
# 数据库账号
spring.datasource.username=root
# 数据库密码
spring.datasource.password=123456
# 数据库驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# JPA 配置
# 自动处理对象关系映射,允许自动建表等操作
spring.jpa.hibernate.ddl-auto=update
# 是否在控制台显示数据库语句
spring.jpa.show-sql=true
复制代码
About spring.jpa.hibernate.ddl-auto
configuration has the following options:
- validate: When loading Hibernate, create a database table structure verification
- create: every time you load Hibernate, recreate the database table structure
- create-drop: to build the table when loading Hibernate, delete the table structure when you exit
- update: Hibernate load automatically update the database table structure
Code
Database operations
Entity class
Entity class code that is a description of a physical object.
Mapping relationship database tables and fields (ORM) in the entity class, the entity class such that by operating the completed additions and deletions to the database change search operation.
To create a "Book" entity class as an example, suppose we expect the operating table named "t_book":
// 标记此类为实体类
@Entity
// 设置操作的数据库表
@Table(name="t_book")
public class Book{
// 设置主键
@Id
// 字段值的生成策略,暂不展开说明,可以私下查一下
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
// 配置字段属性,可以不需要
@Column(length = 32)
private String name;
// 添加字段的 getter/setter 方法
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
复制代码
Some of the code length, can
Lombok
be simplified.
* Simplified using codes Lombok
Lombok is a Java utility that can help developers by eliminating the lengthy annotations Java code, application on our entity class effect is as follows:
@Entity
@Table(name="t_book")
@Data
public class Book{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
}
复制代码
It can be seen in the use lombok
of Data
the comments, we simplified the code a lot, do not need to write fields Getter/Setter
and toString
methods, and do not need to specify the database field Column, keep only the primary key of the @Id
notes can be.
DAO class
Entity classes Book
only established object-relational mapping, also you need to create a lasting DAO classes simplify the process ( save
/ delete
etc).
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookDao extends JpaRepository<Book, Integer> {
}
复制代码
In the method JpaRepository
has been achieved, the need for additional write.
Test Case
Create a test case for writing test data:
@RunWith(SpringRunner.class)
@SpringBootTest
public class BookTests {
@Autowired
public BookDao bookDao;
@Test
public void testBook() {
Book book = new Book();
book.setName("book1");
bookDao.save(book);
}
}
复制代码
Test cases by query the database t_book
table you can see a piece of data has been inserted.
Web Interface
Or from the start with the simplest implementation, the first to write a reception GET
interface request and returns the response content "Hello, Spring Boog!":
@RestController
@RequestMapping("/")
public class HelloController {
@RequestMapping("/hello")
public String index(){
return "Hello, Spring Boot!";
}
}
复制代码
Right-run project DemoApplication
, started visiting 0.0.0.0:8080/hello
see the browser output "Hello, Spring Boot!", One of the most simple interface to create success.
to sum up
Before the impression that Java is a cumbersome, multi-statement, configuration and more. But after the experience of the Spring Boot, particularly the use of some initialization plug-in to create a project can be found, in fact, the most basic source framework Spring Boot has generated for us is good, but need to understand the use of some framework or library, general Web development the idea is still the same. Next in the business to continue to learn the code!