Spring启动会创建新行而不是更新

时间:2017-06-02 13:34:41

标签: java spring spring-boot spring-data-jpa thymeleaf

Theese是豆子:

@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 个答案:

答案 0 :(得分:0)

您的HTML表单没有ID信息。

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

由于您的表单只有nameformedgenre,因此Band内的processUpdateBandForm对象有一个未初始化的band_id字段,结果在Band上创建新的save

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

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

答案 1 :(得分:0)

首先,在您的processUpdateBandForm函数中,您需要首先从Db获取band对象,然后更新它。现在你只是添加一个新对象。所以框架认为它是一个新的对象。

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)
}
相关问题