I have made dropwizzard application using jdbi2. I am doing an update on my table and have annotated the dao method which does this with @GetGeneratedKeys and return type int. The documentation here says
If the return type is int, then the value will be the number of rows changed. Alternatively, if the method is annotated with @GetGeneratedKeys, then the return value with be the auto-generated keys. The insert method returns me correct 'id'. But my dao update method always returns me 0. Is there anything wrong here?
Here is my table
CREATE TABLE `User` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`FIRSTNAME` varchar(30) DEFAULT NULL,
`LASTNAME` varchar(30) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
This is my POJO
@Data
@Builder
@AllArgsConstructor
public class User {
@JsonProperty
private int id;
@JsonProperty
private String firstName;
@JsonProperty
private String lastName;
}
Here is my dao class with dao method to update
@RegisterMapper(UserMapper.class)
public interface UserDao {
@SqlUpdate("Insert into User (FIRSTNAME, LASTNAME) values (:firstName, :lastName)")
@GetGeneratedKeys
int insert(@BindBean User user); //returns correct autogenerated id
@SqlUpdate("Update User set FIRSTNAME = :firstName," +
"LASTNAME = :lastName where ID = :id")
@GetGeneratedKeys
int update(@BindBean User User); //Shouldn't it return the id of updated user?
}
And here is my resource class:
@Path("/user")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public class UserResource {
UserDao dao;
public UserResource(UserDao UserDao)
{
this.dao = UserDao;
}
@POST
public User add(@Valid User user) {
int i = dao.insert(user); //returns correct autogenerated id
user.setId(i);
return user;
}
@PUT
@Path("/{id}")
public User update(@PathParam("id") Integer id, @Valid User user) {
User updateUser = new User(id, user.getFirstName(),user.getLastName());
int i = dao.update(updateUser); // --> i is always 0, why?
System.out.println(i);
return updateUser;
}
}
I am sending request using postman in this way:
Put: localhost:7466/user/5
Body:(JSON/application/json) {
"firstName": "new_first_name",
"lastName": "new_last_name"
}
Please comment if anything is not clear. TIA
EDIT : Shouldn't I get at least the number of rows updated here? I am getting 0 always.