Pessoal, estou tentando criar um método para editar. Tenho uma classe Nivel que é a minha entidade:
@Entity
@Table(name="niveis")
public class Nivel extends AbstractPersistable<Long> {
private static final long serialVersionUID = 1L;
@NotBlank(message="Campo obrigatório.")
@Length(min = 3, max = 50)
@Column(nullable = false, unique = true, length = 50)
private String nome;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
@Override
protected void setId(Long id) {
super.setId(id);
}}
Aqui está o Repository:
public interface NivelRepository extends JpaRepository<Nivel, Long>{
Page<Nivel> findAllByOrderByNomeAsc(Pageable pageable);
List<Nivel> findAll();
Nivel findOne(Long id);
Nivel findByNome(String nome);
@Modifying
@Query("update Nivel n set n.nome = ?1 where n.id = ?2")
void updateNome(String nome, Long id);
}
O service ficou assim:
@Service
@Transactional(readOnly=true, propagation =
Propagation.REQUIRED)public class NivelService {
@Autowired
private NivelRepository repository;
public Page<Nivel> findByPagination(int page, int size) {
Pageable pageable = new PageRequest(page, size);
return repository.findAllByOrderByNomeAsc(pageable);
}
public List<Nivel> findAll() {
return repository.findAll();
}
public Nivel findByNome(String nome) {
return repository.findByNome(nome);
}
public Nivel findById(Long id) {
return repository.findOne(id);
}
@Transactional(readOnly = false)
public void delete(Long id) {
repository.delete(id);
}
@Transactional(readOnly = false)
public void saveOrUpdate(Nivel nivel) {
if (nivel.getId() == null) {
save(nivel);
} else {
update(nivel);
}
}
private void update(Nivel nivel) {
Nivel persistente = repository.findOne(nivel.getId());
if (!persistente.getNome().equals(nivel.getNome())) {
persistente.setNome(nivel.getNome());
}
repository.save(persistente);
}
private void save (Nivel nivel) {
repository.save(nivel);
}
}
O meu controller ficou desta forma:
@Controller
@RequestMapping(value="nivel")
public class NivelController {
@Autowired
private NivelService nivelService;
@RequestMapping(value = "/page/{page}", method = RequestMethod.GET)
public ModelAndView pageNiveis(@PathVariable("page") Integer pagina) {
ModelAndView view = new ModelAndView("nivel/list");
Page<Nivel> page = nivelService.findByPagination(pagina - 1, 5);
view.addObject("page", page);
view.addObject("urlPagination", "/nivel/page");
return view;
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String delete(@PathVariable("id") Long id) {
nivelService.delete(id);
return "redirect:/nivel/add";
}
@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
public ModelAndView preUpdate(@PathVariable("id") Long id, ModelMap model) {
Nivel nivel = nivelService.findById(id);
model.addAttribute("nivel", nivel);
return new ModelAndView("/nivel/cadastro", model);
}
@RequestMapping(value="/update", method=RequestMethod.POST)
public ModelAndView update(@Valid @ModelAttribute("nivel") Nivel nivel, BindingResult result, RedirectAttributes attr) {
if (result.hasErrors()) {
return new ModelAndView("/nivel/cadastro");
}
nivelService.saveOrUpdate(nivel);
attr.addFlashAttribute("message", "Nível alterado com sucesso.");
return new ModelAndView("redirect:/nivel/list");
}
@RequestMapping(value = {"/nivel/{id}", "/list"}, method = RequestMethod.GET)
public ModelAndView getNivel(@PathVariable("id") Optional<Long> id) {
ModelAndView view = new ModelAndView("nivel/list");
if (id.isPresent()) {
Nivel nivel = nivelService.findById(id.get());
view.addObject("niveis", Arrays.asList(nivel));
} else {
List<Nivel> niveis = nivelService.findAll();
view.addObject("niveis", niveis);
Page<Nivel> page = nivelService.findByPagination(0, 5);
view.addObject("page", page);
view.addObject("urlPagination", "/nivel/page");
}
return view;
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute("nivel") @Validated Nivel nivel, BindingResult result) {
ModelAndView view = new ModelAndView();
if ( result.hasErrors() ) {
Page<Nivel> page = nivelService.findByPagination(0, 5);
view.addObject("page", page);
view.addObject("urlPagination", "/categoria/page");
view.setViewName("categoria/cadastro");
return view;
}
nivelService.saveOrUpdate(nivel);
view.setViewName("redirect:/nivel/add");
return view;
}
}