1, adding a dependency to the pom.xml
<!--spring data jpa依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!--mysql数据库依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--freemarker模板依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
2, the configuration database and the application.properties in JPA, freemarker
#DB Configation
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin
#JPAConfigation
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
#freemarker
spring.freemarker.suffix=.ftl
3, create entity classes
@Entity @Table(name = "user") @Data public class User { @Id//主键 @GeneratedValue(strategy = GenerationType.IDENTITY)//主键自增 private Integer id; private String name; private Integer age; }
4. Create a class UserDao interface inheritance JpaRepository
public interface UserDao extends JpaRepository<User,Integer> { }
5. Create a controller class
@Controller public class PageController { @Autowired private UserDao userDao; @RequestMapping("/users/page/list") public String showUserList(Model model){ List<User> userList = userDao.findAll(); model.addAttribute("userList",userList); return "user"; } }
6, shows the query to the data in the template page user.ftl
<html> <head> <title>spring boot</title> </head> <body> <table border="1px" bgcolor="#7fffd4"> <thead> <tr> <th>id</th> <th>name</th> <th>age</th> </tr> </thead> <tbody> <#list userList as user> <tr> <td>${user.id}</td> <td>${user.name}</td> <td>${user.age}</td> </tr> </#list> </tbody> </table> </body> </html>
7, start the project, write interface path in the browser, view the results