SpringBoot用户CRUD

本文介绍了一个使用Spring Boot实现的简单用户管理系统。该系统包括用户实体定义、存储库接口及其实现、控制器方法等关键部分。通过具体代码展示了如何进行用户的增删查改操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.准备

http://start.spring.io/ 这里地址去直接生成你需要的项目信息,如何你本身ide以及集成了springboot 那么可以直接生成项目信息

 需要的知识:java,spring,springmvc,thymelafe

2开始

根据图片项目结构信息可以推断,我们需要写下面几个类:

 1 package com.dgw.boot.dgw.domain;
 2 
 3 /**
 4  * @author DGW-PC
 5  * @data   2018年7月17日
 6  */
 7 public class User{
 8     
 9     private Long id;
10     private String name;
11     private String email;
12     
13     public User() {
14         
15     }
16     
17     public User(Long id, String name, String email) {
18         this.id = id;
19         this.name = name;
20         this.email = email;
21     }
22 
23     @Override
24     public String toString() {
25         return "User [id=" + id + ", name=" + name + ", email=" + email + "]";
26     }
27 
28     public Long getId() {
29         return id;
30     }
31 
32     public void setId(Long id) {
33         this.id = id;
34     }
35 
36     public String getName() {
37         return name;
38     }
39 
40     public void setName(String name) {
41         this.name = name;
42     }
43 
44     public String getEmail() {
45         return email;
46     }
47 
48     public void setEmail(String email) {
49         this.email = email;
50     }
51 }    

 

Dao beans

public interface UserRepository {
    
    User savaOrUpdateUser(User user);
    
    void deleteUser(long id);
    
    User getUserById(long id);
    
    List<User> listUsre();
    

}

@Repository
public class UserRepositoryImpl implements UserRepository {

    private static AtomicLong count=new AtomicLong();
    private ConcurrentMap<Long, User> useMap=new ConcurrentHashMap<>();
    
    @Override
    public User savaOrUpdateUser(User user) {
        Long id = user.getId();
        if(id==null) {
            id=count.incrementAndGet();
            user.setId(id);
        }
        this.useMap.put(id, user);
        return user;
    }

    @Override
    public void deleteUser(long id) {
        this.useMap.remove(id);
    }

    @Override
    public User getUserById(long id) {
        return this.useMap.get(id);
    }

    @Override
    public List<User> listUsre() {
        return new ArrayList<>(this.useMap.values());
    }

}

 控制器:

 1 /**
 2      * 从 用户存储库 获取用户列表
 3      * @return
 4      */
 5     private List<User> getUserlist() {
 6          return userRepository.listUser();
 7     }
 8 
 9     /**
10      * 查询所用用户
11      * @return
12      */
13     @GetMapping
14     public ModelAndView list(Model model) {
15         model.addAttribute("userList", getUserlist());
16         model.addAttribute("title", "用户管理");
17         return new ModelAndView("users/list", "userModel", model);
18     }
19  
20     /**
21      * 根据id查询用户
22      * @param message
23      * @return
24      */
25     @GetMapping("{id}")
26     public ModelAndView view(@PathVariable("id") Long id, Model model) {
27         User user = userRepository.getUserById(id);
28         model.addAttribute("user", user);
29         model.addAttribute("title", "查看用户");
30         return new ModelAndView("users/view", "userModel", model);
31     }
32 
33     /**
34      * 获取 form 表单页面
35      * @param user
36      * @return
37      */
38     @GetMapping("/form")
39     public ModelAndView createForm(Model model) {
40         model.addAttribute("user", new User());
41         model.addAttribute("title", "创建用户");
42         return new ModelAndView("users/form", "userModel", model);
43     }
44 
45     /**
46      * 新建用户
47      * @param user
48      * @param result
49      * @param redirect
50      * @return
51      */
52     @PostMapping
53     public ModelAndView create(User user) {
54          user = userRepository.saveOrUpateUser(user);
55         return new ModelAndView("redirect:/users");
56     }
57 
58     /**
59      * 删除用户
60      * @param id
61      * @return
62      */
63     @GetMapping(value = "delete/{id}")
64     public ModelAndView delete(@PathVariable("id") Long id, Model model) {
65         userRepository.deleteUser(id);
66  
67         model.addAttribute("userList", getUserlist());
68         model.addAttribute("title", "删除用户");
69         return new ModelAndView("users/list", "userModel", model);
70     }
71 
72     /**
73      * 修改用户
74      * @param user
75      * @return
76      */
77     @GetMapping(value = "modify/{id}")
78     public ModelAndView modifyForm(@PathVariable("id") Long id, Model model) {
79         User user = userRepository.getUserById(id);
80  
81         model.addAttribute("user", user);
82         model.addAttribute("title", "修改用户");
83         return new ModelAndView("users/form", "userModel", model);
84     }

 

转载于:https://www.cnblogs.com/dgwblog/p/9325076.html

### Spring Boot 2 CRUD Example Tutorial #### 创建和配置Spring Boot项目 为了实现基于Spring Boot 2的CRUD操作,首先需要创建一个新的Spring Boot应用。可以利用Spring Initializr快速搭建基础环境[^1]。 ```java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这段代码初始化了整个应用程序并启动它[^2]。 #### 配置数据库连接 对于本教程而言,采用H2内存数据库作为数据存储解决方案。通过`application.properties`文件中的相应属性完成对H2数据库的支持配置: ```properties spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.h2.console.enabled=true ``` 上述设置指定了JDBC URL、驱动类名以及登录凭证等必要参数[^3]。 #### 定义实体类 接下来定义表示持久化对象的Java类——即所谓的“实体”。这里以名为`Tutorial`的例子说明如何映射到关系型表结构上: ```java @Entity @Table(name = "tutorials") public class Tutorial { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(nullable = false) private String title; @Column(nullable = true) private String description; private boolean published; // Getters and Setters... } ``` 此部分展示了怎样声明字段及其约束条件,并标注它们与表格列之间的对应关系。 #### 实现Repository接口 借助于Spring Data JPA提供的简化方式,只需继承特定类型的仓库接口即可获得基本的数据访问功能而无需编写具体逻辑: ```java @Repository public interface TutorialRepository extends JpaRepository<Tutorial, Long> { List<Tutorial> findByPublished(boolean published); Optional<Tutorial> findById(Long id); } ``` 这些方法允许按照不同标准查询记录,同时也包含了常见的增删改查行为。 #### 构建RESTful Web服务控制器 最后一步就是设计面向用户的HTTP端点,以便能够远程调用内部业务流程。下面给出了一组典型的GET/POST/PUT/DELETE请求处理函数: ```java @RestController @RequestMapping("/api/tutorials") public class TutorialController { @Autowired private TutorialRepository repository; @GetMapping("") public ResponseEntity<List<Tutorial>> getAllTutorials(@RequestParam(required = false) String title) { ... } @PostMapping("") public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial tutorial) { ... } @PutMapping("/{id}") public ResponseEntity<Tutorial> updateTutorial(@PathVariable("id") long id, @RequestBody Tutorial tutorialRequest) { ... } @DeleteMapping("/{id}") public ResponseEntity<HttpStatus> deleteTutorial(@PathVariable("id") long id) { ... } } ``` 以上片段实现了完整的资源管理生命周期控制,包括获取列表、新增实例、修改现有条目及移除指定项等功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值