My project is about a User-Manager web.
I'm a new in Spring and Java.
Here is my code:In the UserController
@RequestMapping(value="/users/{name}",method = RequestMethod.GET)
public User showUser(@PathVariable("name") String name){
return userService.findUser(name);
}
In the UserService:
public User findUser(String name){
return userRepository.findOne(name);
}
And in the Postman when I go to the link:http://localhost:8080/users/hunghip4 (hunghip4 is a user I created)
{
"timestamp": 1460570912129,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
"message": "Provided id of the wrong type for class com.uet.dhqg.usermanage.model.User. Expected: class java.lang.Integer, got class java.lang.String; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class com.uet.dhqg.usermanage.model.User. Expected: class java.lang.Integer, got class java.lang.String",
"path": "/users/hunghip4"
}
The User model:
@Entity
@Table(name="user")
public class User extends HypermediaLinks {
@Id
@Column(name="id")
private int id;
@Column(name="name")
private String name;
@Column(name="pass")
private String pass;
public int getId(){
return id;
}
public String getName(){
return name;
}
public void serName(String name){
this.name = name;
}
public String getPass(){
return pass;
}
public void serPass(String pass){
this.pass = pass;
}
}
The UserRepository:
@Repository
public interface UserRepository extends CrudRepository<User,String>{
}
The findOne is used to find entities based on ID not on any random field of your entity.
findOne() is defined as <S extends T> Optional<S> findOne(Example<S> example); . It means that in your case it accepts a Example<Reader> and returns an Optional<Reader> .
Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.
Your UserRepository
is defined as CrudRepository<User,String>
. Where User
is the type and String
the type of the id. However your User
class has an id field of the type int
NOT of type String
.
First fix your UserRepository
to be a proper representation of your User
.
public interface UserRepository extends CrudRepository<User, Integer> {}
Next create a method to find your User
by name.
public User findByName(String name);
And call this from your controller instead of findOne
. The findOne
is used to find entities based on ID not on any random field of your entity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With