如何在不插入新对象的情况下从数据库更新对象?

Posted

技术标签:

【中文标题】如何在不插入新对象的情况下从数据库更新对象?【英文标题】:How can I update object from database without inserting new? 【发布时间】:2021-04-28 02:38:14 【问题描述】:

我想从我的数据库中更新对象而不向数据库插入新对象。

这里有两种方法:

@RequestMapping("/edit/id")
    public ModelAndView showEditProductPage(@PathVariable(name = "id") Integer id, Model model) 

        ModelAndView modelAndView = new ModelAndView("edit_customer");

        Customer customer = customerService.getCustomer(id);
        //Customer customer = customerRepository.getOne(id);
        //customer.setCustomerId(customerRepository.getOne(id).getCustomerId());
        System.out.println(customer.getCustomerId());
        System.out.println(customer.toString());
        model.addAttribute("customer", customer);
        modelAndView.addObject("customer", customer);
        return modelAndView;
    

输出为:id=1 Customerid=1, firstName='Krzysztof', address='ulica 1', phoneNumber='123456789'

@RequestMapping("/update/id")
    public String updateCustomer(@PathVariable(name = "id") Integer id,
                                 @ModelAttribute("customer") Customer customer)
        //System.out.println(id);
        //customer.setCustomerId(id);
        System.out.println("____________________");
        System.out.println("customer id " + customer.getCustomerId());
        System.out.println("____________________");
        customer.setCustomerId(id);
        System.out.println("customer id " + customer.getCustomerId());
        System.out.println("owner " + customer.getOwner());
        System.out.println("address " + customer.getAddress());
        System.out.println("phone number " + customer.getAddress());
        System.out.println("to string: " + customer.toString());
        System.out.println("id " + id);
        customerService.save(customer);

        return "redirect:/";
    

第二种方法后的输出是:id=1 Customerid=null, firstName='Krzysztof', address='ulica 1zzz', phoneNumber='123456789'

客户存储库扩展了 JPA 存储库, 保存方法:

public void save(Customer customer) 
        customerRepository.save(customer);
    

百里香模板:

!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8" />
    <title>Edit Customer</title>
    <link rel="stylesheet" type="text/css" th:href="@/table.css" />
</head>
<body>
<div align="center">
    <h1>Edit Customer</h1>
    <a href="/">Go Back</a>
    <br />
    <form action="#" th:action="@'/update/' + $id" th:object="$customer"
          method="post">
        <table border="0" cellpadding="10">
            <tr>
                <td>Customer ID:</td>
                <td>
                    <input type="text" th:field="*customerId" readonly="readonly" />
                </td>
            </tr>
            <tr>
                <td>First Name:</td>
                <td>
                    <input type="text" th:field="*owner" />
                </td>
            </tr>
            <tr>
                <td>Address:</td>
                <td><input type="text" th:field="*address" /></td>
            </tr>
            <tr>
                <td>Phone Number:</td>
                <td><input type="text" th:field="*phoneNumber" /></td>
            </tr>
            <tr>
                <td colspan="2"><button type="submit">Save</button> </td>
            </tr>
        </table>
    </form>
</div>
</body>
</html>

客户实体类:

package com.praca.manager.entity;

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

@Entity
@Table(name = "customer")
public class Customer 

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer customerId;

    @Column(name = "owner")
    private String owner;

    @Column(name = "address")
    private String address;

    @Column(name = "phone_number")
    private String phoneNumber;

    @OneToMany(mappedBy = "customer")
    List<Details> details;

    public Customer()
    

    public Customer(Integer customerId,
                    String owner,
                    String address,
                    String phoneNumber)
                        this.customerId = customerId;
                        this.owner = owner;
                        this.address = address;
                        this.phoneNumber = phoneNumber;
    

    public Integer getCustomerId() 

        return customerId;
    

    public void setCustomerId(Integer id)

        this.customerId = customerId;
    

    public String getOwner() 

        return owner;
    

    public void setOwner(String firstName) 

        this.owner = firstName;
    

    public String getAddress() 

        return address;
    

    public void setAddress(String address)

        this.address = address;
    

    public String getPhoneNumber() 

        return phoneNumber;
    

    public void setPhoneNumber(String phoneNumber) 

        this.phoneNumber = phoneNumber;
    

    @Override
    public String toString() 
        return "Customer" +
                "id=" + customerId +
                ", firstName='" + owner + '\'' +
                ", address='" + address + '\'' +
                ", phoneNumber='" + phoneNumber + '\'' +
                '';
    

这里的 ID 字段也是 '1' sql脚本:

create table customer(
customer_id int auto_increment primary key not null,
owner varchar(200) not null,
address varchar(200) not null,
phone_number int not null
);

尽管我尝试将 id 设置为 1 或任何其他数字,但它仍然为空。 谁能告诉我为什么以及如何解决它?

【问题讨论】:

发布你的Customer实体类 我怀疑你的 id 生成策略有问题,我猜你的 id 不是 autoincrement 贴在原帖底部 它是自增的,我一会儿用sql编辑帖子 设置这个:@GeneratedValue(strategy = GenerationType.AUTO) 【参考方案1】:

问题出在 Customer 类的设置器中:

public void setCustomerId(Integer id)

    this.customerId = customerId;

您将该字段分配给它自己,这就是它始终为空的原因。应该是“this.customerId = id”:)。

【讨论】:

以上是关于如何在不插入新对象的情况下从数据库更新对象?的主要内容,如果未能解决你的问题,请参考以下文章

如何在不阻塞的情况下从 Spring Webflux 中的 Mono 对象中提取数据?

如何在不指定列名的情况下从另一个表更新一个表?

如何在不为每个帖子调用评论对象的情况下从墙上的帖子中获取评论计数?

如何在不使用 for 循环的情况下从 appsettings 文件中读取对象数组中特定键的值

子组件如何在不监听生命周期方法的情况下从父组件接收 props?

如何让 Json.Net 在不忽略子属性的情况下从 documentDB 序列化/反序列化动态/通用对象?