This post would demo how to do basic CRUD operations by using springboot 2 and JPA.
2. Environments
SpringBoot 2.0.2+
SpringBoot starter data jpa
MySQL connector java
Lombok
Java 1.8
3. The Pom.xml
spring boot version:
all dependencies:
4. The dependencies explanation
4.1 The lombok
The lombok is an IDE plugin to help you do some boliertemplate jobs. In this post we use the lombok to generate the getter/setter of the domain object.
You can refer to this post to learn how to use lombok.
5. The project layout
6. The database , table and initial data
For demo purpose, I setup one database in localhost as follows:
There is a table ‘tbl_student’ in both of the databases:
And insert five records into that table:
7. The domain class Student
Here we use the lombok @Data annotation to generate getter/setter and constructors for the Student class.
We define the id property as the @Id of the table ,and specify the GenerationType.IDENTITY to it, which means the id is auto-increment.
We define the table name by @Table annotation
7. The app codes
7.1 the application.properties
Supply these properties in your application.properties:
7.3 The StudentRepository interface
The dao.StudentRepository is as follows:
The class StudentRepository only extends from the CrudRepository ,there is no need to define any other methods to implement the CRUD operations.
7.5 The testcase
The StudentRepositoryTest class would test the CRUD operations and find operations:
Run the testcase, we got a green bar.
It’s so easy, do you think so?
The example source code has been uploaded to github, you can visit here to view the example source codes.