Springboot2+jpa+thymeleaf如何实现增删改查

这篇文章主要讲解了Spring boot2+jpa+thymeleaf如何实现增删改查,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

创新互联长期为千余家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为魏县企业提供专业的成都做网站、网站制作、成都外贸网站建设魏县网站改版等技术服务。拥有10余年丰富建站经验和众多成功案例,为您定制开发。

一、pom.xml引入相关模块web、jpa、thymeleaf、oracle:


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

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

     
      com.oracle 
      ojdbc8 
      12.2.0.1     
    

二、application.properties配置

server.port = 9001

spring.datasource.driver-class-name = oracle.jdbc.driver.OracleDriver
spring.datasource.url = jdbc:oracle:thin:@127.0.0.1:1521:testdb
spring.datasource.username = dev
spring.datasource.password = dev

spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql = true

spring.thymeleaf.cache = false

说明:

1、由于本机的8080已经被使用,修改一下端口号为9001。

2、hibernate.hbm2ddl.auto参数有四个值:

create: 每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要
这样执行,这就是导致数据库表数据丢失的一个重要原因。

create-drop :每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。

update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载
hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。
validate :每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

3、show-sql 是否打印出自动生产的SQL,方便调试的时候查看

4、propertiesspring.thymeleaf.cache=false是关闭thymeleaf的缓存,不然在开发过程中修改页面不会立刻生效需要重启,生产
可配置为true。

三、启动类需要添加Servlet的支持

package com.example.demo;

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

  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(DemoApplication.class);
  }
  
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

四、数据库层代码

1、实体类映射数据库表

package com.example.demo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;

import org.hibernate.validator.constraints.Length;

@Entity
@Table(name = "userinfo")
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;

  //必须有构造
   public User() {
   }
     
  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;
  }
}

2、继承JpaRepository类会自动实现很多内置的方法

package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.User;

public interface UserRepository extends JpaRepository {
  User findById(long id);
  void deleteById(Long id);
}

五、业务层

service调用jpa实现相关的增删改查,实际项目中service层处理具体的业务代码。

1、UserService.java

package com.example.demo.service;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.example.demo.entity.User;
public interface UserService {
  
  public Page getUserPage(Pageable pageable);  
  public List getUserList();
  public User findUserById(long id);
  public void save(User user);
  public void edit(User user);
  public void delete(long id);
}

2、UserServiceImpl.java

package com.example.demo.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;

@Service
public class UserServiceImpl implements UserService {
  
  @Autowired
  private UserRepository userRepository;

  @Override
  public Page getUserPage(Pageable pageable) {
    return userRepository.findAll(pageable);
  }
  
  @Override
  public List getUserList() {
    return userRepository.findAll();
  }

  @Override
  public User findUserById(long id) {
    return userRepository.findById(id) ;
  }

  @Override
  public void save(User user) {
    userRepository.save(user);
  }

  @Override
  public void edit(User user) {
    userRepository.save(user);
  }

  @Override
  public void delete(long id) {
    userRepository.deleteById(id);
  }

}

六、控制层

package com.example.demo.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

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.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;

@Controller
public class UserController {
  
  @Resource
  UserService userService;

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

  @RequestMapping("/list")
  public String list(Model model) {
    List users=userService.getUserList();
    model.addAttribute("users", users);
    
    /*int page=1,size=2;
    Sort sort = new Sort(Direction.DESC, "id");
    Pageable pageable = PageRequest.of(page, size, sort);
    model.addAttribute("users", pageable);*/
    
    return "user/list";
  }

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

  @RequestMapping("/add")
  public @ResponseBody User add(@Valid User user, BindingResult result) {
    if (result.hasErrors()) {
      List list = result.getAllErrors();
      for (ObjectError error : list) {
        System.out.println(error.getDefaultMessage());
      }
      return null;
    }
    userService.save(user);
    return user;    
  }

  @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";
  }
}

七、页面

1、列表页 list.hmtl




  
  userList
  



用户列表



# User Name Password Age Edit Delete
1 neo Otto 6 edit delete
add

Spring boot2+jpa+thymeleaf如何实现增删改查

2、新增页 userAdd.html




  
  user
  



添加用户



     

Spring boot2+jpa+thymeleaf如何实现增删改查

3、修改页 userEdit.html




  
  user
  



修改用户



      Back

看完上述内容,是不是对Spring boot2+jpa+thymeleaf如何实现增删改查有进一步的了解,如果还想学习更多内容,欢迎关注创新互联行业资讯频道。


文章名称:Springboot2+jpa+thymeleaf如何实现增删改查
网站地址:http://pwwzsj.com/article/pcjjpj.html