西丽网站设计,wordpress添加会员登录页面,厦门网站制作费用,形象墙设计SpringBootJpaThymeleaf实现增删改查
这篇文章介绍如何使用 Jpa 和 Thymeleaf 做一个增删改查的示例。
1、pom依赖
pom 包里面添加Jpa 和 Thymeleaf 的相关包引用
?xml version1.0 encodingUTF-8?
project xmlnshttp://maven.…SpringBootJpaThymeleaf实现增删改查
这篇文章介绍如何使用 Jpa 和 Thymeleaf 做一个增删改查的示例。
1、pom依赖
pom 包里面添加Jpa 和 Thymeleaf 的相关包引用
?xml version1.0 encodingUTF-8?
project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.1.0.RELEASE/version/parentgroupIdcom.example/groupIdartifactIdspring-boot-jpa-thymeleaf-curd/artifactIdversion0.0.1-SNAPSHOT/versionnamespring-boot-jpa-thymeleaf-curd/namedescriptionspring-boot-jpa-thymeleaf-curd/descriptionpropertiesjava.version1.8/java.version/propertiesdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-thymeleaf/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-jpa/artifactId/dependencydependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-devtools/artifactIdoptionaltrue/optional/dependency/dependenciesbuildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactIdconfigurationforktrue/fork/configuration/plugin/plugins/build/project2、application.properties中添加配置
spring.datasource.urljdbc:mysql://127.0.0.1/test?useUnicodetruecharacterEncodingutf-8serverTimezoneUTCuseSSLtrue
spring.datasource.usernameroot
spring.datasource.passwordroot
spring.datasource.driver-class-namecom.mysql.cj.jdbc.Driverspring.jpa.properties.hibernate.hbm2ddl.autocreate
spring.jpa.properties.hibernate.dialectorg.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql true
spring.thymeleaf.cachefalse其中propertiesspring.thymeleaf.cachefalse是关闭 Thymeleaf 的缓存不然在开发过程中修改页面不会
立刻生效需要重启生产可配置为 true。
在项目 resources 目录下会有两个文件夹static目录用于放置网站的静态内容如 css、js、图片
templates 目录用于放置项目使用的页面模板。
3、启动类
启动类需要添加 Servlet 的支持
package com.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;SpringBootApplication
public class Application extends SpringBootServletInitializer {Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(Application.class);}public static void main(String[] args) throws Exception {SpringApplication.run(Application.class, args);}
}4、数据库层代码
实体类映射数据库表
package com.example.model;import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;Entity
public class User {IdGeneratedValueprivate long id;Column(nullable false, unique true)private String userName;Column(nullable false)private String password;Column(nullable false)private int age;public long getId() {return id;}public User setId(long id) {this.id id;return this;}public String getUserName() {return userName;}public User setUserName(String userName) {this.userName userName;return this;}public String getPassword() {return password;}public User setPassword(String password) {this.password password;return this;}public int getAge() {return age;}public User setAge(int age) {this.age age;return this;}
}5、 JpaRepository
package com.example.repository;import com.example.model.User;
import org.springframework.data.jpa.repository.JpaRepository;public interface UserRepository extends JpaRepositoryUser, Long {User findById(long id);void deleteById(Long id);
}继承 JpaRepository 类会自动实现很多内置的方法包括增删改查也可以根据方法名来自动生成相关 Sql。
6、业务层处理
Service 调用 Jpa 实现相关的增删改查实际项目中 Service 层处理具体的业务代码。
package com.example.service;import com.example.model.User;import java.util.List;public interface UserService {public ListUser getUserList();public User findUserById(long id);public void save(User user);public void edit(User user);public void delete(long id);}package com.example.service.impl;import com.example.model.User;
import com.example.repository.UserRepository;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;Service
public class UserServiceImpl implements UserService {Autowiredprivate UserRepository userRepository;Overridepublic ListUser getUserList() {return userRepository.findAll();}Overridepublic User findUserById(long id) {return userRepository.findById(id);}Overridepublic void save(User user) {userRepository.save(user);}Overridepublic void edit(User user) {userRepository.save(user);}Overridepublic void delete(long id) {userRepository.deleteById(id);}
}7、控制层
package com.example.web;import com.example.model.User;
import com.example.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;import javax.annotation.Resource;
import java.util.List;Controller
public class UserController {ResourceUserService userService;RequestMapping(/)public String index() {return redirect:/list;}RequestMapping(/list)public String list(Model model) {ListUser users userService.getUserList();model.addAttribute(users, users);return user/list;}RequestMapping(/toAdd)public String toAdd() {return user/userAdd;}RequestMapping(/add)public String add(User user) {userService.save(user);return redirect:/list;}RequestMapping(/toEdit)public String toEdit(Model model, Long id) {User user userService.findUserById(id);model.addAttribute(user, user);return user/userEdit;}RequestMapping(/edit)public String edit(User user) {userService.edit(user);return redirect:/list;}RequestMapping(/delete)public String delete(Long id) {userService.delete(id);return redirect:/list;}
}Controller 负责接收请求处理完后将页面内容返回给前端。 return user/userEdit; 代表会直接去 resources 目录下找相关的文件。 return redirect:/list; 代表转发到对应的 Controller这个示例就相当于删除内容之后自动调整到 list 请求然后再输出到页面。
8、页面内容
list 列表 list.html
!DOCTYPE html
html langen xmlns:thhttp://www.thymeleaf.org
headmeta charsetUTF-8/titleuserList/titlelink relstylesheet th:href{/css/bootstrap.css}/link
/head
body classcontainer
br/
h1用户列表/h1
br/br/
div classwith:80%table classtable table-hovertheadtrth#/ththUser Name/ththPassword/ththAge/ththEdit/ththDelete/th/tr/theadtbodytr th:eachuser : ${users}th scoperow th:text${user.id}1/thtd th:text${user.userName}neo/tdtd th:text${user.password}Otto/tdtd th:text${user.age}6/tdtda th:href{/toEdit(id${user.id})}edit/a/tdtda th:href{/delete(id${user.id})}delete/a/td/tr/tbody/table
/div
div classform-groupdiv classcol-sm-2 control-labela href/toAdd th:href{/toAdd} classbtn btn-infoadd/a/div
/div/body
/html访问http://localhost:8080/效果如下图所示
tr th:eachuser : ${users} 这里会从 Controler 层 model set 的对象去获取相关的内容th:each表
示会循环遍历对象内容。
点击Add按钮会跳转到新增页面。
新增页面 userAdd.html
!DOCTYPE html
html langen xmlns:thhttp://www.thymeleaf.org
headmeta charsetUTF-8/titleuser/titlelink relstylesheet th:href{/css/bootstrap.css}/link
/head
body classcontainer
br/
h1添加用户/h1
br/br/
div classwith:80%form classform-horizontal th:action{/add} methodpostdiv classform-grouplabel foruserName classcol-sm-2 control-labeluserName/labeldiv classcol-sm-10input typetext classform-control nameuserName iduserName placeholderuserName//div/divdiv classform-grouplabel forpassword classcol-sm-2 control-label Password/labeldiv classcol-sm-10input typepassword classform-control namepassword idpassword placeholderPassword//div/divdiv classform-grouplabel forage classcol-sm-2 control-labelage/labeldiv classcol-sm-10input typetext classform-control nameage idage placeholderage//div/divdiv classform-groupdiv classcol-sm-offset-2 col-sm-10input typesubmit valueSubmit classbtn btn-info /nbsp; nbsp; nbsp;input typereset valueReset classbtn btn-info //div/div/form
/div
/body
/html填写数据并且点击Submit按钮用户添加成功并且跳转到用户列表页面。 点击edit按钮跳转到用户修改页面。
修改页面 userEdit.html
!DOCTYPE html
html langen xmlns:thhttp://www.thymeleaf.org
headmeta charsetUTF-8/titleuser/titlelink relstylesheet th:href{/css/bootstrap.css}/link
/head
body classcontainer
br/
h1修改用户/h1
br/br/
div classwith:80%form classform-horizontal th:action{/edit} th:object${user} methodpostinput typehidden nameid th:value*{id} /div classform-grouplabel foruserName classcol-sm-2 control-labeluserName/labeldiv classcol-sm-10input typetext classform-control nameuserName iduserName th:value*{userName} placeholderuserName//div/divdiv classform-grouplabel forpassword classcol-sm-2 control-label Password/labeldiv classcol-sm-10input typepassword classform-control namepassword idpassword th:value*{password} placeholderPassword//div/divdiv classform-grouplabel forage classcol-sm-2 control-labelage/labeldiv classcol-sm-10input typetext classform-control nameage idage th:value*{age} placeholderage//div/divdiv classform-groupdiv classcol-sm-offset-2 col-sm-10input typesubmit valueSubmit classbtn btn-info /nbsp; nbsp; nbsp;a href/toAdd th:href{/list} classbtn btn-infoBack/a/div/div/form
/div
/body
/html修改用户的年龄为100然后点击Submit按钮提交修改。
然后跳转到用户列表页面发现数据修改了。 可以点击delete按钮删除用户。
删除之后跳转到用户列表页面。 这样一个使用 Jpa 和 Thymeleaf 的增删改查示例就完成了。