spring-boot JPA快速入门完整代码

spring-boot jpa 使用快速入门

项目结构

spring-boot JPA快速入门完整代码_第1张图片
image.png

pom文件



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.1.RELEASE
         
    
    com.toolz
    myuser
    0.0.1-SNAPSHOT
    myuser
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-data-jpa
        

        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

        
            mysql
            mysql-connector-java
        

        
            org.apache.commons
            commons-lang3
            3.6
        

        
            org.springframework.boot
            spring-boot-devtools
            true
        

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

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



实体类entity代码

package com.toolz.myuser.entity;

import org.apache.commons.lang3.builder.ToStringBuilder;

import javax.persistence.*;
import java.util.Date;

@Entity
public class Userinfo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(nullable = false, unique = true)
    private String userName;

    @Column(nullable = false)
    private String pwd;

    @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 getPwd(){
        return pwd;
    }

    public void setPwd(String pwd){
        this.pwd = pwd;
    }
    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);
    }
}

Application类

package com.toolz.myuser;

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 MyuserApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(MyuserApplication.class);
    }

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

}

Controller

package com.toolz.myuser.controller;

import com.toolz.myuser.entity.Userinfo;
import com.toolz.myuser.param.UserParam;
import com.toolz.myuser.repository.UserRepository;
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 java.util.Date;
import java.util.List;


@Controller
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @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 = "10") Integer size){
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(page, size);
        Page userList = userRepository.findList(pageable);
        model.addAttribute("users",userList);
        return "user/list";
    }

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

    @RequestMapping("/add")
    public String add(UserParam userParam, BindingResult result, ModelMap model)
    {
        String errorMsg = "";
        if (result.hasErrors())
        {
            List list = result.getAllErrors();
            for (ObjectError e: list){
                errorMsg = errorMsg + e.getCode() + ":" + e.getDefaultMessage();
            }
            model.addAttribute("errorMsg", errorMsg);
            return "user/userAdd";
        }
        Userinfo u = userRepository.findByUserName(userParam.getUserName());
        if(u!=null)
        {
            model.addAttribute("errorMsg", "用户名已存在");
            return "user/userAdd";
        }
        Userinfo user = new Userinfo();
        BeanUtils.copyProperties(userParam, user);
        user.setRegTime(new Date());
        userRepository.save(user);
        return "redirect:/list";
    }

    @RequestMapping("/delete")
    public String del(Long id){
        userRepository.deleteById(id);
        return "redirect:/list";
    }

    @RequestMapping("toEdit")
    public String edit(Long id){

        return "user/userAdd";
    }
}

DAO

package com.toolz.myuser.repository;

import com.toolz.myuser.entity.Userinfo;
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.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import javax.transaction.Transactional;
import java.util.Optional;


public interface UserRepository extends JpaRepository {

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

    @Override
    Optional findById(Long id);

    // 简单自定义查询
    Userinfo findByUserName(String userName);

    void deleteById(Long id);

    @Modifying
    @Transactional
    @Query(value ="delete from Userinfo u where u.userName = ?1")
    void deleteByUserName(String userName);

}

Param

package com.toolz.myuser.param;

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

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;

public class UserParam {

    private long id;

    @NotEmpty(message = "用户名不能为空")
    private String userName;

    @NotEmpty(message = "用户名不能为空")
    @Length(message = "密码长度不能少于6位")
    private String pwd;

    @Max(value = 100, message = "年龄不能大于100")
    @Min(value = 1, message = "年龄必须大于1")
    private int age;

    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 getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public int getAge() {
        return age;
    }

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

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

重写的启动类

package com.toolz.myuser;

import com.toolz.myuser.entity.Userinfo;
import com.toolz.myuser.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.util.Date;

@Profile(value = "dev")
@Component
public class MyStartupRunner implements CommandLineRunner {
    @Autowired
    private UserRepository userRepository;

    private String addUser(Userinfo user){
        String name = "zhangsan";
        String pwd = "abc";
        int age = 18;

        Userinfo u = userRepository.findByUserName(name);
        if(u!=null)
        {
            System.out.println("该用户已存在");
            userRepository.deleteByUserName(name);
            System.out.println("该用户已被清除");
        }

        user.setUserName(name);
        user.setPwd(pwd);
        user.setAge(age);
        user.setRegTime(new Date());
        userRepository.save(user);
        return  "用户保存成功";

    }

    public void run(String... strings) throws Exception {
        System.out.println("项目启动了!!!!!!!!!!!!!!!!!!!!!!");

        System.out.println("开始添加用户");
        String res = addUser(new Userinfo());
        System.out.println(res);
    }
}

配置文件
application.properties


# 自动创建/更新/验证数据库表结构
spring.jpa.properties.hibernate.hbm2ddl.auto = update
# 设置数据库引擎为innodb
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# 终端输出sql语句
spring.jpa.show-sql=true

# 开发为false
spring.thymeleaf.cache=false

#server.port=8080

spring.profiles.active=dev

application-dev.properties

spring.datasource.url = jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

server.port=8081

list.html




    
    用户列表
    



    

用户列表


ID 用户名 密码 年龄 注册时间 Edit Delete
1111 Wayne abcabcabc 120 2018/12/27 编辑 删除

userAdd.html




    
    添加用户
    


    

添加用户


你可能感兴趣的:(spring-boot JPA快速入门完整代码)