我使用Postman发送一个带有一些值的POST请求(我放了两个字符串,一个是用户名,另一个是邮件),但所有数据都保存到第一列(“用户名”)。我做错了什么?
我试过了。
{
"username": "mm46676",
"mail": "[email protected]"
}
字符串
我希望mm46676保存在用户名列中,email protected(https://stackoverflow.com/cdn-cgi/l/email-protection)保存在邮件列中。我使用H2控制台查看它是如何保存在db.
中的
EmployeeController.java
import com.incompatibleTypes.plancation.plancationapp.model.Employee;
import com.incompatibleTypes.plancation.plancationapp.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping(path = "/employee")
public class EmployeeController {
private final EmployeeRepository employeeRepository;
public EmployeeController(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
@GetMapping("/all")
public @ResponseBody Iterable<Employee> showAllEmployees(){
return employeeRepository.findAll();
}
@PostMapping(path = "/add")
public @ResponseBody String addNewEmployee (@RequestBody String username, String mail){
Employee employee = new Employee();
employee.setUsername(username);
employee.setMail(mail);
employeeRepository.save(employee);
return "Employee Saved!";
}
}
型
员工模型(如果它能以任何方式提供帮助)
package com.incompatibleTypes.plancation.plancationapp.model;
import jakarta.persistence.*;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@Data
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
private Role role;
@Column(name = "username")
private String username;
@Column(name = "mail")
private String mail;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Department department;
@ManyToOne
@JoinColumn(name = "minimal_vacation_day_id")
private VacationDay minimalVacationDay;
@ManyToMany
@JoinTable(
name = "employee_bonusvacdays",
joinColumns = @JoinColumn(name = "bonus_vacation_day_id"),
inverseJoinColumns = @JoinColumn(name = "employee_id")
)
private Set<BonusVacationDay> bonusVacationDays = new HashSet<>();
private LocalDateTime dateEmployed;
}
型
2条答案
按热度按时间wlzqhblo1#
代码中的问题是当将请求体作为方法参数传递时。使用以下代码:
字符串
整个JSON主体作为String传递给变量
username
。您应该传递一个带有字段username
和mail
的对象。这可以是实体或-甚至更好-专用POJO又名DTO。类似于以下内容:型
8dtrkrch2#
你在控制器中使用
@RequestBody
和String,在这种情况下,你的输入变成了一个字符串。试着像这样替换:字符串
祝你好运!