Spring Boot+Mysql 入门 +简单的增删改查
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
我们使用maven来新建项目,首先,新建一个空白的web项目
然后添加相关依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ziv.test</groupId> <artifactId>MySpringboot</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>MySpringboot Maven Webapp</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
这里使用spring-data-jpa来操作数据库,Spring Boot 不推荐使用jsp作前端页面渲染,这里我们使用thymeleaf作模板引擎。
在resources目录下新建如下目录和文件
static用来存放静态资源,比如css/js等,templates用来存放html等资源。
application.yml是项目中最重要的文件,有了它,我们才不用编写如springmvc那种多而杂的配置,如下
spring: datasource: url: jdbc:mysql://localhost:3306/zz?characterEncoding=utf-8 username: root password: root driver-class-name: com.mysql.jdbc.Driver jpa: database-platform: org.hibernate.dialect.MySQL5Dialect hibernate: ddl-auto: update show-sql: true thymeleaf: prefix: classpath:/templates/ logging: file: F:/mylog/log.log level: org: springframework: web: DEBUG
看,就这么些,就完成了mysql,jpa,thyeleaf和log的配置,相比于springmvc,算了。。。
接下来在src/maim./java中加入如下目录和文件,如同springmvc
其中,Application.java文件是Spring Boot项目的启动类,必须加上@SpringBootApplication注解
package com.m2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class Application extends SpringBootServletInitializer { /* * @RequestMapping("/") public String greeting() { return "Hello World!"; } */ protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
model
package com.m2.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Table(name="Student") @Entity public class Student { @Id @GeneratedValue private int id; @Column(nullable = false, unique = true) private String name; @Column(nullable = false) private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Dao(还不熟悉spring-data-jpa的同学,可以先去了解一下)
package com.m2.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.m2.model.Student; public interface StudentRepository extends JpaRepository<Student, Integer>{ }
Service
package com.m2.service; import java.util.List; import com.m2.model.Student; public interface StudentService { Student findUserById(int id); List<Student> findAll(); void deleteById(int id) ; void save(Student student) ; void updatestudent(Student student); }
package com.m2.service.serviceImpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.m2.dao.StudentRepository; import com.m2.model.Student; import com.m2.service.StudentService; @Service public class StudentServiceImpl implements StudentService{ @Autowired StudentRepository studentRepository; @Override public Student findUserById(int id) { // TODO Auto-generated method stub return studentRepository.findOne(id); } @Override public List<Student> findAll() { // TODO Auto-generated method stub return studentRepository.findAll(); } @Override public void deleteById(int id) { // TODO Auto-generated method stub studentRepository.delete(id); } @Override public void save(Student student) { studentRepository.save(student); } @Override public void updatestudent(Student student) { // TODO Auto-generated method stub studentRepository.save(student); } }
Controller
package com.m2.Controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.m2.model.Student; import com.m2.service.StudentService; @Controller @RequestMapping("/student") public class StudentController { @Autowired StudentService studentService; @RequestMapping("/findbyid") @ResponseBody public String findbyid(int id) { Student student=studentService.findUserById(id); return student.getName(); } @RequestMapping("/studentlist") public String findalldata(Model model) { List<Student> studentlist=studentService.findAll(); model.addAttribute("studentlist", studentlist); return "showstudent"; } @RequestMapping("/delectbyid") public String delectbyid(int id) { studentService.deleteById(id); return "redirect:/student/studentlist"; } @RequestMapping("/savestudent") public String savestudent(Student student) { studentService.save(student); return "redirect:/student/studentlist"; } @RequestMapping("/toupdatestudent") public String toupdatestudent(int id,Model model) { Student student=studentService.findUserById(id); model.addAttribute("student", student); return "editstudent"; } @RequestMapping("/updatestudent") public String updatestudent(Student student) { studentService.updatestudent(student); return "redirect:/student/studentlist"; } }
至此,简单的CURD就已经完成了。
然后,我们编写前台页面,在templates目录下新建如下html页面:
showstudent.html: (要引用thymeleaf模板,html必须加入:<html xmlns:th="http://www.thymeleaf.org"> 代码)
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <div> <form action="/student/findbyid" method="post"> 请输入id <input type="text" name="id" /> <input type="submit" value="提交"/> </form> </div> <table> <thead> <tr> <th>id</th> <th>name</th> <th>age</th> <th>edit</th> <th>delete</th> </tr> </thead> <tbody> <tr th:each="student : ${studentlist}"> <td th:text="${student.id}"></td> <td th:text="${student.name}"></td> <td th:text="${student.age}"></td> <td><a th:href="@{/student/toupdatestudent(id=${student.id})}">edit</a></td> <td><a th:href="@{/student/delectbyid(id=${student.id})}">delete</a></td> </tr> </tbody> </table> <div> <form action="/student/savestudent" method="post"> 请输入姓名 <input type="text" name="name" /> 请输入年龄 <input type="text" name="age" /> <input type="submit" value="添加"/> </form> </div> </body> </html>
editstudent.html:
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <form action="/student/updatestudent" th:object="${student}" method="post"> <input type="hidden" name="id" th:value="${student.id}"/> 请输入姓名 <input type="text" name="name" th:value="${student.name}"/> 请输入年龄 <input type="text" name="age" th:value="${student.age}"/> <input type="submit" value="提交" /> </form> </body> </html>
student.html:
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p th:text="'Hello, ' + ${student.name} + '!'" /> <p th:text="${student.id}" /> <p th:text="${student.age}" /> </body> </html>
最后,我们更新一下项目:
按 ALT+F5,选中当前项目,点击OK。
然后,到我们之前编写的启动类Application.java中运行项目:右击-->run as-->spring boot App/java application
控制台出现如上效果,证明项目运行成功
浏览器输入网址:http://localhost:8080/student/studentlist:
添加:
删除:
修改:zhangsan改为lisi
根据id查询:
本人也是小白,也是最近才开始研究Spring Boot,如有写错或者不详细的地方,欢迎指正!