Spring Boot创建新行而不是更新

4

这些是豆子:

@Entity
@Table(name = "bands")
public class Band implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer band_id;

@Column(name = "name")
@NotEmpty
public String name;

@Column(name = "formed")
@NotNull
public Integer formed;

@ManyToOne
@JoinColumn(name = "genre_id")
public Genre genre;

public Integer getBandId() {
    return band_id;
}

public void setBandId(Integer band_id) {
    this.band_id = band_id;
}

public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}

public Integer getFormed() {
    return this.formed;
}

public void setFormed(Integer formed) {
    this.formed = formed;
}

public Genre getGenre() {
    return genre;
}

public void setGenre(Genre genre) {
    this.genre = genre;
}

@XmlElement
public Genre getGenres() {
    Genre genre = getGenre();
    return genre;
}

}



@Entity
@Table(name = "genres")
@Access(AccessType.FIELD)
public class Genre implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer genre_id;

@Column(name = "name")
@NotEmpty
public String name;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "genre")
public Set<Band> bands;

public Integer getGenreId() {
    return genre_id;
}

public void setGenreId(Integer genre_id) {
    this.genre_id = genre_id;
}

public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}

public Set<Band> getBands() {
    return this.bands;
}

public void setBands(Set<Band> bands) {
    this.bands = bands;
}

}

这是控制器中初始化页面并调用保存操作的部分:

    @RequestMapping(value = "/bands/{band_id}/edit", method = RequestMethod.GET)
public String initUpdateBandForm(@PathVariable("band_id") int band_id, ModelMap model) {
    model.addAttribute("genres", this.bandRepository.findAllGenres());
    Band band = this.bandRepository.findById(band_id);
    model.addAttribute("band", band);
    return "bands/updateBandForm";
}

@RequestMapping(value = "bands/{band_id}/edit", method = RequestMethod.POST)
public String processUpdateBandForm(@Valid @ModelAttribute("band") Band band, BindingResult result) {
    if (result.hasErrors()) {
        return "bands/updateBandForm";
    } else {
        this.bandRepository.save(band);
        return "redirect:/bands/{band_id}";
    }
}

这是存储库保存操作:

void save(Band band);

这是updateBandForm的代码:

<form th:object="${band}" method="post">

    <label>Name</label> 
    <input type="text" th:field="*{name}" /> 

    <label>Formed</label>
    <input type="text" th:field="*{formed}" />

    <label>Genre</label>

    <select th:field="*{genre}">
        <option th:each="genre: ${genres}" th:value="${{genre}}" th:text="${genre.name}" />
    </select>

    <br>
    <button type="submit">Update Band</button>

</form>

我也使用格式化工具:

@Service
public class GenreFormatter implements Formatter<Genre> {

@Autowired
GenreRepository genreRepository;

@Override
public String print(Genre genre, Locale locale) {
    return (genre != null ? genre.getGenreId().toString() : "");
}

@Override
public Genre parse(String text, Locale locale) throws ParseException {
    Integer id = Integer.valueOf(text);
    return this.genreRepository.findById(id);
}

}

@Configuration
@EnableWebMvc
@ComponentScan(value = {"org.springframework.samples.discography.system"})
public class WebConfig extends WebMvcConfigurerAdapter {

@Autowired
private GenreFormatter genreFormatter;

@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addFormatter(genreFormatter);
}

}

控制器方法创建新行而不是更新现有行... 有人能帮忙吗?我是否漏掉了什么?
2个回答

2

您的HTML表单缺少ID信息。

@ModelAttribute 将创建一个 Band 对象,其中包含由HTML表单发送的请求参数中找到的数据。

由于您的表单仅具有 nameformedgenre,因此在 processUpdateBandForm 中的 Band 对象具有未初始化的 band_id 字段,导致在 save 上创建新的 Band

请在您的表单中添加ID信息以解决此问题。

<input type="hidden" th:field="*{bandId}" /> 

谢谢您的回答,不幸的是我现在遇到了这个错误:org.springframework.beans.NotReadablePropertyException: Invalid property 'band_id' of bean class [org.springframework.samples.discography.band.Band]: Bean property 'band_id' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? - Mehrunes Dagon
你的 Band Java bean 的 getter 和 setter 是错误的。将字段更改为 bandId 或修复你的 getter/setter 为 getBand_idsetBand_id(如果你选择后者,请在 Thymeleaf 中将输入更改为 "*{band_id}")。 - kagmole
没问题,我很乐意。 :^) - kagmole

0
在你的 processUpdateBandForm 函数中,首先需要从数据库中获取乐队对象,然后再进行更新。目前你只是添加了一个新对象,所以框架认为它是一个新对象。
public String processUpdateBandForm(@Valid @ModelAttribute("band") Band band, BindingResult result) {

   Band bandFromDb = this.bandRepository.findById(band.getBandId);
   //compare band and bandFromDb and update fields from band to bandFromDb.  
  //Dont change the id field which is band_id(this will create new object)
   this.bandRepository.save(bandFromDb)
}

这里的问题是band.getBandId()返回了null。 - Mehrunes Dagon
是的,因为在这种情况下Id是自动生成的。所以在这种情况下,您需要使用其他唯一键搜索数据库。 - pvpkiran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接