Spring + Thymeleaf creates new record instead of updating - spring-mvc

I am trying to update an existing record but instead, it creates a new record even though the primary key is not a null value. Also, the subject field is returning null. I'm using the CrudRepository from spring framework.
What I want to happen is for it to update in the database instead of creating, the subject field should return Math, Science, or English.
Below is my input form, controller, Entity, DTO, and service implementation.
What am I doing wrong since my other input form for users uses the same code
edit.html
<form th:method="PUT" th:action="#{~/teacher/edit}" th:object="${grades}">
<input type="hidden" name="id" th:field="*{id}">
<input type="hidden" name="studentID" th:field="*{studentID}">
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="quiz1" class="col-form-label">Quiz 1:</label></div>
<div class="col-xl-3"><input id="quiz1" type="text" th:field="*{quiz1}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="quiz2" class="col-form-label">Quiz 2:</label></div>
<div class="col-xl-3"><input id="quiz2" type="text" th:field="*{quiz2}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="quiz3" class="col-form-label">Quiz 3:</label></div>
<div class="col-xl-3"><input id="quiz3" type="text" th:field="*{quiz3}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="quiz4" class="col-form-label">Quiz 4:</label></div>
<div class="col-xl-3"><input id="quiz4" type="text" th:field="*{quiz4}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="quiz5" class="col-form-label">Quiz 5:</label></div>
<div class="col-xl-3"><input id="quiz5" type="text" th:field="*{quiz5}">
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="hw1" class="col-form-label">Homework 1:</label></div>
<div class="col-xl-3"><input id="hw1" type="text" th:field="*{hw1}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="hw2" class="col-form-label">Homework 2:</label></div>
<div class="col-xl-3"><input id="hw2" type="text" th:field="*{hw2}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="hw3" class="col-form-label">Homework 3:</label></div>
<div class="col-xl-3"><input id="hw3" type="text" th:field="*{hw3}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="hw4" class="col-form-label">Homework 4:</label></div>
<div class="col-xl-3"><input id="hw4" type="text" th:field="*{hw4}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="hw5" class="col-form-label">Homework 5:</label></div>
<div class="col-xl-3"><input id="hw5" type="text" th:field="*{hw5}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="hw6" class="col-form-label">Homework 6:</label></div>
<div class="col-xl-3"><input id="hw6" type="text" th:field="*{hw6}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="hw7" class="col-form-label">Homework 7:</label></div>
<div class="col-xl-3"><input id="hw7" type="text" th:field="*{hw7}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="hw8" class="col-form-label">Homework 8:</label></div>
<div class="col-xl-3"><input id="hw8" type="text" th:field="*{hw8}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="exam1" class="col-form-label">Midterms:</label></div>
<div class="col-xl-3"><input id="exam1" type="text" th:field="*{exam1}"></div>
</div>
<div class="row" style="padding: 10px;">
<div class="col-xl-3"></div>
<div class="col-xl-5"><label for="exam2" class="col-form-label">Finals:</label></div>
<div class="col-xl-3"><input id="exam2" type="text" th:field="*{exam2}"></div>
</div>
<div class="mb-3">
<label for="subject" class="form-label">Subject</label>
<select id="subject" th:field="*{subject}">
<option th:value="Math" th:text="Math"></option>
<option th:value="English" th:text="English"></option>
<option th:value="Science" th:text="Science"></option>
<option selected th:value=null th:text="None"></option>
</select>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
TeacherController
#Controller
#RequestMapping("teacher")
public class TeacherController {
#Autowired
private AdminService adminService;
#Autowired
private GradesService gradesService;
#GetMapping
public String index(Model model){
model.addAttribute("users", adminService.list());
return "teacher/teacher";
}
#GetMapping("/section")
public String section(Model model){
model.addAttribute("users", adminService.list());
return "teacher/section";
}
#GetMapping("/edit")
public String edit(Model model){
model.addAttribute("users", adminService.list());
return "teacher/viewStudents";
}
#GetMapping("/{id}")
private String getUser(#PathVariable Long id, Model model) {
model.addAttribute("user", adminService.get(id));
model.addAttribute("grades", gradesService.get(id));
return "teacher/edit";
}
#PutMapping("/edit")
private String updateUser(GradesDTO gradesDTO, Model model) {
gradesService.update(gradesDTO);
return edit(model);
}
GradesEntity
#Entity
#Table(name="grades")
public class Grades {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
#ManyToOne
#JoinColumn(name="student_ID", nullable = false)
private User studentID;
#Column
private String subject;
#Column(columnDefinition = "BIGINT default '0'")
private Long quiz1 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long quiz2 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long quiz3 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long quiz4 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long quiz5 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long hw1 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long hw2 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long hw3 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long hw4 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long hw5 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long hw6 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long hw7 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long hw8 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long exam1 = 0L;
#Column(columnDefinition = "BIGINT default '0'")
private Long exam2 = 0L;
#Column(columnDefinition = "Double default '0.0'")
private Double weightQ = 0D;
#Column(columnDefinition = "Double default '0.0'")
private Double weightD = 0D;
#Column(columnDefinition = "Double default '0.0'")
private Double weightE = 0D;
public Grades(){
}
public Grades(Long id){
this.Id = id;
}
public Grades(GradesDTO gradesDTO){
this.studentID = new User(gradesDTO.getStudentID());
this.quiz1= gradesDTO.getQuiz1();
this.quiz2= gradesDTO.getQuiz2();
this.quiz3= gradesDTO.getQuiz3();
this.quiz4= gradesDTO.getQuiz4();
this.quiz5= gradesDTO.getQuiz5();
this.hw1=gradesDTO.getHw1();
this.hw2=gradesDTO.getHw2();
this.hw3=gradesDTO.getHw3();
this.hw4=gradesDTO.getHw4();
this.hw5=gradesDTO.getHw5();
this.hw6=gradesDTO.getHw6();
this.hw7=gradesDTO.getHw7();
this.hw8=gradesDTO.getHw8();
this.exam1=gradesDTO.getExam1();
this.exam2=gradesDTO.getExam2();
this.subject = gradesDTO.getSubject();
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public User getStudentID() {
return studentID;
}
public void setStudentID(User studentID) {
this.studentID = studentID;
}
public Long getQuiz1() {
return quiz1;
}
public void setQuiz1(Long quiz1) {
this.quiz1 = quiz1;
}
public Long getQuiz2() {
return quiz2;
}
public void setQuiz2(Long quiz2) {
this.quiz2 = quiz2;
}
public Long getQuiz3() {
return quiz3;
}
public void setQuiz3(Long quiz3) {
this.quiz3 = quiz3;
}
public Long getQuiz4() {
return quiz4;
}
public void setQuiz4(Long quiz4) {
this.quiz4 = quiz4;
}
public Long getQuiz5() {
return quiz5;
}
public void setQuiz5(Long quiz5) {
this.quiz5 = quiz5;
}
public Long getHw1() {
return hw1;
}
public void setHw1(Long hw1) {
this.hw1 = hw1;
}
public Long getHw2() {
return hw2;
}
public void setHw2(Long hw2) {
this.hw2 = hw2;
}
public Long getHw3() {
return hw3;
}
public void setHw3(Long hw3) {
this.hw3 = hw3;
}
public Long getHw4() {
return hw4;
}
public void setHw4(Long hw4) {
this.hw4 = hw4;
}
public Long getHw5() {
return hw5;
}
public void setHw5(Long hw5) {
this.hw5 = hw5;
}
public Long getHw6() {
return hw6;
}
public void setHw6(Long hw6) {
this.hw6 = hw6;
}
public Long getHw7() {
return hw7;
}
public void setHw7(Long hw7) {
this.hw7 = hw7;
}
public Long getHw8() {
return hw8;
}
public void setHw8(Long hw8) {
this.hw8 = hw8;
}
public Long getExam1() {
return exam1;
}
public void setExam1(Long exam1) {
this.exam1 = exam1;
}
public Long getExam2() {
return exam2;
}
public void setExam2(Long exam2) {
this.exam2 = exam2;
}
public Double getWeightQ() {
return weightQ;
}
public void setWeightQ(Double weightQ) {
this.weightQ = weightQ;
}
public Double getWeightD() {
return weightD;
}
public void setWeightD(Double weightD) {
this.weightD = weightD;
}
public Double getWeightE() {
return weightE;
}
public void setWeightE(Double weightE) {
this.weightE = weightE;
}
}
GradesDTO
public class GradesDTO {
private Long id;
private Long studentID;
private Long quiz1;
private Long quiz2;
private Long quiz3;
private Long quiz4;
private Long quiz5;
private Long hw1;
private Long hw2;
private Long hw3;
private Long hw4;
private Long hw5;
private Long hw6;
private Long hw7;
private Long hw8;
private Long exam1;
private Long exam2;
private Double weightQ;
private Double weightD;
private Double weightE;
private String subject;
public GradesDTO(){
}
public GradesDTO(Long Id, Long quiz1, Long quiz2, Long quiz3, Long quiz4, Long quiz5, Long hw1, Long hw2, Long hw3, Long hw4, Long hw5, Long hw6, Long hw7, Long hw8, Long exam1,
Long exam2, Double weightQ, Double weightD, Double weightE, String subject ){
this.id=Id;
this.quiz1=quiz1;
this.quiz2=quiz2;
this.quiz3=quiz3;
this.quiz4=quiz4;
this.quiz5=quiz5;
this.hw1=hw1;
this.hw2=hw2;
this.hw3=hw3;
this.hw4=hw4;
this.hw5=hw5;
this.hw6=hw6;
this.hw7=hw7;
this.hw8=hw8;
this.exam1=exam1;
this.exam2=exam2;
this.weightQ=weightQ;
this.weightD=weightD;
this.weightE=weightE;
this.subject=subject;
}
public GradesDTO(Grades grades){
this.id = grades.getId();
this.studentID = grades.getStudentID().getId();
this.quiz1 = grades.getQuiz1();
this.quiz2 = grades.getQuiz2();
this.quiz3 = grades.getQuiz3();
this.quiz4 = grades.getQuiz4();
this.quiz5 = grades.getQuiz5();
this.hw1 = grades.getHw1();
this.hw2 = grades.getHw2();
this.hw3 = grades.getHw3();
this.hw4 = grades.getHw4();
this.hw5 = grades.getHw5();
this.hw6 = grades.getHw6();
this.hw7 = grades.getHw7();
this.hw8 = grades.getHw8();
this.exam1 = grades.getExam1();
this.exam2 = grades.getExam2();
this.weightD = grades.getWeightD();
this.weightQ = grades.getWeightQ();
this.weightE = grades.getWeightE();
this.subject = grades.getSubject();
}
public Long getStudentID() {
return studentID;
}
public void setStudentID(Long studentID) {
this.studentID = studentID;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getQuiz1() {
return quiz1;
}
public void setQuiz1(Long quiz1) {
this.quiz1 = quiz1;
}
public Long getQuiz2() {
return quiz2;
}
public void setQuiz2(Long quiz2) {
this.quiz2 = quiz2;
}
public Long getQuiz3() {
return quiz3;
}
public void setQuiz3(Long quiz3) {
this.quiz3 = quiz3;
}
public Long getQuiz4() {
return quiz4;
}
public void setQuiz4(Long quiz4) {
this.quiz4 = quiz4;
}
public Long getQuiz5() {
return quiz5;
}
public void setQuiz5(Long quiz5) {
this.quiz5 = quiz5;
}
public Long getHw1() {
return hw1;
}
public void setHw1(Long hw1) {
this.hw1 = hw1;
}
public Long getHw2() {
return hw2;
}
public void setHw2(Long hw2) {
this.hw2 = hw2;
}
public Long getHw3() {
return hw3;
}
public void setHw3(Long hw3) {
this.hw3 = hw3;
}
public Long getHw4() {
return hw4;
}
public void setHw4(Long hw4) {
this.hw4 = hw4;
}
public Long getHw5() {
return hw5;
}
public void setHw5(Long hw5) {
this.hw5 = hw5;
}
public Long getHw6() {
return hw6;
}
public void setHw6(Long hw6) {
this.hw6 = hw6;
}
public Long getHw7() {
return hw7;
}
public void setHw7(Long hw7) {
this.hw7 = hw7;
}
public Long getHw8() {
return hw8;
}
public void setHw8(Long hw8) {
this.hw8 = hw8;
}
public Long getExam1() {
return exam1;
}
public void setExam1(Long exam1) {
this.exam1 = exam1;
}
public Long getExam2() {
return exam2;
}
public void setExam2(Long exam2) {
this.exam2 = exam2;
}
public Double getWeightQ() {
return weightQ;
}
public void setWeightQ(Double weightQ) {
this.weightQ = weightQ;
}
public Double getWeightD() {
return weightD;
}
public void setWeightD(Double weightD) {
this.weightD = weightD;
}
public Double getWeightE() {
return weightE;
}
public void setWeightE(Double weightE) {
this.weightE = weightE;
}
public String getSubject() {
return subject;
}
public void setSubjectId(String subject) {
this.subject = subject;
}
}
GradesServiceImpl
#Service
public class GradesServiceImpl implements GradesService {
#Autowired
private GradesRepository gradesRepository;
#Autowired
AdminRepository adminRepository;
#Autowired
AdminServiceImpl adminServiceimpl;
#Override
public List<GradesDTO> list() {
return StreamSupport.stream(gradesRepository.findAll().spliterator(), false)
.map(GradesDTO::new)
.collect(Collectors.toList());
}
#Override
public void add(GradesDTO user) {
gradesRepository.save(new Grades(user));
}
#Override
public GradesDTO get(Long id) {
AdminDTO adminDTO = adminServiceimpl.get(id);
User user = new User(adminDTO);
return new GradesDTO(gradesRepository.findById(gradesRepository.findByStudentID(user).getId()).get());
}
#Override
public void update(GradesDTO updatedUser) {
Grades grades = new Grades(updatedUser);
gradesRepository.save(grades);
}
}

You are not correctly updating the record in the database. As per your code
#Override
public void update(GradesDTO updatedUser) {
Grades grades = new Grades(updatedUser);
gradesRepository.save(grades);
}
You are just trying to save new record into the table, as JPA is not aware about anything weather it already exists or not. Hence, everytime you are trying it saving a new record.
To properly update any record you need to first find it/fetch it from the database then do the modification into the fetched entity object.
Now either you can call save method on it or not , it will get saved automatically by JPA.
#Override
public void update(GradesDTO updatedUser) {
Grades recordToBeUpdated= gradesRepository.findById(pass_your_id_here);
//You can find your record which you want to update by any means ,Id is not neccesary.
//do the update on the fetched entity obbject
//recordToBeUpdated--> set new values
gradesRepository.save(recordToBeUpdated);
}

Related

Why iterate last data from ArrayList<>?

I get data from database perfectly and pass to the Thymeleaf(Template), but the problem is near mdl.addAttribute("number" ,request.getNumber()) in controller to detect last value from foreach loop iteration and send by model
Here down my code:
Dto
public interface ProfileDto {
public Integer getU_id();
public Integer getP_id();
public String getEmail();
public String getUsername();
public String getPassword();
public String getContact();
public String getDate();
public String getProfile();
public String getWebsite();
public String getBio();
public String getGender();
public String getPost();
}
Entity
#Entity
#Table(name = "request_master")
public class Request {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int req_id;
private int sender_id;
private int receiver_id;
private String status;
private String date;
#Transient
private int number;
// getter setter
}
Repository
public interface profileRepo extends JpaRepository<Request, Integer> {
#Query(nativeQuery = true, value = "SELECT * FROM registration_master rm INNER JOIN profile_master pm ON rm.u_id = pm.user_id WHERE rm.u_id != ?")
List<ProfileDto> findByIdUser(Integer Id);
public interface requestRepo extends JpaRepository<Request, Integer> {
#Query(nativeQuery = true, value="SELECT * FROM request_master WHERE sender_id = ? and receiver_id = ?")
List<Request> getSuggetionButton(Integer Sender_id, Integer Receiver_id);
}
Service
#Service
public class ServiceImpl implements Service {
#Autowired
private profileRepo profileRepo;
#Autowired
private requestRepo requestRepo;
#Override
public List<ProfileDto> getSuggestedList(Integer Id) {
return this.profileRepo.findByIdUser(Id);
}
#Override
public List<Request> getSuggestionButton(Integer Sender_id, Integer Receiver_id) {
return this.requestRepo.getSuggetionButton(Sender_id, Receiver_id);
}
}
Controller
#Controller
public class Controller {
#Autowired
private Service service;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model mdl, Request request) {
int SessionId = Integer.parseInt(session.getAttribute("uid").toString());
List<ProfileDto> Suggestion_list = service.getSuggestedList(SessionId);
for(ProfileDto Suggestion_id : Suggestion_list)
{
List<Request> Friend_request = this.service.getSuggestionButton(SessionId, Suggestion_id.getU_id());
if(Friend_request.size() > 0)
{
request.setNumber(Friend_request.size());
}
else
{
request.setNumber(0);
}
}
mdl.addAttribute("number" ,request.getNumber());
mdl.addAttribute("suggestionList", Suggestion_list);
return "post";
}
}
Thymeleaf
<div class="follow-user-list" th:each="suggetionFriend : ${suggestionList}">
<div class="follow-user clearfix" th:id="'follow-user'+${suggetionFriend.u_id}">
<img th:src="${suggetionFriend.profile}" alt="" class="profile-photo-sm pull-left" />
<div class="name clearfix">
<h5>
</h5>
<div class='follow-unfollow-btn' th:id="'follow-unfollow-button'+${suggetionFriend.u_id}">
<div th:text="${number}">
</div>
</div>
</div>
</div>
</div>
in below image 1 is for condition matched and find data and 0 is for condition not matched and not find data
In My output i can get only last iterate data in both user
Output:
Expected output:
I think problem is to pass data from controller to thymeleaf
If you have good idea to transfer value from Controller to Template tell me please
You should maintain request for each profile/user instead of having single request, what I mean by that is you should have number of request for each profileId/userId, you can maintain a map of profileId/userId and number of request for that profile/user, and use that map in your template, try to modify your code as below
Controller
#Controller
public class Controller {
#Autowired
private Service service;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model mdl, Request request) {
Map<Integer, Integer> profileToNoOfRequestMap = new HashMap<>();
int SessionId = Integer.parseInt(session.getAttribute("uid").toString());
List<ProfileDto> Suggestion_list = service.getSuggestedList(SessionId);
for(ProfileDto Suggestion_id : Suggestion_list)
{
List<Request> Friend_request = this.service.getSuggestionButton(SessionId, Suggestion_id.getU_id());
profileToNoOfRequestMap.put(Suggestion_id.getU_id(), Friend_request.size());
}
mdl.addAttribute("profileToNoOfRequestMap", profileToNoOfRequestMap);
mdl.addAttribute("suggestionList", Suggestion_list);
return "post";
}
}
Thymeleaf
<div class="follow-user-list" th:each="suggetionFriend : ${suggestionList}">
<div class="follow-user clearfix" th:id="'follow-user'+${suggetionFriend.u_id}">
<img th:src="${suggetionFriend.profile}" alt="" class="profile-photo-sm pull-left" />
<div class="name clearfix">
<h5>
</h5>
<div class='follow-unfollow-btn' th:id="'follow-unfollow-button'+${suggetionFriend.u_id}">
<div th:text="${profileToNoOfRequestMap.get(suggetionFriend.u_id)}">
</div>
</div>
</div>
</div>
</div>

Etat HTTP 400 - Required String parameter 'color' is not present in spring mvc controller?

First the modal of team Update where Team is an entity in my spring mvc application Then The controller method and the updateTeam method implementation:
Here is the code:
<div class="modal fade" id="update-team-modal_${t.id}" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5>Modification Equipe</h5>
</div>
<div class="modal-body">
<form enctype="multipart/form-data" method="POST"
action="updateTeam" onsubmit="return validateTeamUpdate();">
<div class="form-group">
<input id="id" type="hidden" name="id" class="form-control"
value="${t.id}">
</div>
<div class="form-group">
<label for="name">Nom </label><span class="req">*</span>
<div class="input-group">
<input type="text" name="name" id="name"
class="form-control-large" value="${t.name }" autocomplete="off"
required="required" />
</div>
</div>
<div class="form-group">
<label for="color">Couleur</label><span class="req">*</span> <input
type="text" id="color" name="color" class="form-control demo"
style="width: 200px;"
data-swatches="#fff|#000|#f00|#0f0|#00f|#ff0|#0ff"
required="required" value="${t.color }">
</div>
<div class="form-group">
<label for="validateur">Validateur</label> <span class="req">*
</span> <select class="form-control-small" id="validateur"
name="validateur" required="required">
<option value="${t.validateur.matricule}">${t.validateur.firstName
} ${t.validateur.lastName }</option>
<c:forEach var="u" items="${users}">
<option value="${u.matricule}">${u.firstName}
${u.lastName}</option>
</c:forEach>
</select>
</div>
<div class="modal-footer">
<button class="btn btn-ok" type="submit"
style="background-color: #C6172E; color: white;">
<i class="glyphicon glyphicon-ok"></i>Editer
</button>
<button class="btn"
style="background-color: #5A6B80; color: white;"
data-dismiss="modal" onclick="this.form.reset();">
<i class="glyphicon glyphicon-remove"></i>Annuler
</button>
</div>
</form>
</div>
</div>
</div>
</div>
#RequestMapping(value = "/updateTeam", method = RequestMethod.POST)
public ModelAndView updateTeam(#RequestParam("id") long id,
#RequestParam("name") String name,
#RequestParam("validateur") String validateur,#RequestParam("color")String color) {
Team team = teamService.getById(id);
User validant = null;
if (!validateur.equals("null"))
validant = userService.getByMatricule(validateur);
team.setName(name);
team.setColor(color);
team.setValidateur(validant);
teamService.updateTeam(team);
return new ModelAndView(new RedirectView("gestionEquipes"));
}
#Override
public void updateTeam(Team t) {
teamRepository.saveAndFlush(t);
}
Bad Request 400
Etat HTTP 400 - Required String parameter 'color' is not present in spring mvc controller? La requête envoyée par le client était syntaxiquement incorrecte.
Can someone give me an idea how to solve this problem?
package tn.softMaint.MiniPortail.entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import com.google.gson.annotations.Expose;
#Entity
#Table(name = "teams")
/**
*
* #author ajlassi
* Classe d'entité des équipes
* Les attributs avec l'annotation #Expose seront exposés à GSON
*/
public class Team implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "team_id")
#Expose
private long id;
#Expose
#Column(unique = true)
#NotEmpty
private String name,color;
#Expose
private boolean isActif;
#ManyToOne(optional = false,fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#NotNull
private User validateur ;
#ManyToMany(fetch=FetchType.EAGER,mappedBy = "teams")
private List<User> members = new ArrayList<User>();
public Team() {
super();
}
public Team(String name, String color) {
super();
this.name = name;
this.color = color;
setIsActif(true);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean getIsActif() {
return isActif;
}
public void setIsActif(boolean isActif) {
this.isActif = isActif;
}
public User getValidateur() {
return validateur;
}
public void setValidateur(User validateur) {
this.validateur = validateur;
}
public List<User> getMembers() {
return members;
}
public void setMembers(List<User> members) {
this.members = members;
}
#Override
public String toString() {
return "Team [id=" + id + ", name=" + name + ", color=" + color
+ ", isActif=" + isActif + ", validateur=" + validateur
+ ", members=" + members + "]";
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Team other = (Team) obj;
if (id != other.id)
return false;
return true;
}
}
#RequestMapping(value = "/addTeam", method = RequestMethod.POST)
public ModelAndView addTeam(#RequestParam("name") String name,
#RequestParam("color") String color,
#RequestParam("validateur") String validateur,
RedirectAttributes redirectAttributes) {
User validant = null;
if (!validateur.equals("null"))
validant = userService.getByMatricule(validateur);
List<Team>teams=teamService.getAll();
boolean uniqueName=true;
boolean uniqueColor=true;
for (Team team : teams){
if (name.toLowerCase().equals(team.getName().toLowerCase()))
uniqueName = false;
if(color.equals(team.getColor()))
uniqueColor=false;
}
if (uniqueName == false)
redirectAttributes.addFlashAttribute("flashMessageErrorName", "error");
else if(uniqueColor==false)
redirectAttributes.addFlashAttribute("flashMessageErrorColor", "error");
else if((uniqueName==false)&&(uniqueColor==false))
redirectAttributes.addFlashAttribute("flashMessageError", "error");
else{
Team team = new Team(name, color);
team.setValidateur(validant);
boolean test = teamService.addTeam(team);
if (test == true)
redirectAttributes.addFlashAttribute("flashMessageAdd","success");
}
return new ModelAndView(new RedirectView("gestionEquipes"));
}

Selecting the option passed from the controller

I'm having trouble with the selection of the right value in a 'select' when the options are String. I can't find the solution in the forums.
I pass 'kind' in the controller and I can see that the values are fine but only the Integer fields are selected properly in the 'select'. The ones with String always show the first value and not the one pass in 'kind'.
I added the code I thought it could help
Can anyone help?
My HTML code. The form contains many 'select' but I left two, the first one works but the second one always show the first option:
<form role="form" th:action="#{/kind/update}" th:object="${kind}" method="post">
<div class="form-group col-md-4">
<label for="replicates">No. of Replicates</label>
<select id="replicates" class="form-control" style="width: 70%;" th:field="${kind.replicates}">
<option th:each="rep: ${replicatesnumber}" th:value="${rep}" th:text="${rep}"> </option>
</select>
</div>
<div class="form-group col-md-3">
<label for="substrate">Substrate</label>
<select id="substrate" class="form-control" th:field="${kind.substrate}">
<option th:each="substrate: ${substrates}" th:value="${substrate}" th:text="${substrate}"> </option>
</select>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Save</button>
<a class="btn btn-primary" th:href="#{/division/edit/}+${kind.division.id}" role="button">Cancel</a>
</div>
</form>
The controller look like this:
#Controller
#RequestMapping("/kind")
public class KindController {
#Autowired
private KindService kindService;
#ModelAttribute("replicatesnumber")
public int[] getReplicates() {
int[] reps = new int[3];
reps[0] = 2;
reps[1] = 4;
reps[2] = 8;
return reps;
}
#ModelAttribute("substrates")
public List<String> getSubstrates() {
return Arrays.asList("BP", "PP", "TP", "OGM", "Sand");
}
#GetMapping(value= "/edit/{kindId}")
public String viewDivision(#PathVariable Integer kindId, Model model){
Kind kind= kindService.findById(kindId);
model.addAttribute("kind",kind);
return "kind_edit";
}
and the entity:
#Entity
#Table(name = "kind", schema = "ostscourses")
public class Kind implements java.io.Serializable {
private Integer id;
private Division division;
private String name;
private Integer germinationDays;
private Integer firstCount;
private Integer replicates;
private Boolean dark;
private Integer chill;
private String temperature;
private String substrate;
private Integer noSeeds;
private List<Sample> samples;
public Kind() {
}
public Kind(Integer id, Division division) {
this.id = id;
this.division = division;
}
public Kind(Integer id, Division division, String name, Integer germinationDays, Integer firstCount, Integer replicates, Boolean dark, Integer chill, String temperature, String substrate, Integer noSeeds, List<Sample> samples) {
this.id = id;
this.division = division;
this.name = name;
this.germinationDays = germinationDays;
this.firstCount = firstCount;
this.replicates = replicates;
this.dark = dark;
this.chill = chill;
this.temperature = temperature;
this.substrate = substrate;
this.noSeeds = noSeeds;
this.samples = samples;
}
#Id
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "division_id", nullable = false)
#JsonIgnore
public Division getDivision() {
return this.division;
}
public void setDivision(Division division) {
this.division = division;
}
#Column(name = "name", length = 25)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "germination_days")
public Integer getGerminationDays() {
return this.germinationDays;
}
public void setGerminationDays(Integer germinationDays) {
this.germinationDays = germinationDays;
}
#Column(name = "first_count")
public Integer getFirstCount() {
return this.firstCount;
}
public void setFirstCount(Integer firstCount) {
this.firstCount = firstCount;
}
#Column(name = "replicates")
public Integer getReplicates() {
return this.replicates;
}
public void setReplicates(Integer replicates) {
this.replicates = replicates;
}
#Column(name = "dark")
public Boolean getDark() {
return this.dark;
}
public void setDark(Boolean dark) {
this.dark = dark;
}
#Column(name = "chill")
public Integer getChill() {
return this.chill;
}
public void setChill(Integer chill) {
this.chill = chill;
}
#Column(name = "temperature", length = 10)
public String getTemperature() {
return this.temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
#Column(name = "substrate", length = 5)
public String getSubstrate() {
return this.substrate;
}
public void setSubstrate(String substrate) {
this.substrate = substrate;
}
#Column(name = "no_seeds")
public Integer getNoSeeds() {
return this.noSeeds;
}
public void setNoSeeds(Integer noSeeds) {
this.noSeeds = noSeeds;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "kind")
#JsonIgnore
public List<Sample> getSamples() {
return this.samples;
}
public void setSamples(List<Sample> samples) {
this.samples = samples;
}
#Override
public int hashCode() {
int hash = 3;
hash = 47 * hash + Objects.hashCode(this.id);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Kind other = (Kind) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Kind{" + "id=" + id + ", name=" + name + ", germinationDays=" + germinationDays + ", firstCount=" + firstCount + ", replicates=" + replicates + ", dark=" + dark + ", chill=" + chill + ", temperature=" + temperature + ", substrate=" + substrate + ", noSeeds=" + noSeeds + '}';
}
}
Well, I just found a solution creating enum with the values I need in the select
public enum SubstrateType{
BP,
PP,
TP,
OGM,
Sand;
}
In my controller:
#ModelAttribute("substrates")
public SubstrateType[] getSubstrates() {
return SubstrateType.values();
}
I know it should work without enum as I have seen this before. Anyway I think is a good practice having enum.

Multiple select in thymeleaf + hibernate + spring boot

Hello guys I'm using thymeleaf 3 with spring boot and spring data jpa. But here is the problem. When I try to save I get this error from Hibernate:
Hibernate: insert into consulta (medico_id) values (?)
Hibernate: insert into consulta_pacientes (consulta_id, pacientes_id) values (?, ?)
2016-12-12 16:06:53.963 WARN 11912 --- [nio-9393-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1364, SQLState: HY000
2016-12-12 16:06:53.963 ERROR 11912 --- [nio-9393-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : Field 'pct_id' doesn't have a default value
2016-12-12 16:06:53.965 INFO 11912 --- [nio-9393-exec-9] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2016-12-12 16:06:53.976 ERROR 11912 --- [nio-9393-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not execute statement; nested exception is org.hibe
rnate.exception.GenericJDBCException: could not execute statement] with root cause
java.sql.SQLException: Field 'pct_id' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526) ~[mysql-connector-java-5.1.39.jar:5.1.39]
I already tried to use converter but didn't workout properly. Tried to look in this posts* ...but didn't solve either.
*1 http://forum.thymeleaf.org/th-selected-not-working-on-lt-select-gt-lt-option-gt-td4029201.html
*2
thymeleaf multiple selected on edit
Any tips? I'm kind of lost right now.
cadastro.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
...
<form action="#" th:action="#{salvar}" th:object="${consulta}" method="POST">
<div class="form-inline">
<label for="select-medico-consulta" class="form-group">Medico</label>
<select th:field="*{medico.id}" id="select-medico-consulta" >
<div>
<option th:each="medicoEntry : ${medicos}"
th:value="${medicoEntry.id}"
th:text="${medicoEntry.nome}"></option>
</div>
</select>
<div class="form-group">
<label id="paciente-label" for="select-paciente" > Paciente</label>
<select th:field="*{pacientes}" id="select-paciente" size="5" multiple="multiple" >
<div>
<option th:each="pacienteEntry : ${listaPacientes}"
th:field="*{pacientes}"
th:value="${pacienteEntry.id}"
th:text="${pacienteEntry.nome}"></option>
</div>
</select>
</div>
</div>
<div class="form-group">
<label for="comment">Consulta</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<button type="submit" class="btn btn-default">Salvar</button>
</form>
</div>
...
consultaController.java
package
and imports...
#Controller
#RequestMapping("/medclin")
public class ConsultaController {
#Autowired
private ConsultaDao consultadao;
#Autowired
private MedicoDao medicoDao;
#Autowired
private PacienteDao pacienteDao;
#RequestMapping("/consulta")
public ModelAndView Consulta() {
ModelAndView modelAndView = new ModelAndView("consulta/consulta");
ArrayList<Medico> medicos = (ArrayList<Medico>) medicoDao.findAll();
ArrayList<Paciente> pacientes = (ArrayList<Paciente>) pacienteDao.findAll();
modelAndView.addObject("medicos", medicos);
modelAndView.addObject("listaPacientes", pacientes);
modelAndView.addObject("consulta", new Consulta());
return modelAndView;
}
#RequestMapping(value = "/salvar", method = RequestMethod.POST)
public String salvar(#ModelAttribute Consulta consulta) {
consultadao.save(consulta);
return "redirect:medclin/home";
}
}
consultaDao.java
package br.com.medclin.boot.daos;
import java.io.Serializable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import br.com.medclin.boot.models.Consulta;
#Repository
public interface ConsultaDao extends CrudRepository<Consulta , Integer>
{
}
EDIT:
as asked by #bphilipnyc
Paciente.java
#Entity
public class Paciente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String nome;
private Calendar dataNascimento;
private String endereco;
#NotNull
private String cpf;
#ManyToOne
private Plano planoDeSaude;
public Paciente(String nome, Calendar dataNascimento, String endereco, String cpf, Plano plano) {
super();
this.nome = nome;
this.dataNascimento = dataNascimento;
this.endereco = endereco;
this.cpf = cpf;
this.planoDeSaude = plano;
}
public Paciente(String nome, Calendar dataNascimento, String endereco, String cpf) {
super();
this.nome = nome;
this.dataNascimento = dataNascimento;
this.endereco = endereco;
this.cpf = cpf;
}
public Paciente(String pctCpf) {
this.cpf = pctCpf;
}
public Paciente() {
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Calendar getDataNascimento() {
return this.dataNascimento;
}
public void setDataNascimento(Calendar dataNascimento) {
this.dataNascimento = dataNascimento;
}
public String getEndereco() {
return this.endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getCpf() {
return this.cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Plano getPlanoDeSaude() {
return planoDeSaude;
}
public void setPlanoDeSaude(Plano planoDeSaude) {
this.planoDeSaude = planoDeSaude;
}
public boolean equals(Paciente pct) {
if (this.id == pct.id)
return true;
else
return false;
}
#Override
public int hashCode() {
return super.hashCode();
}
#Override
public String toString() {
return "Paciente [id=" + id + ", nome=" + nome + ", dataNascimento=" + dataNascimento + ", endereco=" + endereco
+ ", cpf=" + cpf + ", planoDeSaude=" + planoDeSaude + "]";
}
}
The problem was solved. It seems that if you change your hibernate mapping, you must recreate the database. I did that and the problem was solved.

springboot + thymeelaf form handling with select and object

Hello there,
I'm facing a problem - for several days now- that is: I need to save a form with a select/option that contains a reference to another class...but when the controller tries to save it fails. The console shows me nothing...any tips?
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Dec 11 17:00:10 BRST 2016
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='consulta'. Error count: 1
The form cadastro.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
<div th:replace="includes/header :: menu"></div>
<div id="consu" class="container">
<form action="#" th:action="#{salvar}" th:object="${consulta}" method="POST">
<div class="form-inline">
<label for="select-medico-consulta" class="form-group">Medico</label>
<select id="select-medico-consulta" th:field="*{medico}">
<div>
<option th:each="medico : ${medicos}" th:value="${medico}"
th:text="${medico.nome}" ></option>
</div>
</select>
<div class="form-group">
<label id="paciente-label" for="select-paciente-consulta" > Paciente</label>
</div>
</div>
<div class="form-group">
<label for="comment">Consulta</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<div class="checkbox">
<label>
<input type="checkbox"/> Internado
</label>
</div>
<button type="submit" class="btn btn-default">Salvar</button>
</form>
</div>
<div th:fragment="footer">
<p class="rodape">
<img class="img-responsive" src="/img/logo.jpg"
th:src="#{/img/logo.jpg}" alt="error" />
</p>
</div>
</body>
</html>
ConsultaController
#Controller
#RequestMapping("/medclin")
public class ConsultaController {
#Autowired
private ConsultaDao consultadao;
#Autowired
private MedicoDao medicoDao;
#Autowired
private PacienteDao pacienteDao;
#RequestMapping("/consulta")
public ModelAndView Consulta() {
ModelAndView modelAndView = new ModelAndView("consulta/consulta");
ArrayList<Medico> medicos = (ArrayList<Medico>) medicoDao.findAll();
ArrayList<Paciente> pacientes = (ArrayList<Paciente>) pacienteDao.findAll();
modelAndView.addObject("medicos", medicos);
modelAndView.addObject("pacientes", pacientes);
modelAndView.addObject("consulta", new Consulta());
return modelAndView;
}
#RequestMapping(value = "/salvar", method = RequestMethod.POST)
public String salvar(#ModelAttribute Consulta consulta) {
consultadao.save(consulta);
return "redirect:medclin/home";
}
}
the Model, consulta.java
#Entity
public class Consulta {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#ManyToOne
private Medico medico;
#ManyToMany
#JoinTable(name = "CONSULTA_PACIENTES")
private List<Paciente> pacientes = new ArrayList<>();
#ManyToMany
#JoinTable(name = "CONSULTA_RECEITA")
private List<Receita> receita = new ArrayList<>();
public Consulta(Medico med, List<Paciente> paciente) {
this.medico = med;
this.pacientes = paciente;
}
public Consulta() {
}
public Consulta(Medico medico2) {
this.medico = medico2;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<Paciente> getPct() {
return pacientes;
}
public void setPct(List<Paciente> pct) {
this.pacientes = pct;
}
public Medico getMedico() {
return medico;
}
public void setMedico(Medico medico) {
this.medico = medico;
}
public List<Receita> getReceita() {
return receita;
}
public void setReceita(List<Receita> receita) {
this.receita = receita;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((medico == null) ? 0 : medico.hashCode());
result = prime * result + ((pacientes == null) ? 0 : pacientes.hashCode());
result = prime * result + ((receita == null) ? 0 : receita.hashCode());
return result;
}
//TODO corrigir esse erro
public boolean equals(Consulta cons) {
if (this.id == cons.getId())
return true;
else
return false;
}
#Override
public String toString() {
return "Consulta [id=" + id + ", medico=" + medico + ", pacientes=" + pacientes + ", receita=" + receita + "]";
}
}
Try
<select id="select-medico-consulta" th:field="*{medico.id}">
<option th:each="medicoEntry : ${medicos}" th:value="${medicoEntry.id}"
th:text="${medicoEntry.nome}" ></option>
</select>

Resources