[英]How to update record in spring boot application?
我正在尝试更新 spring 启动应用程序中的记录,但它添加了新记录而不是更新,我也想搜索
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Transient;
@Entity
public class Events {
private Long id;
private String game;
private String catergory;
private String venue;
private float entrance_fee;
private String date;
private String time;
private Timestamp created_time;
private String image;
public Events() {
super();
// TODO Auto-generated constructor stub
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getGame() {
return game;
}
public void setGame(String game) {
this.game = game;
}
public String getCatergory() {
return catergory;
}
public void setCatergory(String catergory) {
this.catergory = catergory;
}
public String getVenue() {
return venue;
}
public void setVenue(String venue) {
this.venue = venue;
}
public float getEntrance_fee() {
return entrance_fee;
}
public void setEntrance_fee(float entrance_fee) {
this.entrance_fee = entrance_fee;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Timestamp getCreated_time() {
return created_time;
}
public void setCreated_time(Timestamp created_time) {
this.created_time = created_time;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Transient
public String getImagePath() {
if(image == null || id == null) return null;
return "/event-images/" + id + "/" + image;
}
}
这是我的存储库...
import java.util.List;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EventsRepository extends PagingAndSortingRepository<Events, Long> {
List<Events> findByCatergoryLike(String catergory);
}
这是我的服务..
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
@Service
public class EventsService {
@Autowired
private EventsRepository eventsRepository;
public Page<Events> listAll(int pageNumber){
Sort sort = Sort.by("date").ascending();
Pageable pageable = PageRequest.of(pageNumber -1, 1, sort);
return eventsRepository.findAll(pageable);
}
public Events save(Events events) {
return eventsRepository.save(events);
}
public void update(Events events) {
eventsRepository.save(events);
}
public Events get(Long id) {
return eventsRepository.findById(id).get();
}
public void delete(Long id) {
eventsRepository.deleteById(id);
}
public List<Events> findBycatergory(String catergory) {
return eventsRepository.findByCatergoryLike("%"+catergory+"%");
}
}
这是controller中的更新方法..
@RequestMapping(value = { "/update_event" }, method = RequestMethod.POST)
public String upadate(@ModelAttribute("events") @PathVariable(name="id") Long id, Events events,
@RequestParam("fileImage") MultipartFile multipartFile) throws IOException {
String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
events.setImage(fileName);
eventsService.update(events);
String uploadDir = "./event-images/" + events.getId();
Path uploadPath = Paths.get(uploadDir);
if(!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = multipartFile.getInputStream()){
Path filePath = uploadPath.resolve(fileName);
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
}catch (IOException e) {
throw new IOException("Could not save uploaded file: " + fileName);
}
if(fileName.length()>1048576) {
System.out.println("file too large");
}
return "redirect:/events";
}
然后最后更新表格..
<form action="#" th:action="@{/update_event}" th:object="${Edit_events}" method="post"
enctype="multipart/form-data">
<div id="name">
<h2 class="name">Sports</h2>
<input class="firstname" type="text" th:field="*{game}" /><br>
<input class="lastname" type="text" th:field="*{catergory}" /><br>
</div>
<h2 class="name">Venue</h2>
<input class="username" type="text" th:field="*{venue}" />
<h2 class="name">Entrance Fee</h2>
<input class="email" type="text" th:field="*{entrance_fee}" />
<h2 class="name">Date & Time</h2>
<input type="date" class="password" th:field="*{date}" />
<input type="time" class="number" th:field="*{time}" /><br>
<img th:src="*{imagePath}">
<input type="file" class="photoBtn" name="fileImage" id="fileImage" accept="image/png,
image/jpeg"/> <button type="submit">SAVE CHANGES</button><a th:href="@{/events}">..DISCARD..</a>
</form>
解决方案非常简单,您需要先获取记录,然后使用 save(events) 对其进行更新 例如:在请求有效负载中,您将获得事件 class 的 object,使用eventsRepository.findById(events.id)
Z9CE3D1Z48 call to fetch the repository tofetch the repository tofetch数据然后更新返回的实例然后保存它,内部 JPA 检查条目是否已注册。 如果是,那么它将更新,否则它将创建一个新条目。
` Optinal<Events>currentEvent = eventsRepository.findById(events.id); if(currentEvent.isPresent()){// map the input values with currentEventusing mapper eventsRepository.save(events) }`
希望这有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.