Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package com.example.springbook.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.springbook.model.Buku;
import com.example.springbook.repository.BukuRepository;
@RestController
@RequestMapping("/buku")
public class BukuController {
@Autowired
BukuRepository bukuRepository;
@GetMapping("/")
public List<Buku> getAll(){
return bukuRepository.findAll();
}
@PostMapping("/")
public Buku tambahbuku(@Valid @RequestBody Buku buku) {
return bukuRepository.save(buku);
}
@PutMapping("/{id}")
public ResponseEntity<Buku> updateBuku(@PathVariable(value="id")Long id,
@Valid @RequestBody Buku detailbuku){
Buku buku = bukuRepository.findOne(id);
if(buku == null)
return ResponseEntity.notFound().build();
buku.setTitleBook(detailbuku.getTitleBook());
buku.setNamaDepanPengarang(detailbuku.getNamaDepanPengarang());
buku.setNamaBelakangPengarang(detailbuku.getNamaBelakangPengarang());
buku.setNamaPeminjam(detailbuku.getNamaPeminjam());
buku.setStatusPeminjaman(detailbuku.getStatusPeminjaman());
Buku updatedBuku = bukuRepository.save(buku);
return ResponseEntity.ok(updatedBuku);
}
@DeleteMapping("/{id}")
public String deleteBuku(@PathVariable (value="id") Long id){
Buku buku = bukuRepository.findOne(id);
String result = "";
if(buku == null) {
result = "id "+id+" tidak ditemukan";
return result;
}
result = "id "+id+" berhasil di hapus";
bukuRepository.delete(id);
return result;
}
@GetMapping("/{id}")
public ResponseEntity<Buku> getBukuById(@PathVariable(value="id") Long id){
Buku buku = bukuRepository.findOne(id);
if(buku == null)
return ResponseEntity.notFound().build();
return ResponseEntity.ok().body(buku);
}
@GetMapping("/sortbuku")
public List<Buku> sortbuku(@RequestParam(value="title")String titleBook){
return bukuRepository.findByTitleBook(titleBook);
}
@GetMapping("/sortstatus/{statusPeminjaman}")
public List<Buku> sortstatus(@PathVariable(value="statusPeminjaman") int statusPeminjaman){
return bukuRepository.findByStatusPeminjaman(statusPeminjaman);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.