JPA+Thymeleaf增删改查
1.创建项目
利用IDEA工具创建项目,选择相关依赖
修改pox.xml文件,并添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId><version>3.3.2</version>
</dependency><dependency><groupId>nz.net.ultraq.thymeleaf</groupId><artifactId>thymeleaf-layout-dialect</artifactId><version>3.0.0</version>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
1.2.配置文件
spring:#配置数据源datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/数据库?useUnicode=true&characterEncoding=utf-8username: rootpassword: 123456type: com.alibaba.druid.pool.DruidDataSource #使用阿里巴巴Druid数据源# #Themeleaf模板引擎配置thymeleaf:cache: true #关闭缓存,方便调试(默认为:true)encoding: UTF-8 #设置编码mode: HTML5 #设置thymeleaf的模式prefix: classpath:/templates/ #设置模板的路径suffix: .html #设置模板的格式check-template: true #在开发时,热部署会监视模板变化,默认为truecheck-template-location: true #检查模板路径,默认为truetemplate-resolver-order: 1 #配置模板解析器的优先级,默认为1
2.模型开发
模型开发包括entity、repository、service
2.1entity
实体类包括User,Role,使用注解配置映射,且配置好关联关系:
User实体类:
@TableName("sys_user")
@Data
public class User implements Serializable {@TableField("usr_id")@TableId(type = IdType.AUTO)private Integer usrId;private String usrName;private String usrPassword;private Integer usrRoleId;private Integer usrFlag;
// @TableField(exist = false)
// private String roleName;@TableField(exist = false)private Role role; // 角色信息public User() {}public User(String usrName, String usrPassword, int role, Integer usrFlag) {this.usrName = usrName;this.usrPassword = usrPassword;this.role = role;this.usrFlag = usrFlag;}public User get() {return new User();}
}
Role实体类:
@TableName("sys_role")
@Data
public class Role implements Serializable {@TableId(value = "role_id",type = IdType.AUTO)@TableField("role_id")private Integer roleId;@TableField("role_name")private String roleName;@TableField("role_desc")private String roleDesc;@TableField("role_flag")private Integer roleFlag;// @OneToMany(targetEntity = User.class,fetch = FetchType.EAGER,cascade = CascadeType.REMOVE,mappedBy = "role")
// private Set<User> users=new HashSet<>();public Role() {}public Role(String roleName, String roleDesc, Integer roleFlag) {this.roleName = roleName;this.roleDesc = roleDesc;this.roleFlag = roleFlag;}
}
2.2repository
repository需要提供实体相应的接口,继承JpaRepository接口即可,如果有特殊的操作,则可适当添加对应的方法。
public interface UserMapper extends JpaRepository<User, Long>,JpaSpecificationExecutor<User>{public List<User> findByUsrNameAndUsrPassword(String usrName,String usrpassword);
}public interface RoleMapper extends JpaRepository<Role, Long>{}
UserMapper除继承JpaRepository外,还继承了JpaSpecificationExecutor,用于复杂查询,具体操作在service中实现。
2.3service
service层分别使用IUserService和IRoleService
public interface UserService extends IService<User> {User login(String username, String password);int addUser(User user);int updateUser(User user);int deleteUser(int id);@Cacheable(value="user", keyGenerator = "keyGenerator")public User getUser(Long usrId);User getUserById(int id);List<User> findAllUsers();List<User> selectUserList();List<User> selectUsersPage(Integer roleId, String usrName, Integer pageNum, Integer pageSize);public interface RoleService extends IService<Role> {
}
3.实现增删改查
1.新增
@GetMapping("/add")public String addUser(Model model){List<Role> roles=roleService.list();model.addAttribute("roles",roles);return "/user/add";}@PostMapping("/save")public String saveUser(User user){int i = userService.addUser(user);if(i>0){return "redirect:/user/list";}return "/user/add";}
2.修改
@GetMapping("/edit")public String updateUser(Model model,Long usrId){List<Role> roles=roleService.list();User user = userService.getUserById(Math.toIntExact(usrId));model.addAttribute("roles",roles);model.addAttribute("user",user);return "/user/edit";}@PostMapping("/edit")public String editUser(User user){int i = userService.updateUser(user);if(i>0){return "redirect:/user/list";}return "/user/edit";}
3.删除
@PostMapping("/del/{id}")@ResponseBodypublic String deleteUser(@PathVariable Integer id){if(id==null || id==0){return "false";}int count=userService.deleteUser(id);if(count==0){return "false";}else{return "true";}
在list.html页面实现增删脚本,通过ajax实现删除:
function doDel(obj, usrId) {if (confirm("你确定需要删除该用户信息吗?")) {$.ajax({type: "POST",url: ctxPath + "user/del/" + usrId,/*data: {"usrId": usrId},*/dataType: "text",success: function (data) {// alert(JSON.stringify(data)); // {"result":"true"}if (data === "true") { // 删除成功:移除删除行alert("删除成功!");$(obj).parents("tr").remove();// window.location.href = project_name() + "/user/list";}},error: function (data) {alert("对不起,删除失败!");}});}}
4.查询
@RequestMapping("/list")public String list(Model model,Integer roleId,String usrName,@RequestParam(defaultValue = "1") Integer pageIndex){List<Role> roles=roleService.list();QueryWrapper<User> qw=new QueryWrapper<>();if(usrName!=null && !"".equals(usrName)){qw.like("usr_name",usrName);}Page<User> userPage= new Page<>(pageIndex, Constants.USER_PAGE_SIZE);IPage<User> userPager = userService.page(userPage, qw);userPager.setRecords(userService.selectUsersPage(roleId, usrName, (pageIndex-1)*Constants.USER_PAGE_SIZE, Constants.USER_PAGE_SIZE));model.addAttribute("roleId",roleId);model.addAttribute("usrName",usrName);model.addAttribute("roles",roles);model.addAttribute("userPager",userPager);return "user/list";}
4.其他功能
4.1拦截器
@Configuration
public class IndexConfig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("forward:/login");}
}
4.2Ajax
$(document).ready(function () {$.ajax({type: "GET",url: "${pageContext.request.contextPath}/role/json",dataType: "json",success: function (data) {$.each(data, function (i, tmp) {$("#roleId").append("<option value='" + tmp.roleId + "'>" + tmp.roleName + "</option>");});},error: function (data) {alert("对不起,获取数据失败!");}});});