Reputation: 89
My Table:
Emotion |
---|
EID (Primary Key) |
user_mood |
Latitude |
Longitude |
uid |
@Entity
public class Emotion
{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer eId;
@Column(name = "user_mood")
private String mood;
private String latitude;
private String longitude;
private String uid;
}
My Interface:
public interface EmotionRepository extends JpaRepository<Emotion, String>{}
When I try to fetch values using uid emotionRepo.findById(uid) I am getting below type mismatch error
Error message:
org.hibernate.TypeMismatchException: Provided id of the wrong type for class mood_sensor.mood_sensor.pojos.Emotion. Expected: class java.lang.Integer, got class java.lang.String
Can I retrieve data using uid or I should use only the primaryKey(Integer) to retrieve data?
Upvotes: 0
Views: 1812
Reputation: 3370
Yes, it's possible, but the method findById
, from CrudRepository<T, ID>
always expect to receive the ID as the argument - see here (be aware that JpaRepository
extends from CrudRepository
).
You can query by another field in a variety of ways, but as I saw that your use case is pretty simple, I'd suggest you to make use of Spring Data's query creation deriving from the method's name - see here and here
It's really simple, just create a method called findByUid
in your EmotionRepository
and Spring will take care of the rest by deriving the desired query from the method's name:
public interface EmotionRepository extends JpaRepository<Emotion, Integer> {
Optional<Emotion> findByUid(String uid);
}
Spring Data will then generate something like the following query:
SELECT e.* FROM Emotion e WHERE e.uid = <the-value>
Now, you can use findByUid
method to query using the uid
field.
And another fix: change from
EmotionRepository extends JpaRepository<Emotion, String>
to
EmotionRepository extends JpaRepository<Emotion, Integer>
this is because the id from Emotion
is of type Integer
, not String
.
Upvotes: 2
Reputation: 844
Inside your JpaRepository
(EmotionRepository
), you can make a function signature, anmd and the JPA will create a method to fetch whatever data you need.
This doc should help you understand exactly what is happening: http://static.springsource.org/spring-data/data-jpa/docs/1.0.0.M1/reference/html/#jpa.query-methods.query-creation
Upvotes: 0