Issue
let me explain better. I am creating a CRUD project in Spring MVC; as I am making some changes to the code, initially the method of interest was integer type. I put the code below for you to understand better.
public int delete(int studentId) {
String sql = "delete from student1 where stu_id=?";
try {
int counter = jdbcTemplate.update(sql, new Object[] { studentId });
return counter;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
Now I have to create it as a boolean. I tried to do it in the following way:
public boolean delete(int studentId) {
String sql = "delete from student1 where stu_id=?";
boolean status=false;
try {
status = jdbcTemplate.update(sql, new Object[] { studentId });
} catch (Exception e) {
e.printStackTrace();
return status;
}
}
it just gives me an error on
jdbcTemplate.update (sql, new Object [] {studentId})
because jdbcTemplate.update returns an integer. How can I change this? Thank you all
Solution
You can not convert int to boolean directly but we can say that if the integer value is greater than equal to 1 set the boolean value as true, otherwise set boolean as false.
For an int, any non-zero value evaluates to true, while zero evaluates to false.
Also jdbcTemplate.update()
returns an int
not a boolean
value , 1 if query was successful otherwise 0.
You can try it like this
public boolean delete(int studentId) {
String sql = "delete from student1 where stu_id=?";
boolean statusFlag = true;
int status = 0;
try {
status = jdbcTemplate.update(sql, new Object[] { studentId });
if(status >= 1 || status < 0){
statusFlag = true;
}
else{
statusFlag = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return statusFlag;
}
}
Or a simpler way
return status !=0;
Answered By - Dren
Answer Checked By - Willingham (JavaFixing Volunteer)