Spring Boot2.0系列教程之 JPA 和 Thymeleaf 实践(五)

前面几篇文章学习了 Spring Boot Web 开发、JPA 操作数据库、Thymeleaf 和页面的交互的技术。这节课程就综合使用前几节的课程内容,来做一个用户的管理功能,包括展示用户列表(分页),添加用户、修改用户、删除用户。有人说程序员的一生都是在增删改查,这句话不一定全对,但也有一定的道理,相比于这句话,我更认同的是这句:程序员的技术学习都是从增删改查开始的。

这篇文章介绍如何使用 JPA 和 Thymeleaf 做一个用户管理功能。

 

注:第一部分为代码,第二部分为增删改查操作的截图,完整代码可在github下载。

github地址:https://github.com/zjh746140129/Spring-Boot2.0

项目结构截图:

Spring Boot2.0系列教程之 JPA 和 Thymeleaf 实践(五)_第1张图片

一、代码片段

1、编写用户类

package com.boot.model;



import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;

/**
 * @Description: 用户类
 * @Author: zhoujh
 * @CreateDate: 2018/6/17$ 上午11:18$
 * @Version: 1.0
 */
@Entity
public class User {
    @Id
    @GeneratedValue
    private long id;
    @Column(nullable = false, unique = true)
    @NotEmpty(message="姓名不能为空")
    private String userName;
    @Column(nullable = false)
    @NotEmpty(message="密码不能为空")
    @Length(min=6,message="密码长度不能小于6位")
    private String passWord;
    @Column(nullable = false)
    private int age;
    @Column(nullable = false)
    private Date regTime;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getRegTime() {
        return regTime;
    }

    public void setRegTime(Date regTime) {
        this.regTime = regTime;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

2、编写service

package com.boot.service;

import com.boot.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

/**
 * @Description: 接口
 * @Author: zhoujh
 * @CreateDate: 2018/6/17$ 上午11:27$
 * @Version: 1.0
 */
public interface UserService extends JpaRepository{

    @Query("select u from User u")
    Page findList(Pageable pageable);

    User findUserById(long id);

    User findByUserName(String userName);

    void deleteUserById(Long id);
}

3、编写controller

package com.boot.controller;


import com.boot.model.User;
import com.boot.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Description: controller
 * @Author: zhoujh
 * @CreateDate: 2018/6/17$ 上午11:35$
 * @Version: 1.0
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public String index() {
        return "redirect:/list";
    }

    @RequestMapping("/list")
    public String list(Model model,@RequestParam(value = "page", defaultValue = "0") Integer page,
                       @RequestParam(value = "size", defaultValue = "6") Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(page, size, sort);
        Page users=userService.findList(pageable);
        model.addAttribute("users", users);
        return "user/list";
    }

    @RequestMapping("/toAdd")
    public String toAdd() {
        return "user/userAdd";
    }

    @RequestMapping("/add")
    public String add(@Valid User userParam,BindingResult result, ModelMap model) {
        String errorMsg="";
        if(result.hasErrors()) {
            List list = result.getAllErrors();
            for (ObjectError error : list) {
                errorMsg=errorMsg + error.getCode() + "-" + error.getDefaultMessage() +";";
            }
            model.addAttribute("errorMsg",errorMsg);
            return "user/userAdd";
        }
        User u= userService.findByUserName(userParam.getUserName());
        if(u!=null){
            model.addAttribute("errorMsg","用户已存在!");
            return "user/userAdd";
        }
        User user=new User();
        BeanUtils.copyProperties(userParam,user);
        user.setRegTime(new Date());
        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(@Valid User userParam, BindingResult result,ModelMap model) {
        String errorMsg="";
        if(result.hasErrors()) {
            List list = result.getAllErrors();
            for (ObjectError error : list) {
                errorMsg=errorMsg + error.getCode() + "-" + error.getDefaultMessage() +";";
            }
            model.addAttribute("errorMsg",errorMsg);
            model.addAttribute("user", userParam);
            return "user/userEdit";
        }

        User user=new User();
        BeanUtils.copyProperties(userParam,user);
        user.setRegTime(new Date());
        userService.save(user);
        return "redirect:/list";
    }

    @RequestMapping("/delete")
    public String delete(Long id) {
        userService.deleteUserById(id);
        return "redirect:/list";
    }
}

4、启动类

package com.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BootthymeleafApplication {

	public static void main(String[] args) {
		SpringApplication.run(BootthymeleafApplication.class, args);
	}
}

 

5、配置文件

Spring.datasource.url=jdbc:mysql://localhost:3306/school_score
Spring.datasource.username=root
Spring.datasource.password=root
Spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Spring.jpa.properties.hibernate.hbm2ddl.auto=update
Spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
Spring.jpa.show-sql= true
server.port=8089

6、pom.xml



	4.0.0

	com.boot
	bootthymeleaf
	0.0.1-SNAPSHOT
	jar

	bootthymeleaf
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.2.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-data-jpa
		
		
			mysql
			mysql-connector-java
		
		
			org.springframework.boot
			spring-boot-starter-thymeleaf
		

		
			org.apache.commons
			commons-lang3
			3.6
		
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	



二、演示增删改查

1、访问 http://localhost:8089/   可以进行CRUD操作

Spring Boot2.0系列教程之 JPA 和 Thymeleaf 实践(五)_第2张图片

2、修改

Spring Boot2.0系列教程之 JPA 和 Thymeleaf 实践(五)_第3张图片

3、 新增

Spring Boot2.0系列教程之 JPA 和 Thymeleaf 实践(五)_第4张图片

 

好了,到这里 使用JPA 和 Thymeleaf完成一个简单到用户管理就完成了,读者在实践过程中有问题,评论私信即可,回第一时间回复。

你可能感兴趣的:(Spring,Boot,Spring,Boot2.0系列教程)