在ModelAttribute模型中接收到的是更新现有数据库记录,而不是创建新记录

时间:2019-02-02 20:16:26

标签: java spring hibernate spring-boot thymeleaf

为什么AgentController代码更新现有记录而不是创建新记录,但是CountryController中的相同代码可以正常工作?

国家管制员:

@GetMapping("/country/add")
public String addNewCountry(Model model){
    model.addAttribute("country", new Country());
    return "country/add";
}

@PostMapping("/country")
public String createCountry(@ModelAttribute Country country){
    countriesRepository.save(country);
    return "redirect:/countries";
}

国家HTML形式:

    <form action="#" th:action="@{/country}" th:object="${country}" method="post">
        <p>Name: <input type="text" th:field="*{name}" /></p>
        <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>

代理HTML形式:

    <form action="#" th:action="@{'/country/{id}/agents/new'(id=${country_id})}" th:object="${agent}" method="post">
        <p>Name: <input type="text" th:field="*{first_name}" /></p>
        <p>Surname: <input type="text" th:field="*{last_name}"></p>
        <p>Documents: <input type="text" th:field="*{documents}" /></p>
        <p>People recruited: <input type="text" th:field="*{people_recruited}"></p>
        <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>

代理控制器:

@GetMapping("/country/{id}/agent/add")
public String addNewAgent(@PathVariable(name = "id") String countryId, Model model){
    model.addAttribute("country_id", countryId);
    model.addAttribute("agent", new Agent());
    return "agent/add";
}

@PostMapping("/country/{id}/agents/new")
public String createAgent(@PathVariable(value = "id") String countryId, @ModelAttribute Agent agent){
    // Here i have one to many relation(one country many agents)
    return countriesRepository.findById(Long.parseLong(countryId)).map(country -> {
        agent.setCountry(country);
        agentsRepository.save(agent);
        return "redirect:/country/" + countryId + "/show/agents";
    }).orElseThrow(() -> new ResourceNotFoundException("CountryId " + countryId + " not found"));
}

UPD: 如果我创建第一个座席并将其删除,则下一个创建操作将正常进行。

代理类

@Entity
@Table(name = "agents")
public class Agent implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
private String status = "classified";

@NotNull
private String first_name;

@NotNull
private String last_name;

@NotNull
@Max(value = 2147483647)
private Integer documents;

@NotNull
@Max(value = 8)
private Integer people_recruited;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "country_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private Country country;

0 个答案:

没有答案