我的表:
情感 |
---|
EID(主键) |
user_mood |
纬度 |
经度 |
用户名 |
@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;
}
我的界面:
public interface EmotionRepository extends JpaRepository<Emotion, String>{}
当我尝试使用 uid 获取值时 emotionRepo.findById(uid) 我收到以下类型不匹配错误
错误信息:
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
我可以使用 uid 检索数据还是应该只使用 primaryKey(Integer) 来检索数据?
答案 0 :(得分:1)
是的,这是可能的,但是方法 findById
, from CrudRepository<T, ID>
总是期望接收 ID 作为参数 - 请参阅 here(请注意JpaRepository
扩展自 CrudRepository
)。
您可以通过多种方式通过另一个字段进行查询,但正如我看到您的用例非常简单,我建议您利用源自方法名称的 Spring Data 查询创建 - 请参阅 here 和 here
这真的很简单,只需在您的 findByUid
中创建一个名为 EmotionRepository
的方法,Spring 将通过从该方法的名称派生所需的查询来处理其余的工作:
public interface EmotionRepository extends JpaRepository<Emotion, Integer> {
Optional<Emotion> findByUid(String uid);
}
Spring Data 将生成类似于以下查询的内容:
SELECT e.* FROM Emotion e WHERE e.uid = <the-value>
现在,您可以使用 findByUid
方法使用 uid
字段进行查询。
另一个修正:从改变
EmotionRepository extends JpaRepository<Emotion, String>
到
EmotionRepository extends JpaRepository<Emotion, Integer>
这是因为来自 Emotion
的 id 属于 Integer
类型,而不是 String
。
答案 1 :(得分:0)
在您的 JpaRepository
(EmotionRepository
) 中,您可以创建函数签名和 anmd,JPA 将创建一个方法来获取您需要的任何数据。
此文档应该可以帮助您准确了解正在发生的事情:http://static.springsource.org/spring-data/data-jpa/docs/1.0.0.M1/reference/html/#jpa.query-methods.query-creation